C Language (1) - 11235
C Language (1) - 11235
C Language (1) - 11235
ECIL
CONTENTS
TOPIC -1 (Basics)
TOPIC –2 (Introduction)
ª Introduction to C
ª Character Set
ª Variables & Constants
ª Variable names
ª Data types & declarations
ª Operators & Precedence of Operators
TOPIC – 3 (Statements)
ª Types of statements
ª Declaration statements
ª Input / Output statements
ª Format Specifications
ª Field Widths etc.,
ª If - else Statement
ª Switch Statement
ª While Loop
ª Do - While Loop
ª For Loop
ª Goto and Break, Continue Statements etc.,
TOPIC - 5 (Arrays)
ª Definition
ª Types of Arrays
ª Multi-dimensional arrays
ª Matrices manipulation
TOPIC - 6 (Functions)
2
ª Definition & Declaration
ª Types of functions
ª Returning values from a function
ª Recursive Function
ª Passing arrays to the function
TOPIC – 7 (Pointers)
3
Basics
Machine languages:
Advantages:
1. Simplicity
2. Uniformity and
3. Portability
Examples for High Level Language are BASIC, FORTRAN, PASCAL, COBOL
etc.,
5
ª BASIC CONCEPTS OF High Level Language
A computer program written in a High Level Language is referred to as
SOURCE program. A program that is written in High Level Language (i.e.
SOURCE program) must be translated in to machine language before it can be
executed. This is known as compilation (some time interpretation). So a
COMPILER is a machine language program that translates (or compiles) the
SOURCE program (of High Level Language) in to machine language, which is
known as “OBJECT PROGRAM”. The object program is the input to the
computer to perform the required task. You know already some High Level
Languages like BASIC, COBOL, PASCAL, FORTRAN etc., and every High Level
Language will have its own COMPILER program to generate an object
program.
As you know every computer must have its own COMPILER for
particular High Level Language. During this module you are going to learn
BASIC language and then followed by other High Level Languages, for which
material will be provided separately in due course.
In the statements the value of the term, right of the equal sign
(=operator) is assigned to the variable on the left. While assigning the value
6
both left and right terms must be of same type. A numerical value can not be
assigned to a string variable or vice versa.
Now we will see errors and types that may come across while writing
and running the programs. It is practically almost impossible for a
programmer to write a program and enter it into the computer with out
making an occasional mistake. Therefore we must have a way to correct typing
errors and to add, delete or change statements once it has been transmitted to
computer. Incorrectly typed characters can be deleted or corrected by using
keyboard key like del key or backspace key.
∗ ERROR DIAGNOSTICS
∗ LOGICAL DEBUGGING
7
We have seen that syntax errors and certain types of logical errors will
cause diagnostic messages to be generated when compiling or executing a
program. Errors of this type are easy to find and correct. Usually however,
logical errors are much more difficult to detect, because the diagnostics gives
error-free. So in this case, a bit of ‘detective work’ is required which is called
logical debugging.
8
Introduction to C
ª Introduction to C
⇒ Character Set
Header: main( )
9
Body: {body}
CONSTANTS will have fixed values and they cannot be changed during the
program execution.
EX:
main()
{
int num; /* int is data type and num is variable name */
num=35; /* here 35 is constant */
}
Rules:
The Variables indicate the compiler how much space (memory) is required
by the particular variable depending upon the data type it holds. And these
are to be declared at the beginning of the program. Variables can change their
values during the execution of the program. So variable can be defined as a
tool to reserve memory to hold the data value. In the above example num is
the name of the variable.
Rules:
1. It must have at least one digit
2. It must not contain decimal point (value).
3. It can be either positive or negative value ( which should be prefixed with +
or - )
4. By default, if there is no sign that will be assumed as positive.
5. It can hold numbers in the range –32 768 to 32767.
FLOAT is used to store real values, which contain fractional part also.
The keyword used is float. Double is used where more accuracy is required in
fractional numbers calculations. The keyword is double.
11
Rules:
1. It must have at least one digit
2. It must contain decimal point (value).
3. It can be either positive or negative value (which should be prefixed with +
or - )
4. By default, if there is no sign that will be assumed as positive.
5. It can hold numbers in the range – 3.4E38 to 3.4E38
main()
{
float weight;
double weight1;
}
Rules:
main()
12
{
char name;
name=’A’;
}
Arithmetic operators
Increment and decrement operators
Relational operators
Logical operators
Assignment operators
Conditional operators
Sizeof operator
Bit wise operators
Arithmetic operators:
Addition Example:
Subtraction Example:
main()
{
int result;
int first;
int second;
result=first-second;
}
main()
{
int first,second,result;
first=10;
second=100;
result=first*second; /* first and second are multiplied and result will
be 1000 */
14
result=second/first; /* second is divided by first and result will be
10 */
result=second%first; /* remainder is stored in result =0 */
}
Example:
main()
{
int age;
age=39;
age++; /* age is incremented by one so age=40 */
age--; /* age is decrements by one so age=38 */
}
Relational Operators:
These operators check the relation between the two operands. If the result is
TRUE it returns ‘1’ else’0’.
Equality ==
Lesser than <
Greater than >
Less than or equal to <=
Greater than or equal to >=
Not equal to !=
Logical Operators:
15
AND is logical operator, it returns TRUE i.e. 1 if both the conditions evaluates
to true.
OR is logical operator, it returns TRUE i.e. 1 if any one of the condition
evaluates to true.
NOT is negation operator, it converts TRUE to FALSE or FALSE to TRUE.
ASSIGNMENT OPERATORS:
Conditional Operator :
Example:
16
main()
{
int age,age1,age2;
age=30;
age1=35;
age2=(age1>age) ? age1 : age;
}
sizeof Operator:
sizeof operator is used to know the number of bytes that a particular data
type will occupy in the memory of the system.
SYNTAX IS:
sizeof(int), sizeof(long), sizeof(float), sizeof(double), sizeof(char) etc.,
Precedence of Operators:
³Precedence:
() braces Any
++, -- ,! Increment, decrement operators, negation R to L
sizeof sizeof operator R to L
*, /, % Multiplication, division, modulus L to R
+,- Addition and subtraction L to R
<, <=, >, >= ,==, != Relational operators L to R
&&, | | Logical operators L to R
?: Conditional operator R to L
=,+=,-=,*=,/=,%= etc. Assignment operators R to L
STATEMENTS
17
³Input / Output statements
Rules
1. Every Statement should be terminated by ; (semi colon ).
2. All comments should be prefixed with /* and suffixed by */
3. Do not use “ \n ” in scanf() function.
printf() function is used to print output of the program on the screen. The type
of data that we want to print should be specified in certain specification. The
type of data and its respective format specifications were given below.
syntax:
printf(“format string”,list of variables);
Format specification starts always with ‘ % ’
int %d
long %l
unsigned %u
float %f
char %c
string %s
octal %o
hex %x
Ex1:
/* simple printf() statement implementation */
main()
{
printf(“Corporate Learning Centre\n”);
}
Ex2:
/* printf() statement implementation with integer format */
main()
{
int num=20;
char sex=’M’;
printf(“%d\t%c”,num,sex);
}
scanf() reads input from keyboard and stores the content in the memory
location named by variable declaration. It reads all data types with certain
limitations. While reading the data the type of data should be specified in the
format specification. The data type and respective specifications were given in
the earlier topic. It is to note that while reading the data type of char, int, and
float the ‘&’ character should be prefixed as shown in the example.
19
Ex1.
/* scanf () function implementation for reading int,char,float */
main()
{
char name;
int basic;
float da;
printf(“Input the DA , BASIC and Initial NAME of an employee\n”);
scanf(“%f%d%c’,&num,&basic,&name);
printf(“%c\t%d\t%f”,name,basic,da);
}
Ex2:
/* scanf() function implementation for reading string */
main()
{
char name[20];
printf(“Enter your name\n”);
scanf(“%s”,name);
printf(“%s”,name);
}
FIELD WIDTH:
Field width specifies the width of the argument occupies when printing
takes place. It should be mentioned in the format specification. For example if
we mention %8d that argument will occupy a width of 8 characters space and
if the integer is less than 8 digits, then the number will be automatically right
aligned leaving blanks in the left side. To make the argument to be left aligned
use %-8d.
Example:
/* makes use of field width in the format specification */
20
main()
{
long cno=999999;
printf(“%10d\n”,cno); /* right aligned */
printf(“%-10d”,cno); /* left aligned */
}
main(0
{
float value=23.5667;
printf(“%80.2f”,value); /* output is 23.57 */
printf(“%80.1f”,value); /* output is 23.6 */
}
Control flow
21
Statements are executed in the increasing (sequential) order. However,
there are certain statements which can (or required to) be altered the
sequence of execution of the program by directing (passing) the control to
some other statement other than the following statement. And some times it is
required to repeat the set of statements for certain number of times depending
upon some condition. This can be accomplished by using control statements.
We usually refer these branching and loops. Again branching can either
conditional or unconditional branching or jumping (or transfers of control).
Syntax:
if <condition>
Statement;
else
Statement;
Example1:
/* Implementation of if and else */
main()
long num=989822;
if(num==989822)
printf(“your number is: %ld\n”,num);
else
printf(“your number is not %ld”,num);
}
Example 2:
22
/* Implementation of if and else in nesting */
main()
{
int age=53;
int age1=60;
if(age == 53)
{
if(age1==60)
printf(“ age is %d and age1 is %d”,age,age1);
}
else
printf(“ages are not matching”);
}
Example 3:
IF - ELSE CONTROL
23
START
IS
TRUE COND FALSE
?
STATEMENTS STATEMENTS
STOP
Ex.
main()
{
int num=55;
if(num==51)
printf(“The number is %d\n”,num);
else
printf(“The number is not 51”);
}
ª Switch Statement:
By using. if and else control, we have only two way branching facility. But
where as some times we need multiple branching of control. Here we use
switch statement in which there is no limit of number of branches. If a
condition is true that part of the switch statement is executed and none of the
other will comes in to picture. If none of the conditions are true, then default
condition statements (if present) will be executed.
24
Note: Every condition in the switch statement must be terminated with break,
so as to come out of the switch body.
Example:
main()
{
int num=2;
switch(num)
{
case 1:
printf(“This is case 1\n”);
break;
case 2:
printf(“This is case 2\n”);
break;
case 3:
printf(“This is case 3\n”);
break;
case 4:
printf(“This is case 4\n”);
break;
default:
printf(“none of the conditions are true”);
}
}
ª WHILE LOOP
Syntax:
25
while(<condition>)
{
statement1;
statement2;
...
}
Example:
/* Implementation of while loop */
main()
{
int age =10;
while(age <= 50)
printf(“%d\t”,age++);
}
WHILE LOOP
START
AGE=10
IS
NO AGE<=50
YES
PRINT AGE
STOP
AGE=AGE+1
26
main()
{
int num=1;
while(num++<10)
printf(“%d\n”,num);
}
ª Do - While Loop
This is similar to while loop except that the condition will be tested at the
end of the loop, whereas in while condition is tested at the beginning. So the
statement or statements in do while loop will be executed at least once.
Syntax:
do
{
statement1;
statement2;
...
}
while(<cond>);
Example:
main()
{
int num=5;
do
printf(“%d\n”,num++);
while(num<=5);
}
ª FOR LOOP
For loop checks a condition and as per the result it performs an operation
and reevaluates the counter. It is nothing but initialization, testing and
incrementation / decrementation.
Syntax:
main()
{
int num;
for(num=0;num<=10;num++)
{
printf(“%d\t”,num);
}
}
Ex.
main()
{
int num;
for(num=1;num<10;num++)
{
printf(“%d\t”,num++);
}
}
28
DO WHILE CONTROL
START
NUM=1
PRINT NUM
NUM=NUM+1
YES IS NO
NUM<10 STOP
?
Example.
main()
{
int num;
num=1;
do
printf(“%d\t”,num++);
while(num<10);
}
The following example will print the body of the for loop infinitely, because
of there is no initialization, testing and incrementation. Some times this type
of loops required, which is going to be implemented in due course.
29
main()
{
for(;;)
{
printf(“This is infinite loop\n”);
}
Example:
/* Implementation of break statement */
main()
{
int num,num1=20;
for(num=0;num<=num1;num++)
{
if(num==10)
break;
printf(“%d\t”,num);
}
}
CONTINUE is useful for skipping all statements in a loop without coming out
of the loop and going back to the condition checking statement of the loop.
Example:
/* Implementation of continue statement */
main()
{
int num,num1=20;
for(num=0;num<=num1;num++)
{
if(num<=10)
continue;
printf(“%d\t”,num);
}
}
30
One loop can be embedded with in another (called as nested loop) if
necessary to repeat a loop more than once. And in fact, there can be several
levels of nesting. The rules we implement / apply, while writing single loops
also applies to nested loops absolutely. There should be no overlap between
the outer and inner loops. The inner loop must be completely embedded with
in the outer loop. The nesting can be implemented using either WHILE or FOR
depending upon requirement. The following examples given you an idea how
to implement the nesting using for.
main()
{
int num,num1;
for(num=1;num<=3;num++)
{
for(num1=0;num1<=3;num1++)
printf(“%d\t”,num*num1);
printf(“\n”);
}
}
START
NUM++
YES
IS
NUM==5 YES
BREAK
NO NEXT
PRINT NUM
31
main()
{
int num;
for(num=1;num<=10;num++)
{
if(num == 5)
break;
else
printf(“%d\t”,num);
}
}
START
YES
IS YES
NUM==5 CONTINUE
NO
PRINT NUM
ª GOTO STATEMENT:
Goto takes over the control to the specified-labeled location in the program.
Label name should not be any standard C program keywords or function
names. This statement is normally used to come out of deeply nested loops
and to go to a specified statement. Goto cannot be used in between two
functions. It can be used within one function only. However goto statement is
not suggestible to use in programming.
Syntax:
goto clc;
Statements;
32
…..
clc:
Statements;
...
Example:
main()
{
int num,num1=10;
num=20;
printf(“I am learning c language\n”);
if(num!=num1) goto clc;
printf(“Jajam Institute of Information Technology\n”);
clc:
printf(“Goto statement implemented”);
}
ARRAYS
Definition
33
Collection of similar data elements stored in adjacent memory is called an
array. The elements of an array can be of any data type. Arrays of int, char,
float and double etc. are possible. Arrays are two types. Generally single
dimension and multi-dimension arrays. If the elements occupy only in one row
(row arrays) that array is known as single array. Whereas multi-dimension
arrays consists of both row and column elements.
num[0]=32;
num[1]=45;
....
num[9]56;
int num[10]={20,21,22,23,24,25,26,27,28,23}; /* single dimension array */
34
{num1[0][0] num1[0][1] num1[0][2]}
{num1[1]0] num1[1][1] num1[1][2]}
};
Strings
35
Now let us see how a character array can be declared. Character should
be initialized or declared with in single quotes and strings should be declared
with in the double quotes as shown below. And one more point is that at the
end of the every string the compiler will automatically append a null
character ‘\0’ as terminator. Even for an empty string the only character
available in that string is the null character.
main()
{
char name[40]={“corporate learning center”};
printf(“%s”,name);
}
main()
{
char name[2][2][30]={
{“First Row First Column”, “First Row Second Column”},
{“Second Row First Column”, “Second Row Second Column”}
};
Example:
36
main()
{
int row,col;
char name[2][2][40]={
{“Corporate Learning Center”,”ECIL”},
{“ASRao”, “Nagar”}
};
for(row=0;row<=1;row++)
{
for(col=0;col<=1;col++)
printf(“%s\t”,name[row][col]);
}
}
A header file called string.h contains the functions like strcpy(), strlen(), strcat(), strcmp()
etc., Now let us see in detail how exactly these functions will work and how to make use of
these functions.
³String functions
strcpy()
The usage of this function is to copy a string (which is second argument)
to the another string (which is first argument).
Example:
main()
{
char source[10],target[10];
source[]={“corporate”};
strcpy(target,source);
printf(“%s”,target);
}
strcat()
37
The usage is this function is to combine two strings given as arguments.
The second argument (string) is appended to the first argument (string).
Example is as follows.
main()
{
char string1[30]={“corporate ”};
char string2[20]={“ _learning”};
strcat(string1,string2);
printf(“%s”,string1);
}
strlen()
The usage of this function is to find out the length of the string (given in
the argument)
Example:
main()
{
char string1[30]={“Corporate learning center”};
int length=0;
length=strlen(string1);
printf(“Length is %d”,length);
}
strcmp()
The usage of this function is to compare two strings for equality. If both
the strings are equal then it will return true that is zero else false that is non
zero number. Example is like
main()
{
char string1[]={“electronics”};
char string2[]={“electronics”};
if(strcmp(string1,string2)==0) printf(“Two strings are identical”);
38
else
printf(“Two strings are unidentical”);
}
strrev()
main()
{
char a[20]={“computer”};
strrev(a);
puts(a);
/* output is retupmoc */
}
strupr ()
main()
{
char a[20];
puts(“Enter some text”);
gets(a);
strupr(a);
puts(a);
}
input is : computer
output is: COMPUTER
Functions
39
ª Definition & Declaration
Limitations:
Function name should have to start with alphabet and can contain
alphabets, numbers and underscore. Other rules, what ever we apply to
declare a variable name, will also applies to function header declaration.
Purpose / Usage:
Where ever and when ever certain process is repeated many times in the
program, instead of writing lengthy code, it is recommended to write a
function for that task and call the same as many times as we require. This is
nothing but just to avoid repetition of code in the program and provides good
readability and improves efficiency.
Example:
main()
{
printf(“Control is passing to function test\n”);
test(); /* calling a function */
printf(“Function test is completed and returned to main function.”);
}
40
test() /* called function */
{
printf(“This is function test\n”);
}
main()
{
printf(“This is main function\n”);
fun1();
printf(“Returned to main function.”);
}
fun1()
{
printf(“This is first function\n”);
fun2();
printf(“Returned to first function from second function\n”);
}
fun2()
{
printf(“This is second function\n”);
}
³Recursive function:
41
Main()
{
callme();
printf(“Return is not possible from callme function”);
/* control will not reach here */
}
callme()
{
printf(“This is recursive function\n”);
printf(“use ctrl+c to quit\n”);
callme(); /* this is infinite loop */
}
³Arguments:
Example:
main()
{
int num;
printf(“Enter some number\n”);
scanf(“%d”,&num);
printf(“%d”, square(num));
/* num is actual argument passed to function */
}
42
square(int num1) /* num1 is formal argument to be declared */
{
return(num1*num1); /* returning the value back to main function */
}
In the above example the integer value what ever inputted was stored in
the variable num and Function Square passed the actual argument num. And
at the receiving end in the called function formal argument num1 will be
assigned with the value of the num (the actual argument). In this example
only one argument is passed to the function but multiple arguments can be
passed as shown in the following example.
Example:
main()
{
int num,num1,total;
num=10;
num1=20;
char cod=’A’;
total=calcu(num,num1,cod);
printf(“%d”,total);
}
calcu(no,no1,let)
int no,no1;
char let;
{
return(let+no*no1);
}
The data type of actual arguments and formal arguments must be same.
By default all the functions are of integer type. If a function required to
perform either float or other data type, then it should be declared in the
calling function it self explicitly.
43
ª Passing arrays to functions:
Example:
main()
{
int total,num=5;
int marks[]={20,30,40,50,60};
total=fun(marks,num);
printf(“%d”,total);
}
fun(marks,num)
int marks[],num;
{
int sum=0;
while(num--!=0)
sum+=marks[num];
return(sum);
}
Example:
main()
{
float fun(); /* declaration of function type or prototype */
float num=2.5;
printf(“%f”,fun(num));
}
44
float fun(float num1)
{
return(num1+num1);
}
ª Intrinsic functions:
Pointers
45
ª Definition & Declaration:
Pointer is nothing but a one type of variable, which stores the address of
the another variable. We can access the variable which has its address stored
in pointer variable. Pointer variable also permits to supply the address of the
variable, which is stored in it, to some other variable to access the same. And
assigning the values of the first variable to the second variable through the
pointer variable is a technic known as indirection.
* Is known as pointer (indirection) and is used to fetch the contents from the
particular address of a variable.
main()
{
int first,*second,third;
first = 200;
second = &first;
third = *second;
printf(“%d”,third);
} Variables
Location
(address)
46
Let us see exactly what happens in the above example. First and third
are declared as integer variables and second is declared as pointer variable
which is prefixed with *. The value of first is assigned to third through the
pointer second. Second stores the address of first and *second assigns the
value at address of first to third. And finally we print the output to console.
Example 2:
main()
{
int num, *point;
point=#
printf(“Address of num is %u\n”,&num);
printf(“Address of num is %u\n”,point);
printf(“Address of point is %u\n”,&point);
printf(“Value of num is %d\n”,*point);
printf(“Value of num is %d\n”,num);
printf(“value of num is %d\n”,*(&num));
}
Similar analogy can be applied to other data types like char, float.
Suppose if we declare float *pie, it does not mean that pie is going to contain a
floating-point value (real numbers). Remember that pointer variable will hold
only the address of the variable float but not float value.
Pointer to string points at the address of the first character in the string.
Operators like + and - will work on addresses stored.
¾ Pointer to pointer:
47
main()
{
int num=20;
int *point1;
int **point2;
point1 = #
point2 = &point1;
printf(“Address of num is %u\n”,&num);
printf(“Address of num is %u\n”,point1);
printf(“Address of num is %\n”,*point2);
printf(“Address of point1 is %u\n”,&point1);
printf(“Address of point1 is %u\n”,point2);
printf(“Address of point2 is %u\n”,&point2);
printf(“value of num is %d %d %d”,num,*point1,**point2);
}
main()
{
int radi;
float area;
printf(“Enter radius :\n”);
scanf(“%d”,&radi);
areafun(radi,&area);
printf(“area is %f”,area);
}
48
areafun(int r,float *a)
{
*a = 3.14 * r * r;
}
Example:
/* To return more values to the calling function i.e. main() */
main()
{
int num=50,num1=100,num2=150,num3=200;
result(&num,&num1,&num2,&num3);
printf(“%d\t%d\t%d\t%d”,num,num1,num2,num3);
}
result(n1,n2,n3,n4)
int *n1,*n2,*n3,*n4;
{
*n1 = *n1 + *n1;
*n2 = *n2 * *n2;
*n3 = *n3 * 10;
*n4 = *n4 + 5;
}
Example:
main()
{
int num, marks[10]={2,3,4,5,6,7,8,9,1,12};
int *result;
result = &marks[9];
for(num=0;num<=9;num++)
printf(“%d\t”,*result--);
}
In the above example we stored the last element address &marks [9] to
the pointer variable result and while printing the out put to console we started
reading from last element to first element through a for loop. Similarly we can
move from any required element to the destination element by selecting the
base address and then add the number of elements to move as shown.
int *result;
int marks[50];
result = marks + 10;
Now the pointer is moved the 11th element of the marks array. Similarly
we can travel in any fashion in the array. Comparison of two pointers can be
made as follows. Both the pointers must be pointed to the same element in the
array, otherwise we will get some unreliable results. Pointers can be
incremented or decremented, as we require. But Note that no two pointers
will be added, multiplied or divided in any case. Which will result some
unpredictable / unreliable behavior in the system itself.
Example:
50
main()
{
int num, *point1,*point2,arr[11]={11,12,13,14,15,16,17,18,19,20,21};
point1 = arr;
point2 = arr +10;
for(num=0;num<=5;num++)
{
if(*point1 == *point2)
printf(“ Both the pointers are at element %d”,num);
point1++;
point2---;
}
}
51
In the above example we can move with in the limits and can access the
elements in the array. And now let us see a character multi-dimensional array
example:
Example:
main()
{
char *point, city[3][15]={“Andhra ”,
“Telangana”,
“Rayalaseema”,
};
point = city;
printf(“%c\n”,*(point+0));
}
In the above example in the printf statement pointer *(point+0) was used
to read and print the contents of the character array’s zeroth row, zeroth
column. In the place of *(point+0) zero can be replaced with any other required
number to access that particular element.
53
Initialization of the structures can also be done as follows:
main()
{
struct student{
int rno;
int marks;
char name[10];
};
struct student s1; /* declaration of the structure variable */
s1.rno = 12345; /* initialization of the structure elements */
s1.marks = 9400;
strcpy(s1.name , “CLC”);
printf(“%d\t%d\t%s”,s1.rno,s1.marks,s1.name);
}
/* Global declaration */
struct alarm
{
int num;
char ch;
};
alarm samp;
54
main()
{
....
....
}
main()
{
struct exam{
int h_no;
int marks;
};
struct exam1{
char name[20];
struct exam rec;
};
struct exam1 stud;
}
scanf(“%s”,stud.name);
scanf(“%d%d”,stud.rec.h_no,stud.rec.marks);
55
struct emp1{
int cno;
int basic;
};
struct emp e1;
struct emp1 e2;
e1.cno=1234; /* initialization */
e1.basic=14200;
e2 = e1;
/* assigning the total values of e1 structure to e2 structure */
ª Array of structures:
Example
main()
{
struct samp
{
int cno;
char sex;
};
struct samp emp[5];
56
Example 2:
main()
{
struct samp
{
char sex;
int cno;
};
struct samp emp[5];
int num;
for(num=0;num<=4;num++)
{
printf(“Enter sex and code no.\n”);
scanf(“%c%d”,&emp[num].sex,&emp[num].cno);
}
for(num=0;num<=4;num++)
{
printf(“%c\t%d”,emp[num].sex,emp[num].cno);
}
}
struct samp
{
int cno;
int basic;
};
samp e1;
57
main()
{
e1.cno=12345;
e1.basic=4200;
func(e1);
}
ª Pointers to Structures :
main()
{
struct emp{
int cno;
int basic;
};
ª UNIONS:
Unions like structures are derived data types, which group together a
number of variables. However, union members declared in the union will use
the same memory.
Example:
main()
{
union samp{
int cno;
int basic;
}emp;
emp.cno=12345;
printf(“%d\t%d”,emp.cno,emp.basic);
}
In the above example the emp.cno is initialized with 12345 and while we
try to see the output of emp.cno and emp.basic through printf() on the console
both the members will show the same value because as said earlier both are
utilizing the same memory of the system. Even if we declare a character also it
will use the same memory space.
¾ C PREPROCESSOR:
As the name suggests, preprocessor is a program that processes our source
program before passing it for compilation. It helps in better coding of a
program. The common preprocessor directives are:
1. Macro Expansion
2. File Inclusion &
3. Conditional Compilation.
¾ Macro Expansion
#define NUM 100 /* macro template */
#define SQUARE(x) (x*x)
59
main()
{
int num=5;
if(SQUARE(num)<=NUM)
printf(“num is less than NUM”);
else
printf(“num is more than NUM”);
}
¾ File inclusion
This will allow including one file in to another. The presence of a #include
statement in a program causes the entire contents of the added (included) file
to be available at that point in the existing program.
#include <filename>
A typical use of this feature would be to store frequently used functions
and macros definitions in a single file and #include it in whichever file we
require.
ª TYPE CASTING:
Some times we need to force the compiler to explicitly convert the value of
an expression to a particular data type. This would be seen from the following
example.
Example:
main()
{
float result;
int num=10,num1=4;
result= num/num1;
printf(“\nThe value of result=%f”,result);
}
60
In the above program result=1.00 but not 1.5. This is because the num,
num1 are integers and then it yielded an integer to result. But don’t want the
quotient to be truncated. So the solution is to make the num or num1 to
declare as float. But the program requirements are like that num should be an
int only. In such a situation we use type casting as follows:
main()
{
float result;
int num=10,num1=4;
result= (float) num/num1; /* type casting */
printf(“\nThe value of result=%f”,result);
}
main()
{
float real=10.55;
printf(“\nvalue of real=%f”,real);
printf(“\nvalue of real after type casting=%d”,(int)real);
}
ª TYPEDEF:
This is used to rename the data types. This technique will come in to usage
in some situations to help in clarify the source code of the program. It is
nothing but redefining the name of the existing variable type.
Now we can declare variables of the type unsigned long int by writing:
TEST num, num1; is nothing but unsigned long int num, num1;
61
This typedef provided a short and meaningful system to call a data type.
Generally uppercase letters are used to make clear that we are dealing with a
renamed data type. While the easy readability is probably not a great in this
example, but it can be significant when the name of a particular data type is
long and unwieldy, as we often see in structure declarations like:
struct employee{
char name[30];
int age;
float basic;
};
struct employee e1,e2;
The weakness of enum variables is that there is no way to use the enum values
directly in I/O functions like printf() , scanf().
Example:
enum group
{
CLC,ITD,SPD,RID
};
struct emp
{
char name[30];
long cno;
enum group gr;
}e1;
strcpy(e1.name,”xxxxxx”);
e1.cno = 12345;
e1.gr = 1;
if(e1.gr = = “CLC”)
printf(“\nEmployee from CLC”);
else
printf(“\nEmployee from other DIVISION”);
63
ª ASCII CHARACTERS:
Out of this 256 characters first 128 characters are often called as ASCII
(American standard code for information interchange) characters and next 128
characters are called as extended characters.
A to Z 65 to 90
a to z 97 to 122
0 to 9 48 to 57
64
File Operations
The input and output (I / O) is entirely the responsibility of the
operating software. With different operating software, the way the I/O is done
would obviously be different. Wisely, keeping the standard library of functions
common, the functions themselves have been written differently for different
operating software s. Hence, we can use printf(), scanf() etc., any other
standard functions in any environment like DOS. UNIX etc., to achieve the
same result. This is what actually the portability and power of C.
Under the category of Console I/O functions, there are functions available for
handling char, int and strings.
9 Console I/O functions
INPUT:
char getch() Gets a char from keyboard, Enter key not required.
getche() Similar to getch() but it echoes on the screen.
fgetchar() Gets the char, echoes it on the screen AND
Enter key is required.
getchar() A macro, similar to fgetchar()
string gets() Accepts a string until Enter key is hit.
OUTPUT:
char putch() Prints the character on console.
fputchar() Similar to putch().
putchar() A macro, similar to putch().
String puts() Outputs a string to the console.
65
9 Disk I/O functions:
Disk I/O functions are either high level (also called standard I/O or stream
I/O ) or low level (or system I/O). The basic difference between them is that in
the high level functions the buffer management is done by the functions them
selves, where as in low level functions this is the responsibility of the
programmer. The files that are to be accessed for I/O must be opened. The
function fopen() is used to open a file in high level language disk I/O operation
as
66
stdin : Reads from keyboard
stdout : Displays on console
stderr : Displays on console
stdaux : Serial port
stdprn : Parallel port
All the above five files will be opened by default and we need not to open
them on our own whenever we open a program. If any error occurs while
opening file, a null is being returned.
Once the file have been opened it is required to access the specific part of the
file. Positioning the file pointer at the desired position in the file does this. The
functions available for this task are rewind () and fseek(). rewind() positions
the pointer at the beginning of the file and fseek() places the file pointer
virtually anywhere in the file.
Syntax:
fseek(file pointer,+/- no.of bytes,anchor);
After the file is opened and worked with the same, it is must that the file is to
be closed before exiting by using the function fclose();
67
The following program simply reads the contents of the file temp until
the end of the file and prints its contents to the screen.
Example 1:
/* this program will reads from file temp and displays on console */
#include <stdio.h>
main()
{
char ch;
FILE *fp;
fp=fopen(“temp”, “r”);
if(fp = = NULL) exit();
while(!feof(fp))
{
ch=fgetc(fp);
putch(ch);
}
fclose(fp);
}
Example 2:
/* this program will reads from file temp and writes to file test */
#include <stdio.h>
main()
{
char ch;
FILE *fs,*ft;
fs=fopen(“temp”, “r”);
ft=fopen(“test”, “w”);
if((fs==NULL||ft==NULL) ) exit();
68
while(!feof(fs))
{
ch=fgetc(fs);
putc(ch,ft);
}
fcloseall();
}
Example 3:
/* This program will reads from file temp and writes alternate characters to
file test */
#include <stdio.h>
main()
{
char ch;
FILE *fs,*ft;
fs=fopen(“temp”, “r”);
ft=fopen(“test”, “w”);
if((fs==NULL||ft==NULL) ) exit();
rewind(fs);
while(!feof(fs))
{
fseek(fs,1l,1);
ch=fgetc(fs);
putc(ch,ft);
}
fcloseall();
}
69
Example 4:
/* This program will reads from KB and writes to file test */
#include <stdio.h>
main()
{
char ch[20];
long cno;
int basic;
FILE *fs;
fs=fopen(“temp”, “w”);
if(fs = = NULL) exit();
fscanf(stdin, “%s%ld%d”,ch,&cno,&basic);
fprintf(fs, “%s\t%ld\t%d”,ch,cno,basic);
fclose(fs);
}
Example 5:
/* Passing arguments in main */
#include<stdio.h>
main(int argc,char *argv[])
{
FILE *fp;
char ch;
fp = fopen(argv[1],"r");
while(!feof(fp))
{
ch = getc(fp);
printf("%c",ch);
}
fclose(fp);
}
70
Example 6:
#include<stdio.h>
main(int argc, char *argv[])
{
FILE *fp;
char ch,s[15];
if(argc!=2)
{
printf("Enter file name:\n");
scanf("%s",s);
}
else
strcpy(s,argv[1]);
fp=fopen(s,"r+");
if(fp==0)
{
printf("File < %s > not found",s);
exit();
}
while((ch=fgetc(fp))!=EOF)
if(ch>='a' && ch<='z')
{
fseek(fp,-1l,1);
putc((ch=ch-32),fp);
fseek(fp,0l,1);
}
fclose(fp);
}
71
Example7:
/* USAGE OF FPUTS, GETS (string storing) */
#include<stdio.h>
main()
{
FILE *fp;
char s[80];
fp=fopen("xxx","w");
printf("\nEnter some lines of text:\n");
while(strlen(gets(s))>0)
{
fputs(s,fp);
fputs("\n",fp);
}
fclose(fp);
}
Example 8:
/* FILE DELETION PURPOSE USING REMOVE */
#include<stdio.h>
main(int argc,char *argv[])
{
FILE *fp;
fp=fopen(argv[1],"w");
if(argc!=2)
{
printf("Enter file name to be deleted:");
exit();
}
fclose(fp);
remove(argv[1]);
}
72
Example 9:
#include<stdio.h>
main(int argc,char *argv[])
{
FILE *fp;
fp=fopen(argv[1],"r");
if(argc!=3)
{
printf("Enter source file name followed by required name of the file:\n");
exit();
}
fclose(fp);
rename(argv[1],argv[2]);
}
73
Data Structures
DYNAMIC MEMORY ALLOCATION
Necessity
Consider a declaration < int marks[100];> such a declaration would
typically be used if hundred student’s marks are to be stored in
memory. The declaration will reserve 200 bytes of memory for storing
100 integers. Never the less, some times it may happen that when we
actually run the program, we might be interested in storing only 50
student’s marks. In this case, the memory used is 100 bytes (50x2) only,
which would result in wastage of the remaining 100 bytes, which was
reserved by declaration. Subsequently, sometimes we need to store more
than 100 student’s marks, but our declaration provides us (limits us)
only with 100 marks. There is no mechanism to either increase or
decrease the size of an array during the program run. The reason is
arrays use static memory allocation. To over come this, we have an
alternative with the use of standard library functions.
The standard library function malloc() and calloc() functions
allocates memory during the program run as per user requirement and
this memory allocation is known as dynamic memory allocation. Let
us examine the following example.
#include <alloc.h>
main()
{
int n,avg,I,*p,sum=0;
printf(“Enter number of students:”);
scanf(“%d”,&n);
p=(int*)malloc(n*2);
if(p==NULL)
{
printf(“Memory allocation failed”);
exit();
}
74
for(i=0;i<n;i++)
{
printf(“Enter marks of %d student”,i+1);
scanf(“%d”,(p+i));
}
for(i=0;i<n;i++)
sum=sum+*(p+i);
avg=sum/n;
printf(“Average is %d”, avg);
free(p);
}
main()
{
int *p,n;
printf(“Enter some number”);
scanf(“%d”,&n);
p=(int*)calloc(n,2);
}
Another difference between malloc() and calloc() is that, by default the
memory allocated by malloc() contains garbage values, where as that allocated
by calloc() contains all zeros. Another good practice is to free the reserved
memory blocks, soon after the task is over, as last statement in the program.
75
⇛ LINKED LIST
NODE
76
⇛ DOUBLE LINKED LISTS
In the linked lists we have seen each node provides information about
where is the next node in the list. Each node will establish a link to the
successor, but not with the predecessor. It means that the current node in
the list does not know previous node address. While accessing the elements
of a single linked list, suppose if we are at 10th node and would like to
access the 9th node, then only way we have to follow is to start traveling
from first node. To overcome this difficulty, we have an another facility
called double linked lists. Here we can travel either to next node or
previous node as shown.
Stacks and queues are two very useful data structures. These data
structures are often implemented using arrays since most programming
languages provide array as a predefined data type, and such an
implementation is quite easy.
QUEUE
Data
STACK
The linked lists that we have seen so far are often known as linear linked
lists. First setting up a pointer pointing to the first node in the list and then
traversing the entire list-using pointer can access all elements of such a
linked list. Although a linear list is a useful data structure, it has several
shortcomings. For example, given a pointer P to node in a linear list, we
can not reach any of the nodes that precede the node to which P is
pointing. This disadvantage can be overcome by making a small change to
the structure of a linear list such that the link field in the last node
contains a pointer back to the first node rather than a null. Such a list is
called circular linked lists and is shown in next page.
78
ISSUED FOR PARTICIPANTS AS COURSE MATERIAL
HYDERABAD-062
79