Cse 2nd Semester c Programming Notes Part 2
Cse 2nd Semester c Programming Notes Part 2
Prepared By:
Dr. Sujit Kumar Singh
Associate Professor,
Department of Computer Science & Engineering
STRUCTURE OF A C PROGRAM
Tokens in C
A C program consists of various tokens and a token is either a
keyword, an identifier, a constant, a string literal, or a symbol.
For example, the following C statement consists of five tokens −
printf("Hello, World! \n");
The individual tokens are −
printf("Hello, World! \n");
Semicolons
In a C program, the semicolon is a statement terminator. That
is, each individual statement must be ended with a semicolon.
It indicates the end of one logical entity.
Given below are two different statements −
printf("Hello, World! \n");
return 0;
Dr. Sujit Kumar Singh
C Program
Comments
Comments are like helping text in your C program and they are ignored by
the compiler. They start with /* and terminate with the characters */ as
shown below −
/* my first program in C */
You cannot have comments within comments and they do not occur within
a string or character literals.
Identifiers
A C identifier is a name used to identify a variable, function, or any other
user-defined item. An identifier starts with a letter A to Z, a to z, or an
underscore '_' followed by zero or more letters, underscores, and digits (0
to 9).
C does not allow punctuation characters such as @, $, and % within
identifiers. C is a case-sensitive programming language. Thus, Manpower
and manpower are two different identifiers in C. Here are some examples
of acceptable identifiers −
mohd zara abc move_name a_123
myname50 _temp j a23b9 retVal
Dr. Sujit Kumar Singh
C Program
Keywords
The following list shows the reserved words in C. These
reserved words may not be used as constants or variables or
any other identifier names.
auto else long switch break enum register
typedef
case extern return union char float short unsigned
const for signed void continuegoto sizeof volatile
defaultif static while do int struct _Packed
double
Whitespace in C
A line containing only whitespace, possibly with a comment, is
known as a blank line, and a C compiler totally ignores it.
Whitespace is the term used in C to describe blanks, tabs, newline
characters and comments. Whitespace separates one part of a
statement from another and enables the compiler to identify
where one element in a statement, such as int, ends and the next
element begins. Therefore, in the following statement −
int age;
there must be at least one whitespace character (usually a space)
between int and age for the compiler to be able to distinguish
them. On the other hand, in the following statement −
fruit = apples + oranges; // get the total fruit
no whitespace characters are necessary between fruit and =, or
between = and apples, although you are free to include some if
you wish to increase readability.
Dr. Sujit Kumar Singh
DATA TYPES IN C
int i, j, k;
char c, ch;
float f, salary;
double d; Dr. Sujit Kumar Singh
C VARIABLES
The line int i, j, k; declares and defines the variables i, j, and k; which
instruct the compiler to create variables named i, j and k of type int.
Variables can be initialized (assigned an initial value) in their
declaration. The initializer consists of an equal sign followed by a
constant expression as follows −
type variable_name = value;
Variable Declaration in C
A variable declaration provides assurance to the compiler that there
exists a variable with the given type and name so that the compiler
can proceed for further compilation without requiring the complete
detail about the variable. A variable definition has its meaning at the
time of compilation only, the compiler needs actual variable definition
at the time of linking the program.
A variable declaration is useful when you are using multiple files and
you define your variable in one of the files which will be available at
the time of linking of the program. You will use the keyword extern to
declare a variable at any place. Though you can declare a variable
multiple times in your C program, it can be defined only once in a file, a
function, or a block of code.
Dr. Sujit Kumar Singh
C VARIABLES
String Literals
String literals or constants are enclosed in double quotes "".
A string contains characters that are similar to character
literals: plain characters, escape sequences, and universal
characters.
You can break a long line into multiple lines using string
literals and separating them using white spaces.
Here are some examples of string literals. All the three forms
are identical strings.
"hello, dear"
"hello, \
dear"
"hello, " "d" "ear"
Defining Constants
There are two simple ways in C to define constants −
Using #define preprocessor.
Using const keyword.
The #define Preprocessor
Given below is the form to use #define preprocessor to
define a constant −
#define identifier value
The following example explains it in detail −
When the above code is compiled and executed, it produces the following
result −
value of area : 50
The const Keyword
You can use const prefix to declare constants with a specific type as follows
−
const type variable = value;
The following example explains it in detail −
#include <stdio.h>
int main() {
const int LENGTH = 10;
const int WIDTH = 5;
const char NEWLINE = '\n';
int area;
area = LENGTH * WIDTH;
printf("value of area : %d", area);
printf("%c", NEWLINE);
return 0;
} Dr. Sujit Kumar Singh
C - Storage Classes
#include <stdio.h>
/* function declaration */
void func(void);
static int count = 5; /* global variable */
main() {
while(count--) {
func();
}
return 0;
}
/* function definition */
void func( void ) {
When the above code is compiled and executed, it produces the following
result −
i is 6 and count is 4
i is 7 and count is 3
i is 8 and count is 2
i is 9 and count is 1
i is 10 and count is 0
The extern Storage Class
The extern storage class is used to give a reference of a global variable that
is visible to ALL the program files. When you use 'extern', the variable
cannot be initialized however, it points the variable name at a storage
location that has been previously defined.
When you have multiple files and you define a global variable or function,
which will also be used in other files, then extern will be used in another file
to provide the reference of defined variable or function. Just for
understanding, extern is used to declare a global variable or function in
another file.
The extern modifier is most commonly used when there are two or more
files sharing the same global
Dr.variables or functions
Sujit Kumar Singhas explained below.
C - OPERATORS
Relational Operators
The following table shows all the relational operators
supported by C. Assume variable A holds 10 and variable B
holds 20 then −
Logical Operators
Following table shows all the logical operators supported by
C language. Assume variable A holds 1 and variable B holds
0, then −
Bitwise Operators
Bitwise operator works on bits and perform bit-by-bit
operation. The truth tables for &, |, and ^ is as follows −
Assignment
Operators
The
following
table lists
the
assignment
operators
supported
by the C
language −
Operators Precedence in C
Operator precedence determines the grouping of terms in an
expression and decides how an expression is evaluated.
Certain operators have higher precedence than others; for
example, the multiplication operator has a higher precedence
than the addition operator.
For example, x = 7 + 3 * 2; here, x is assigned 13, not 20
because operator * has a higher precedence than +, so it first
gets multiplied with 3*2 and then adds into 7.
Here, operators with the highest precedence appear at the top
of the table, those with the lowest appear at the bottom.
Within an expression, higher precedence operators will be
evaluated first.
The ? : Operator
We have covered conditional operator ? : in the previous
chapter which can be used to replace if...else statements. It
has the following general form −
Exp1 ? Exp2 : Exp3;
Where Exp1, Exp2, and Exp3 are expressions. Notice the use
and placement of the colon.
The value of a ? expression is determined like this −
Exp1 is evaluated. If it is true, then Exp2 is evaluated and
becomes the value of the entire ? expression.
If Exp1 is false, then Exp3 is evaluated and its value
becomes the value of the expression.
Defining a Function
The general form of a function definition in C programming
language is as follows −
return_type function_name( parameter list ) {
body of the function
}
A function definition in C programming consists of a function
header and a function body. Here are all the parts of a
function −
Example
Given below is the source code for a function called max().
This function takes two parameters num1 and num2 and
returns the maximum value between the two −
/* function returning the max between two numbers */
int max(int num1, int num2) {
/* local variable declaration */
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
} Dr. Sujit Kumar Singh
FUNCTION IN C
Function Declarations
A function declaration tells the compiler about a function
name and how to call the function. The actual body of the
function can be defined separately.
A function declaration has the following parts −
return_type function_name( parameter list );
For the above defined function max(), the function
declaration is as follows −
int max(int num1, int num2);
Parameter names are not important in function declaration
only their type is required, so the following is also a valid
declaration −
int max(int, int);
}
Dr. Sujit Kumar Singh
FUNCTION IN C
Function Arguments
If a function is to use arguments, it must declare variables
that accept the values of the arguments. These variables are
called the formal parameters of the function.
Formal parameters behave like other local variables inside
the function and are created upon entry into the function and
destroyed upon exit.
While calling a function, there are two ways in which
arguments can be passed to a function −
Global Variables
Global variables are defined #include <stdio.h>
outside a function, usually on /* global variable declaration */
top of the program. Global int g;
variables hold their values int main () {
throughout the lifetime of your /* local variable declaration */
program and they can be int a, b;
/* actual initialization */
accessed inside any of the
a = 10;
functions defined for the
b = 20;
program.
g = a + b;
A global variable can be printf ("value of a = %d, b = %d
accessed by any function. That and g = %d\n", a, b, g);
is, a global variable is available return 0;
for use throughout your entire }
program after its declaration.
The following program show
how global variables are used
in a program.
Dr. Sujit Kumar Singh
SCOPE IN C
#include <stdio.h>
When the above
/* global variable declaration */
code is compiled
int a = 20;
and executed, it int main () {
produces the /* local variable declaration in main function
following result − */
value of g = 10 int a = 10;
int b = 20;
Formal int c = 0;
Parameters printf ("value of a in main() = %d\n", a);
Formal c = sum( a, b);
parameters, are printf ("value of c in main() = %d\n", c);
treated as local return 0;
variables with-in }
a function and /* function to add two integers */
they take int sum(int a, int b) {
precedence over printf ("value of a in sum() = %d\n", a);
global variables. printf ("value of b in sum() = %d\n", b);
Following is an
return a + b;
example −
} Dr. Sujit Kumar Singh
SCOPE IN C
Declaring Arrays
To declare an array in C, a programmer specifies the type of
the elements and the number of elements required by an
array as follows −type arrayName [ arraySize ];
This is called a single-dimensional array. The arraySize must
be an integer constant greater than zero and type can be
any valid C data type. For example, to declare a 10-element
array called balance of type double, use this statement −
double balance[10];
Here balance is a variable array which is sufficient to hold up
to 10 double numbers.
Initializing Arrays
You can initialize an array in C either one by one or using a
single statement as follows −
double balance[5] = {1000.0, 2.0, 3.4, 7.0, 50.0};
The number of values between braces { } cannot be larger
than the number of elements that we declare for the array
between square brackets [ ].
If you omit the size of the array, an array just big enough to
hold the initialization is created. Therefore, if you write −
double balance[] = {1000.0, 2.0, 3.4, 7.0, 50.0};
You will create exactly the same array as you did in the
previous example. Following is an example to assign a single
element of the array −
#include <stdio.h>
int main () {
int n[ 10 ]; /* n is an array of 10 integers */
int i,j;
/* initialize elements of array n to 0 */
for ( i = 0; i < 10; i++ ) {
n[ i ] = i + 100; /* set element at location i to i + 100 */
}
/* output each array element's value */
for (j = 0; j < 10; j++ ) {
printf("Element[%d] = %d\n", j, n[j] );
}
return 0;
} Dr. Sujit Kumar Singh
SCOPE IN C
Arrays in Detail
Arrays are important to C and should need a lot more
attention. The following important concepts related to array
should be clear to a C programmer −
#include <stdio.h>
int main () {
int var1;
char var2[10];
printf("Address of var1 variable: %x\n", &var1 );
printf("Address of var2 variable: %x\n", &var2 );
return 0;
}
#include <stdio.h>
int main () {
int *ptr = NULL;
printf("The value of ptr is : %x\n", ptr );
return 0;
}
When the above code is compiled and executed, it produces
the following result −
The value of ptr is 0−
struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
} book;
Accessing Structure Members
To access any member of a structure, we use the member
access operator (.). The member access operator is coded as
a period between the structure variable name and the
structure member that we wish to access. You would use the
keyword struct to define variables of structure type. The
following example shows how to use a structure in a program
−
Dr. Sujit Kumar Singh
C STRUCTURES
#include <stdio.h>
#include <string.h> strcpy( Book2.title, "Telecom Billing");
struct Books { strcpy( Book2.author, "Zara Ali");
char title[50]; strcpy( Book2.subject, "Telecom Billing
Tutorial");
char author[50];
Book2.book_id = 6495700;
char subject[100];
/* print Book1 info */
int book_id;
printf( "Book 1 title : %s\n", Book1.title);
};
printf( "Book 1 author : %s\n", Book1.author);
int main( ) {
printf( "Book 1 subject : %s\n", Book1.subject);
struct Books Book1; /*
Declare Book1 of type Book */ printf( "Book 1 book_id : %d\n",
Book1.book_id);
struct Books Book2; /*
/* print Book2 info */
Declare Book2 of type Book */
printf( "Book 2 title : %s\n", Book2.title);
/* book 1 specification */
printf( "Book 2 author : %s\n", Book2.author);
strcpy( Book1.title, "C
Programming"); printf( "Book 2 subject : %s\n", Book2.subject);
strcpy( Book1.author, "Nuha printf( "Book 2 book_id : %d\n",
Ali"); Book2.book_id);
Pointers to Structures
You can define pointers to structures in the same way as you
define pointer to any other variable −
struct Books *struct_pointer;
Now, you can store the address of a structure variable in the
above defined pointer variable. To find the address of a
structure variable, place the '&'; operator before the
structure's name as follows −
struct_pointer = &Book1;
To access the members of a structure using a pointer to that
structure, you must use the → operator as follows −
The memory occupied by a union will be large enough to hold the largest member
of the union. For example, in the above example, Data type will occupy 20 bytes of
memory space because this is the maximum space which can be occupied by a
character string. The following example displays the total memory size occupied by
the above union −
#include <stdio.h>
#include <string.h>
union Data {
int i;
float f;
char str[20];
};
int main( ) {
union Data data;
printf( "Memory size occupied by data : %d\n", sizeof(data));
return 0;
}
When the above code is compiled and executed,
Dr. Sujit Kumarit produces
Singh the following result −
C -unions
data.f = 220.5;
#include <stdio.h> printf( "data.f : %f\n", data.f);
#include <string.h>
strcpy( data.str, "C Programming");
union Data { printf( "data.str : %s\n", data.str);
int i;
return 0;
float f; }
char str[20]; When the above code is compiled and
executed, it produces the following
}; result −
int main( ) {
data.i : 10
union Data data; data.f : 220.500000
data.i = 10; data.str : C Programming
Closing a File
To close a file, use the fclose( ) function. The prototype of this
function is −
int fclose( FILE *fp );
The fclose(-) function returns zero on success, or EOF if there is
an error in closing the file. This function actually flushes any
data still pending in the buffer to the file, closes the file, and
releases any memory used for the file. The EOF is a constant
defined in the header file stdio.h.
There are various functions provided by C standard library to
read and write a file, character by character, or in the form of a
fixed length string.
Writing a File
Following is the simplest function to write individual characters
to a stream −
int fputc( int c, FILE *fpDr.
); Sujit Kumar Singh
C –FILE I/O
The function fputc() writes the character value of the argument c to the output
stream referenced by fp. It returns the written character written on success
otherwise EOF if there is an error. You can use the following functions to write a
null-terminated string to a stream −
int fputs( const char *s, FILE *fp );
The function fputs() writes the string s to the output stream referenced by fp. It
returns a non-negative value on success, otherwise EOF is returned in case of
any error. You can use int fprintf(FILE *fp,const char *format, ...) function as well
to write a string into a file. Try the following example.
Make sure you have /tmp directory available. If it is not, then before
proceeding, you must create this directory on your machine.
#include <stdio.h>
main() {
FILE *fp;
fp = fopen("/tmp/test.txt", "w+");
fprintf(fp, "This is testing for fprintf...\n");
fputs("This is testing for fputs...\n", fp);
fclose(fp);
} Dr. Sujit Kumar Singh
C –FILE I/O
When the above code is compiled and executed, it creates a new file
test.txt in /tmp directory and writes two lines using two different functions.
Let us read this file in the next section.
Reading a File
Given below is the simplest function to read a single character from a file −
int fgetc( FILE * fp );
The fgetc() function reads a character from the input file referenced by fp.
The return value is the character read, or in case of any error, it returns
EOF. The following function allows to read a string from a stream −
char *fgets( char *buf, int n, FILE *fp );
The functions fgets() reads up to n-1 characters from the input stream
referenced by fp. It copies the read string into the buffer buf, appending a
null character to terminate the string.
If this function encounters a newline character '\n' or the end of the file EOF
before they have read the maximum number of characters, then it returns
only the characters read up to that point including the new line character.
You can also use int fscanf(FILE *fp, const char *format, ...) function to read
strings from a file, but it stops reading after encountering the first space
character.}
Dr. Sujit Kumar Singh
C –FILE I/O
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
char name[100];
char *description;
strcpy(name, "Zara Ali");
/* allocate memory dynamically */
description = malloc( 200 * sizeof(char) );
if( description == NULL ) {
fprintf(stderr, "Error - unable to allocate required memory\n");
} else {
strcpy( description, "Zara ali a DPS student in class 10th");
}
printf("Name = %s\n", name );
printf("Description: %s\n", description );
} Dr. Sujit Kumar Singh
C –FILE I/O
When the above code is compiled and executed, it produces the
following result.
Name = Sony Singh
Description: Sony Singh DPS student in class 10th
Same program can be written using calloc(); only thing is you need to
replace malloc with calloc as follows −
calloc(200, sizeof(char));
So you have complete control and you can pass any size value while
allocating memory, unlike arrays where once the size defined, you
cannot change it.
Resizing and Releasing Memory
When your program comes out, operating system automatically release
all the memory allocated by your program but as a good practice when
you are not in need of memory anymore then you should release that
memory by calling the function free().
Alternatively, you can increase or decrease the size of an allocated
memory block by calling the function realloc(). Let us check the above
program once again and make use of realloc() and free() functions −
It is possible to pass some values from the command line to your C programs when
they are executed. These values are called command line arguments and many times
they are important for your program especially when you want to control your program
from outside instead of hard coding those values inside the code.
The command line arguments are handled using main() function arguments where argc
refers to the number of arguments passed, and argv[] is a pointer array which points to
each argument passed to the program. Following is a simple example which checks if
there is any argument supplied from the command line and take action accordingly −
#include <stdio.h>
int main( int argc, char *argv[] ) {
if( argc == 2 ) {
printf("The argument supplied is %s\n", argv[1]);
}
else if( argc > 2 ) {
printf("Too many arguments supplied.\n");
}
else {
printf("One argument expected.\n");
}
}
Dr. Sujit Kumar Singh
C –COMMAND LINE ARGUMENTS
You pass all the command line arguments separated by a space, but if
argument itself has a space then you can pass such arguments by putting
them inside double quotes "" or single quotes ''. Let us re-write above example
once again where we will print program name and we also pass a command
line argument by putting inside double quotes −
#include <stdio.h>
int main( int argc, char *argv[] ) {
printf("Program name %s\n", argv[0]);
if( argc == 2 ) {
printf("The argument supplied is %s\n", argv[1]);
}
else if( argc > 2 ) {
printf("Too many arguments supplied.\n");
}
else {
printf("One argument expected.\n");
}
} Dr. Sujit Kumar Singh
C –COMMAND LINE ARGUMENTS