Programing in C
Programing in C
ENGINEERING AND
TECHNOLOGY,Tiruttani
(An Autonomous Institution)
Accredited by NBA (ECE), NAAC with “A++” Grade &An ISO 9001:2015 Certified Institution
Approved by AICTE, New Delhi& Affiliated to Anna University, Chennai.
UNIX is an operating system which was first developed in the 1960s, and has been under
constant development ever since. By operating system, we mean the suite of programs which
make the computer work. It is a stable, multi-user, multi-tasking system for servers, desktops
and laptops.
UNIX systems also have a graphical user interface (GUI) similar to Microsoft Windows which
provides an easy to use environment. However, knowledge of UNIX is required for operations
which aren't covered by a graphical program, or for when there is no windows interface
available, for example, in a telnet session.
Types of UNIX
There are many different versions of UNIX, although they share common similarities. The
most popular varieties of UNIX are Sun Solaris, GNU/Linux, and MacOS X. Linux in its turn is
packaged in a form known as a Linux distribution. There are several Linux distributions, both
free and commercial.
ISU has a campus site subscription to Red Hat Enterprise Linux (RHEL), providing access for
university-owned equipment as well as personal access to students, faculty, and staff. All our
clusters are running RHEL.
The UNIX operating system
The UNIX operating system is made up of three parts; the kernel, the shell and the programs.
The kernel
The kernel of UNIX is the hub of the operating system: it allocates time and memory to
programs and handles the filestore and communications in response to system calls.
As an illustration of the way that the shell and the kernel work together, suppose a user
types rm myfile (which has the effect of removing the file myfile). The shell searches the
filestore for the file containing the program rm, and then requests the kernel, through system
calls, to execute the program rm on myfile. When the process rm myfile has finished running,
the shell then returns the UNIX prompt % to the user, indicating that it is waiting for further
commands.
The shell
The shell acts as an interface between the user and the kernel. When a user logs in, the login
program checks the username and password, and then starts another program called the shell.
The shell is a command line interpreter (CLI). It interprets the commands the user types in and
arranges for them to be carried out. The commands are themselves programs: when they
terminate, the shell gives the user another prompt (% on our systems).
The adept user can customise his/her own shell, and users can use different shells on the same
machine. Most accounts on our clusters have the bash shell by default. The accounts on hpc-
class use shell specified at https://asw.iastate.edu/cgi-bin/acropolis/user/shell .
The bash and tcsh shells have certain features to help the user inputting commands.
Filename Completion - By typing part of the name of a command, filename or directory and
pressing the [Tab] key, the shell will complete the rest of the name automatically. If the shell
finds more than one name beginning with those letters you have typed, it will beep, prompting
you to type a few more letters before pressing the tab key again.
History - The shell keeps a list of the commands you have typed in. If you need to repeat a
command, use the cursor keys to scroll up and down the list or type history for a list of previous
commands.
What is Linux?
Linux is a free and open-source family of operating systems that is resilient and flexible. In 1991,
an individual by the name as Linus Torvalds constructed it. The system’s source code is
accessible to everyone for anyone to look at and change, making it cool that anyone can see how
the system works. People from all across the world are urged to work together and keep
developing Linux due to its openness.
Since the beginning, Linux has grown into a dependable and safe OS that is used in an array of
gadgets, including PCs, cell phones, and huge supercomputers. It is well-known for being cost-
effective, which implies that employing it doesn’t cost a lot, and efficient, which indicates it can
complete a lot of jobs quickly.
What is Linux Operating System?
Developed by Linus Torvalds in 1991, the Linux operating system is a powerful and flexible
open-source software platform. It acts as the basis for a variety of devices, such embedded
systems, cell phones, servers, and personal computers. Linux, that’s well-known for its reliability,
safety, and flexibility, allows users to customize and improve their environment to suit specific
needs. With an extensive and active community supporting it, Linux is an appealing choice for
people as well as companies due to its wealth of resources and constant developments.
Difference Between Unix and Linux
Linux is essentially a clone of Unix. But, basic differences are shown below:
Linux Unix
The source code of Linux is freely The source code of Unix is not freely
available to its users available general public
The Linux kernel is monolithic, meaning The Unix kernel is modular, meaning that
that all of its services are provided by a it is made up of a collection of
single kernel. independent modules that can be loaded
and unloaded dynamically.
Shell Programming
A shell script is a computer program designed to be run by the Unix/Linux shell which could be one
of the following:
The Bourne Shell
The C Shell
The Korn Shell
The GNU Bourne-Again Shell
A shell is a command-line interpreter and typical operations performed by shell scripts include file
manipulation, program execution, and printing text.
Extended Shell Scripts
Shell scripts have several required constructs that tell the shell environment what to do and when to
do it. Of course, most scripts are more complex than the above one.
The shell is, after all, a real programming language, complete with variables, control structures, and
so forth. No matter how complicated a script gets, it is still just a list of commands executed
sequentially.
The following script uses the read command which takes the input from the keyboard and assigns it
as the value of the variable PERSON and finally prints it on STDOUT.
#!/bin/sh
# Author : Zara Ali
# Copyright (c) Tutorialspoint.com
# Script follows here:
echo "What is your name?"
read PERSON
echo "Hello, $PERSON"
2. Preprocessor Directives
Preprocessors are programs that process the source code before the actual compilation begins. It
is not the part of compilation, but a separate process that allows programmers to modify the code
before compilation. It is the first process that the C source code goes through while being
converted to executable file.
Preprocessor Directives
The preprocessor directives are the instructions to the preprocessor for doing some tasks such as
text substitutions, macro expansions, including header files, and many more before compiling the
code. All of these preprocessor directives begin with a ‘#’ hash symbol.
One of the most commonly used preprocessors is #include which is used to include the header
files for different libraries in C programs. C provides more directives for different functionalities.
ist of Preprocessor Directives
The following table lists all the preprocessor directives in C:
Preprocessor Directives Description
// Macro Definition
#define LIMIT 5
int main(){
for (int i = 0; i < LIMIT; i++) {
printf("%d \n", i);
}
return 0;
}
In the above program, before the compilation begins, the word LIMIT is replaced with 5. The
word ‘LIMIT’ in the macro definition is called a macro template and ‘5’ is macro expansion.
Note There is no semi-colon (;) at the end of the macro definition. Macro definitions do not need
a semi-colon to end.
There are also some Predefined Macros in C which are useful in providing various functionalities
to our program.
A macro defined previously can be undefined using #undef preprocessor. For example, in the
above code,
#include <stdio.h>
// Macro Definition
#define LIMIT 5
// Undefine macro
#undef LIMIT
int main(){
for (int i = 0; i < LIMIT; i++) {
printf("%d \n", i);
}
return 0;
}
int main(){
int a = 10, b = 5;
File Inclusion
File inclusion allows you to include external files (header files, libraries, etc.) into the current
program. This is typically done using the #include directive, which can include both system and
user-defined files.
Syntax
There are two ways to include header files.
#include <file_name>
#include “filename”
The ‘<‘ and ‘>’ brackets tell the compiler to look for the file in the standard
directory while double quotes ( ” ” ) tell the compiler to search for the header file in the source
file’s directory.
Example:
// Includes the standard I/O library
#include <stdio.h>
int main() {
printf("Hello World");
return 0;
}
Conditional compilation allows you to include or exclude parts of the code depending on certain
conditions. This is useful for creating platform-specific code or for debugging. There are the following
conditional preprocessor directives: #if, #ifdef, #ifndef, else, #elif and #endif
Syntax
The general syntax of conditional preprocessors is:
#if
// some code
#elif
// some more code
#else
// Some more code
#endif
3. Compilation Process
The compilation is the process of converting the source code of the C language into machine
code. As C is a mid-level language, it needs a compiler to convert it into an executable code so
that the program can be run on our machine.
The C program goes through the following phases during compilation:
int main() {
char s[] = "Gfg";
Output
3
ii)strcpy()
The strcpy() function copies a string from the source to the destination. It copies the entire string,
including the null terminator.
Example:
#include <stdio.h>
#include <string.h>
int main() {
char src[] = "Hello";
char dest[20];
Output
Hello
iii)strncpy()
The strncpy() function is similar to strcpy(), but it copies at most n bytes from source to
destination string. If source is shorter than n, strncpy() adds a null character to destination to
ensure n characters are written.
Example:
#include <stdio.h>
#include <string.h>
int main() {
char src[] = "Hello";
char dest[20];
Output
Hell
iv)strcat()
The strcat() function is used to concatenate (append) one string to the end of another. It appends
the source string to the destination string, replacing the null terminator of the destination with the
source string’s content.
Example
#include <stdio.h>
#include <string.h>
int main() {
char s1[30] = "Hello, ";
char s2[] = "Geeks!";
Output
Hello, Geeks!
v)strncat()
In C, there is a function strncat() similar to strcat(). This function appends not more than n
characters from the string pointed to by source to the end of the string pointed to by destination
plus a terminating NULL character.
Example:
#include <stdio.h>
#include <string.h>
int main() {
char s1[30] = "Hello, ";
char s2[] = "Geeks!";
Output
Hello, Geek
vi)strcmp()
The strcmp() is a built-in library function in C. This function takes two strings as arguments,
compares these two strings lexicographically and returns an integer value as a result of
comparison.
Example
#include <stdio.h>
#include <string.h>
int main() {
char s1[] = "Apple";
char s2[] = "Applet";
Output
s1 is lexicographically greater than s2
vii)strncmp()
This function lexicographically compares the first n characters from the two null-terminated
strings and returns an integer based on the outcome.
Example:
#include <stdio.h>
#include <string.h>
int main() {
char s1[] = "Apple";
char s2[] = "Applet";
Output
s1 and s2 are same
viii)strchr()
The strchr() function is used to locate the first occurrence of a character in a string. If the
character is found, it returns a pointer to the first occurrence of the character; otherwise, it returns
NULL.
Example:
#include <stdio.h>
#include <string.h>
int main() {
char s[] = "Hello, World!";
if (res != NULL)
printf("Character found at: %ld index", res - s);
else
printf("Character not found\n");
return 0;
}
Output
Character found at: 4 index
ix)strrev()
The strrev() function is used find the reverse of a given string
Example:
#include <stdio.h>
#include <string.h>
int main() {
char s[] = "Hello";
printf(“%s”,,strrev(s));
Output
olleH