You are on page 1of 37

History of C

• The C programming language was devised in the early 1970s by Dennis M. Ritchie an employee
from Bell Labs (AT&T).

• In the 1960s Ritchie worked, with several other employees of Bell Labs (AT&T), on a project
called Multics. The goal of the project was to develop an operating system for a large computer
that could be used by a thousand users. In 1969 AT&T (Bell Labs) withdrew from the project,
because the project could not produce an economically useful system. So the employees of Bell
Labs (AT&T) had to search for another project to work on (mainly Dennis M. Ritchie and Ken
Thompson).

• The language B was developed in 1969-70 by Ken Thompson. A drawback of the B language was
that it did not know data-types. (Everything was expressed in machine words). Another
functionality that the B language did not provide was the use of “structures”. The lag of these
things formed the reason for Dennis M. Ritchie to develop the programming language C. So in
1971-73 Dennis M. Ritchie turned the B language into the C language, keeping most of the
language B syntax while adding data-types and many other changes.

Features of C

• Simple- Every c program can be written in simple English language so that it is very easy to
understand and developed by programmer.

• Platform dependent- A language is said to be platform dependent whenever the program is


execute in the same operating system where that was developed and compiled but not run and
execute on other operating system. C is platform dependent programming language.

• Portability-It is the concept of carrying the instruction from one system to another system. In C
Language .C file contain source code, we can edit also this code. .exe file contain application,
only we can execute this file. When we write and compile any C program on window operating
system that program easily run on other window based system.

• Powerful- C is a very powerful programming language, it have a wide verity of data types,
functions, control statements, decision making statements, etc.

• Modularity -It is concept of designing an application in subprogram that is procedure oriented


approach. In c programming we can break our code in subprogram. For example we can write a
calculator programs in C language with divide our code in subprograms.

• Case sensitive-It is a case sensitive programming language. In C programming 'break and BREAK'
both are different.

Identifiers

Identifiers are basically the names given to program elements such as variables, arrays and functions.

Programming in C (B.Sc.IT) Page 1


Rules for forming identifiers

1. It should start with either alphabet (like a-z,A-Z) or underscore ‘ _ ‘.

2. It cannot include any special characters or punctuation marks( like #, $, ^,?,&,% etc.) except the
underscore ‘_’ .

3. There cannot be two successive underscores.

4. It does not include reserved keyword ( like double, int , if, else, main, break etc.)

Keywords

auto break char const continue default else double enum extern float for goto int long

register return short signed sizeof struct do if switch typedef union unsigned void volatile

static while case

Data types in C

Data Type Keyword Used Size in bytes Range Use

Character char 1 -128 to 127 To store characters

(-28-1 to +28-1-1)

Integer int 2 -32768 to 32767 To store integer numbers

(-216-1 to +216-1-1)

Floating Point float 4 3.4E-38 to 3.4E+38 To store floating point numbers

Double double 8 1.7E-308 to 1.7E+308 To store big floating point numbers

Detailed list of data types

Data Type Size in bytes Range

char 1 -128 to 127

Programming in C (B.Sc.IT) Page 2


unsigned char 1 0 to 255

signed char 1 -128 to 127

int 2 -32768 to +32767

signed int 2 -32768 to +32767

unsigned int 2 0 to 65535

short int 2 -32768 to +32767

long int 4 -2147483648 to -2147483647

float 4 -3.4 E + 48 to 3.4 E + 48

double 8 1.7E-308 to 1.7E+308

long double 10 -3.4 E -4932 to +1.1 E + 4932

Character set

The characters used in C are grouped into the

Following three categories:

1. Alphabets e.g. (A-Z, a-z.)

2. Digits e.g. (0-9)

3. Special characters e.g.

,.:;,“?_!#=|+-*/%&^~<>\()[]{}

Variables

The quantity that changes during the execution of a program is called a variable. The variables

are the names given to identify the specific program elements. The variables represent a

Programming in C (B.Sc.IT) Page 3


particular memory location where the data can be store.

Example : sum,num1,age,city,distance etc.

C Constants

The quantity which does not change during the execution of a program is known as constants.

1. Integer Constant – is a whole number. It is a sequence of digits without a decimal point.

e.g. 246, 0, +25, 9999 etc.

2. Floating Constant – is a number with decimal point. It is defined as a sequence of digits preceded and
followed by decimal point.

e. g. -246.01, 0.0, 82.5 etc

3. Character Constant – is a single character enclosed within a pair of apostrophes.

e.g. ‘a’, ‘?’,’#’ ,’Z’ etc.

4. String Constant – is a sequence of characters enclosed within a pair of double quotes.

e.g. “Hi”, “2000”,”welcome” etc.

Preprocessor statements

These statements begin with # symbol, and are also called preprocessor directives. These

statements direct the C preprocessor to includeheader files and also symbolic constants into a

C program.

e.g.

#include<stdio.h> // for standard I/O function

#define pi 3.14 //for defining constant value of pi

#include<math.h> // for mathematical functions

#include<string.h> // for string related function

Input Output Statements

Standard input-output functions in C:

1. scanf () 5. gets()

2. printf() 6. puts()

Programming in C (B.Sc.IT) Page 4


3. getchar() 7. getch()

4. putchar() 8. getchar()

There are two types of input-output statements

1. Formatted I/O statements- enable the user to specify the type of the data and the way in which
it should be read in or written out.

Example : printf() – output

scanf() - input

2. Unformatted I/O statements- do not specify the type of the data and the way in which it should be
read in or written out.

Example : putchar(),puts() – output

getchar(), gets() - input

Formatted Input

Example: int n;

printf(“Enter a number”);

scanf(“%d”,&n);

scanf(“control string”,address_list);

Control string – specifies the type of the values

Which are to be supplied to the variables.

Address list – address of memory locations

where the values of input variables should be

stored.

Similar for printf() function.

Example: printf(“The value of n=%d”, n);

Programming in C (B.Sc.IT) Page 5


Character groups

Character Group Meaning

%c For a single character

%d For a decimal integer

%f For a floating – point number

%e (long & double) For a floating – point number in exponential format

%o For octal number

%u For an unsigned integer

%s For read a string

%x For hexadecimal value

%lf For double(floating – point) number

Simple program in to print a message

#include<stdio.h>

#include<conio.h>

Void main()

printf(“Hello\n”);

getch();

Programming in C (B.Sc.IT) Page 6


Program in C to addition of two numbers:

//addition of two nos.

#include<stdio.h>

#include<conio.h>

Void main()

int n1,n2,add;

printf(“Enter two nos.\n”);

scanf(“%d%d”,&n1,&n2);

add=n1+n2;

printf(“Addition=%d“,add);

getch();

Note - & meaning value at the address of.

Programming in C (B.Sc.IT) Page 7


Debugging - The process of detecting and correcting errors in the program is known as debugging.

There are three types of errors:

1. Syntax errors – are the result of violation of grammar(rules of programming). On encounter


these errors a computer display error message. Example missing of semicolon.

2. Logical errors – occur during coding process. When programmer code his problem,he must take
care of correct operation to be performed. Difficult to debug.

Example : instead of addition symbol , inserted multiplication symbol so the expected result will

be wrong.

3. Run-time errors – occur when we attempt to run an ambiguous instructions. Example: an


infinite loop in program sequence which causes no output, divide by zero, data overflow.

Compilation & Linking of File

C Operators - C has a rich set of operators. They may operate on a single operand or two operands. They
are used to perform basic arithmetic operations, comparisons, manipulation of bits and so on.

Programming in C (B.Sc.IT) Page 8


Unary Operators- An operator that acts upon only one operand is known as a unary operator.

1. Unary minus – any unary minus operator gets its value changed to negative.

e.g: Let a=3,b=4;

c=a + (-b)

= 3 + (-4)

= -1

2. Logical NOT operator- is used to obtain the logical complement of the operand. If value is true
(1) then answer will be false(0) and if value is false(0) then answer will be true(1).

e.g: Let a=30, c=0;

b=(!a); //answer is b=0

b=(!c); //answer is b=1

3. Bitwise complementation – It is used to obtain the one’s complement of a binary sequence. This
means that each zero gets changed to one and each one gets changed to zero.

e.g: Let a=10;

b=(~a); // answer is b=5

binary value of 10 will be 1010 so ~1010 will be 0101 so the answer is 5.

Programming in C (B.Sc.IT) Page 9


Binary Operators- These operators act upon two operands.

Arithmetic Operator-

Example :

int N1,N2;
N1=5;
N2=3;
N1+N2 //8
N1-N2 //2
N1*N2 //15
N1/N2 //1
N1%N2 //2
Logical Operators –

Programming in C (B.Sc.IT) Page 10


Logical AND – It is equivalent to multiplication operation. The result is true(1) when both the operands
will be true(1) and the result will false(0) when any of the operands have value false(0).
Logical OR - It is equivalent to addition operation. The result is true(1) when any of the operands will be
true(1) and the result will false(0) when both operands have value false(0).
Logical NOT – The result is true(1) when the operand value will be false(0) and the result will be false(0)
when the value of operand will be true(1).
Example: a&&b||c&&(!b)
2&&4||3&&(!4)
2&&4||3&&0
2&&4||0
1||0
1
Relational Operator-

Example : int a=5,b=8;


a>b //false(0)
a<b //true (1)

Programming in C (B.Sc.IT) Page 11


Bitwise Operator

Bitwise AND result will be 1 when both bits are 1 otherwise it is a 0. Bitwise OR result will be 1 when any
of bits is 1 otherwise it is 0. Bitwise XOR result will be 1 when both bits are different otherwise it is 0.
Example: int a=4,b=3,c;
c=a&&b // answer is 1
c=a&b //answer is 0
c=a||b // answer is 1
c=a|b //answer is 7
c=a^b // answer is 7
Bitwise complement (~) is an unary operator that reverse the state of each bit.
Example: int a=10,b;
b=~a; //answer is 5
Bitwise left shift operator shifts the bits towards Left and right shift operator shifts the bits towards
right.
Example: int x=128,y=32;
x=x>>1; //answer is 64
y=y<<2; // answer is 128

Ternary Operator- is a conditional operator in c.

Syntax: <expression>? <value> : <value>


Example : int a=5,b=7;
c=a>b?a:b
5>7?5:7 // answer is 7

sizeof() Operator- It operator returns the size(i.e number of bytes) of the operand.

Syntax: sizeof(operand);
Example: x= sizeof(int) //2
float sum;
y=sizeof(sum) //4

Programming in C (B.Sc.IT) Page 12


Increment/decrement operator-
Increment operator is used to increment the value of an integer incremented by 1.symbol
Represented by ‘++’. This symbol can be placed before or after the integer variable.
Decrement operator is used to decrement the value of an integer decremented by 1.symbol
Represented by ‘--’. This symbol can be placed before or after the integer variable.
Example:
1. int x=14,y=16;
printf(“%d\t%\td%\td%d”,++x,y--,++y,x--);
// answer is 14 17 17 14
printf(“%d\t%d”,x,y);
2. int a=20,b=30;
a++;
++b;
--a;
a++;
printf(“%d\t%d”,a,b);
// answer is 21 31

Precedence of all operators in C

Programming in C (B.Sc.IT) Page 13


Example:
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int x=4,y;
y=sqrt(4);
printf(“%d”,y); //2
getch();
}

Programming in C (B.Sc.IT) Page 14


Control Statements-
It defines order of execution of statements in a program.
• Conditional control statements
• goto statements
Conditional control statements – In some situations, it is necessary to check the condition
To make the decision whether a condition gets true or false depending on these set of instruction will be
executed. C provides a variety of conditional control statement
• if statements
• if-else statements
• Nested-if-statement
• switch statements

if-statements - It is a simple if-statement. It is called a one way branching. If logical condition gets true
then set of Statement that immediately follows if is executed otherwise control transfer to the next
executable statement.

Syntax:
if(condition)
{
statements;
}

Programming in C (B.Sc.IT) Page 15


if-else statement - It is used to execute only one action. If there are two statements to be executed
alternatively, then if else statement is used. It is a two way branching. (when there is two option) for
more than two option use if-else if – else .

Syntax:
if(condition)
{
statements;
}
else
{
statements;
}

Nested if- if within if we called as nested if condition.

Syntax:
if(condition)
{
if (condition)
{
statements;
}
statements;
}

Programming in C (B.Sc.IT) Page 16


switch statements- The switch statement provides a multiple way branching. That is, it allow the user to
select any one of the several alternatives, depending on the value of an expression. Expression is of type
int or char.

Syntax:
switch(expression)
{
case label1: block1;break;
case label2: block2;break;
:
case default: default block; break;
}
#include<stdio.h>
#include<conio.h>
void main()
{
int n;
printf(“Enter a number”);
scanf(“%d”,&n);
switch(n)
{
case 1: printf(“Sunday\n”);break;
case 2: printf(“Monday\n”);break;
case 3: printf(“Tuesday\n”);break;
case 4: printf(“Wednesday\n”);break;
case 5: printf(“Thrusday\n”);break;
case 6: printf(“Friday\n”);break;
case 7: printf(“Saturday\n”);break;
default : printf(“Invalid\n”);break;
}
}

goto statement- in C programming provides an unconditional jump from the 'goto' to a labeled
statement in the same function.
Syntax:
goto label;
.. .
label: statement;
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
int num=1,sum=0;
t: sum=sum+num;
num+=1;

Programming in C (B.Sc.IT) Page 17


goto t;
printf(“Sum=%d\n”,sum);
getch();
}

Loop Control Structures:


Looping is a powerful programming technique, through which a group of statements is executed
repeatedly, until certain specified condition is satisfied.
The control statement can be placed either before or after the body of the loop. If the control statement
is placed before the body of the loop, it is called the entry- controlled loop(while and for loop). If the
control statement is written after the body of the loop, it is called the exit controlled loop.
C provides three types of loop control structure
1. The while statement
2. The do-while statement
3. The for statement

while loop – it is used to execute a set of statements repeatedly as long as the specified condition is
true. Syntax:
while(condition)
{
Statements;
}
// program to print first 10 natural number using while loop
#include<stdio.h>
#include<conio.h>
void main()
{
int i=1;
while(i<=10 )
{
printf(“%d\n”,i);
}
getch();
}
do-while loop – it is used to execute a set of statements repeatedly, until the condition gets false. This is
called post-test loop because the condition for repeatition made at end.
Syntax:
do
{
Statements;
}while(condition);

Programming in C (B.Sc.IT) Page 18


// program to print first 10 natural number using do-while loop
#include<stdio.h>
#include<conio.h>
void main()
{
int i=1;
do
{
printf(“%d\n”,i);
} while(i<=10 );
getch();
}

for loop- is used when the programmer knows how many times a set of statements are executed.
Syntax:
for(intilatization;condition,increment/decrement)
{
Statements;
}
// program to print first 10 natural number using for loop
#include<stdio.h>
#include<conio.h>
void main()
{
int i;
for(i=1;i<=10;i++ )
{
printf(“%d\n”,i);
}
getch();
}

Programming in C (B.Sc.IT) Page 19


Inner loop
Loop inside loop is called inner loop.
Example: while() for() for()
{ { {
for() while() for()
{ { {
//statements //statements //statements
} } }
} } }

Pattern printing example:


1. * 2. A 3. 1
** AB 23
*** ABC 456
**** ABCD 7 8 9 10
***** ABCDE
#include<stdio.h> #include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h> #include<conio.h>
void main() void main() void main()
{ { {
int i,j; int i,j, k=65; int i,j,m=0;
for(i=0;i<5;i++) for(i=0;i<5;i++) for(i=0;i<4;i++)
{ { {
for(j=0;j<=i;j++) for(j=0;j<=i;j++) for(j=0;j<=i;j++)
{ { {
printf(“*”); printf(“%c”,k); m++;
} } printf(“%d”,m);
printf(“\n”); printf(“\n”); }
} } printf(“\n”);
getch(); getch(); }
} } getch();
}

Programming in C (B.Sc.IT) Page 20


Storage Classes
A variable in C can have anyone of four storage classes:
1. Automatic storage class 2. Register storage class
The auto keyword is applied to all local The register variable allocates memory in
variables automatically. It is the default register than RAM. Its size is same of
storage class that is why it is known as register size. It has a faster access than
automatic variable. other variables.
#include <stdio.h> It is recommended to use register variable
#innclude<conio.h> only for quick access such as in counter.
void main(){ #include <stdio.h>
int a=10; #innclude<conio.h>
auto int b=10;//same like above void main(){
printf("%d %d",a,b); register int count,sqr;
getch(); for(count=1;count<=10;count++)
} {
sqr=count*count;
printf("%d”,sqr);
}
getch();
}

3. Static storage class 4. Extern storage class


The static variable is initialized only once The extern variable is visible to all the
and exists till the end of the program. It programs. It is used if two or more files are
retains its value between multiple sharing same variable or function.
functions call. #include<stdio.h>
The static variable has the default value 0 #include<conio.h>
which is provided by compiler. void main()
#include <stdio.h> {
#innclude<conio.h> extern int num=500;
void main(){ output();
int n; }
for(n=1;n<=3;n++) void output()
{ {
staticfun(); Printf(“%d”,num);
} }
getch();
}
void staticfun()
{
static int s=0;
s=s+10;
printf(“s=%d\n”,s);
}

Programming in C (B.Sc.IT) Page 21


Arrays
Array is a collection of homogeneous data elements. These elements may be of type int, float,char or
double. All these elements are stored in consecutive memory locations (on RAM ) .
An array is described by a single name or an identifier. And each individual data item in the array is
referenced by a subscript (or index) enclosed in a pair of square brackets.
Example : int num[5];

10 16 78 11 45
num 0 1 2 3 4
Here, 0,1,2,3 & 4 are subscripts or index.
num[0] -> Indicates the first element in an array num.
num[1] -> Indicates the second element in an array num.
num[2] -> Indicates the third element in an array num.
num[3] -> Indicates the fourth element in an array num.
num[4] -> Indicates the fifth element in an array num.
note: if we want to take 50 numbers from user so for that we can’t take individual variable instead of we
must use array.

Classification of arrays
Generally, arrays are classified into one-dimensional array and multi-dimensional arrays. Further, the
multi-dimensional arrays are classified into two-dimensional, three dimensional and so on n-
dimensional array.

One-dimensional array
It is a linear list of fixed number of data items of the same type. All these data items are accessed using
the same name using the same name using a single subscript. It is also called as single dimensional array.

Programming in C (B.Sc.IT) Page 22


Syntax of one-dimensional array:
data_type arrayname[size];
Here, arrayname -> name of array
size -> size must be an integer constant.
Example: int list[20]; //list is an integer array of size 20 so we can store maximum 20 elements.
char name[20]; //name is a character array of size 20 so we can store max 20 elements.
float xyz[5]; // xyz is a floating array of size 5 so we can store maximum 5 elements.
double p[100]; // p is a double array of size 100 so we can store maximum 100 elements.

/* WAP in C to take 5 elements in array as user /* WAP in C to take 5 elements in array as


input and display it. */ initialized and display it. */
#include <stdio.h> #include <stdio.h>
#include<conio.h> #include<conio.h>
void main() void main()
{ {
int a[5],i; int a[5]={ 18,54,23,78,15};
printf(“Enter 5 elements in array\n”); printf(“Elements in array are:\n”);
for(i=0;i<5;i++) for(i=0;i<5;i++)
{ {
scanf(“%d”,&a[i]); printf(“%d”,a[i]);
} }
printf(“Elements in array are:\n”); getch();
for(i=0;i<5;i++) }
{
printf(“%d”,a[i]);
}
getch();
}

Two-dimensional array
It is an ordered table of homogeneous elements. It is generally, referred to as a matrix, of some rows
and some columns. It is also called as a two-subscripted variable.
Syntax of two-dimensional array:
data_type arrayname [rows][columns];
example: int a[2][2]; // a is an integer array of 2 rows and two columns and store maximum 4 elements.

Programming in C (B.Sc.IT) Page 23


/* WAP in C to take 2X2 matrix as user input and /* WAP in C to take 2X2 matrix as initialized and
display it. */ display it. */
#include <stdio.h> #include <stdio.h>
#include<conio.h> #include<conio.h>
void main() void main()
{ {
int a[2][2],i,j; int a[2][2]={2,3,6,7};
printf(“Enter 5 elements in array\n”); printf(“Elements in matrix are:\n”);
for(i=0;i<2;i++) for(i=0;i<2;i++)
{ {
for(j=0;j<2;j++) for(j=0;j<2;j++)
{ {
scanf(“%d”,&a[i][j]); printf(“%d”,a[i][j]);
} }
} printf(“\n”);
printf(“Elements in matrix are:\n”); }
for(i=0;i<2;i++) getch();
{ }
for(j=0;j<2;j++)
{
printf(“%d”,a[i][j]);
}
printf(“\n”);
}
getch();
}

Functions
If a program is too lengthy then we can break them in small units called module or subprogram.
A function is a set of instructions to carry out a particular task. For example, finding the square or cube
of a given number. The function returns a single value.
Generally, the functions are classified into standard functions and user-defined functions. The standard
functions are also called library functions or built in functions. All standard functions such as
sqrt(),abs(),log(),sin(),pow() etc. are provided in the library of functions.
Syntax of function:
data_type name_of_the_function(Parameter list)
{
//variable declaration;
//statements;
//return (value);
}

Programming in C (B.Sc.IT) Page 24


Example:
//WAP in C to find sum of two nos using function //WAP in C to find sum of two nos using function
#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
int addnum(int x,int y); //function declaration /*Function to add two nos.*/
void main() int addnum(int val1, int val2)
{ {
int n1,n2,result; int sum;
printf(“enter two nos.\n”); sum=val1+val2;
scanf(“%d%d”,&n1,&n2); return(sum);
result=addnum(n1,n2); }/* end of function*/
printf(“The sum of %d and %d=%d\n”,n1,n2,result); void main()
getch(); {
}/*end of main */ int n1,n2,result;
/*Function to add two nos.*/ printf(“enter two nos.\n”);
int addnum(int val1, int val2)//function defination scanf(“%d%d”,&n1,&n2);
{ result=addnum(n1,n2);
int sum; printf(“The sum of %d and %d=%d\n”,n1,n2,result);
sum=val1+val2; getch();
return(sum); }/*end of main */
}/* end of function*/

Category of functions:
1. No argument no return value 2. Arguments but no return value
#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
void test() int addnum(int val1, int val2)
{ {
printf(“You are in function\n”); int sum;
} sum=val1+val2;
void main() printf(“sum =%d\n”sum);
{ }
printf(“You are in main function”); void main()
test(); {
getch(); int n1,n2,result;
} printf(“enter two nos.\n”);
scanf(“%d%d”,&n1,&n2);
addnum(n1,n2);
getch();
}

Programming in C (B.Sc.IT) Page 25


3. no arguments but return value 4.Arguments and return value
#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
int addnum() int addnum(int val1, int val2)
{ {
int n1,n2,sum; int sum;
printf(“enter two nos.\n”); sum=val1+val2;
scanf(“%d%d”,&n1,&n2); return(sum);
sum=n1+n2; }
return(sum); void main()
} {
void main() int n1,n2,result;
{ printf(“enter two nos.\n”);
int result; scanf(“%d%d”,&n1,&n2);
result= addnum(); result=addnum(n1,n2);
printf(“sum is=%d”,result); printf(“sum =%d\n”result);
getch(); getch();
} }

Parameter Passing Mechanisms


It is a mechanism through which arguments are passed to the called function for the required
processing. There are two methods of parameter passing
1. Call by value – When the values of arguments are passed from the calling function to a called
function, the values are copied into the called function. If any changes are made to the values in the
called function, there is no change in the original values within the calling function.
2. Call by reference- In this method, the actual values are not passed, instead their addresses are passed.
There is no copying of values since their memory locations are referenced. If any modification is made to
the values in the called function, then the original values get changed within the calling function.
//Call by value //Call by reference
#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
void Fun(int t1,int t2) void Fun(int *t1,int *t2)
{ {
t1=t1+5; int t;
t2=t2+5; t=*t1;
} *t1=*t2;
void main() *t2=t;
{ }
int x=6,y=7; void main()
printf(“x=%d and y=%d\n”,x,y); {
Fun(x,y); int x=6,y=7;
printf(“x=%d and y=%d\n”,x,y); printf(“x=%d and y=%d\n”,x,y);
getch(); Fun(&x,&y);
} printf(“x=%d and y=%d\n”,x,y);
getch();
}

Programming in C (B.Sc.IT) Page 26


Recursion Function
Recursion is the technique which performs a particular task is repeatedly calling itself.
Example:
#include<stdio.h>
#include<conio.h>
int rec_fun(int n)
{
int fact;
if(n==0)
return(1);
else
fact=n*rec_fun(n-1);
return(fact);
}
void main()
{
int num,temp;
printf(“enter the number\n”);
scanf(“%d”,&num);
temp=rec_fun(num);
printf(“Factorial of %d=%d\n”,num,temp);
getch();
}

STRUCTURE

A structure is a meaningful collection of data items of different type under a unique name.
For example: We want to store some information about a person: his/her name, citizenship number and
salary. We can easily create different variables name, citNo, salary to store these information separately.
However, in the future, you would want to store information about multiple persons. Now, we need to
create different variables for each information per person: name1, citNo1, salary1, name2, citNo2,
salary2.
We can easily visualize how big and messy the code would look. A better approach will be to have a
collection of all related information under a single name Person, and use it for every person. Now, the
code looks much cleaner, readable and efficient as well.
Syntax of structure
struct structure_name
{
data_type member1;
data_type member2;
data_type memeber;
};

Programming in C (B.Sc.IT) Page 27


Example: // For single student information
struct Student struct Student
{ {
int rollno; int rollno;
char name[30]; char name[30];
char course[20]; char course[20];
}s1; }
struct Student s1;

//For multiple student information


struct Student struct Student
{ {
int rollno; int rollno;
char name[30]; char name[30];
char course[20]; char course[20];
}s[10]; }
struct Student s[10];
#include<stdio.h>
#include<conio.h>
void main()
{
struct student
{
char name[50];
int roll;
float marks;
} s;
printf("Enter information:\n");
printf("Enter name: ");
scanf("%s", s.name);
printf("Enter roll number: ");
scanf("%d", &s.roll);
printf("Enter marks: ");
scanf("%f", &s.marks);
printf("Displaying Information:\n");
printf("Name: ");
puts(s.name);
printf("Roll number: %d\n",s.roll);
printf("Marks: %.1f\n", s.marks);
getch();
}

Programming in C (B.Sc.IT) Page 28


UNION
Unions are quite similar to structures in C. Like structures, unions are also derived types.
Syntax of union
union union_name
{
data_type member1;
data_type member2;
data_type memeber;
};
Example: // For single student information
union Student union Student
{ {
int rollno; int rollno;
char name[30]; char name[30];
char course[20]; char course[20];
}s1; }
union Student s1;

//For multiple student information


union Student union Student
{ {
int rollno; int rollno;
char name[30]; char name[30];
char course[20]; char course[20];
}s[10]; }
struct Student s[10];
#include<stdio.h>
#include<conio.h>
void main()
{
union student
{
char name[50];
int roll;
float marks;
} s;
printf("Enter information:\n");
printf("Enter name: ");
scanf("%s", s.name);
printf("Enter roll number: ");
scanf("%d", &s.roll);
printf("Enter marks: ");

Programming in C (B.Sc.IT) Page 29


scanf("%f", &s.marks);
printf("Displaying Information:\n");
printf("Name: ");
puts(s.name);
printf("Roll number: %d\n",s.roll);
printf("Marks: %.1f\n", s.marks);
getch();
}

Difference between structure and union


Each member within a structure is assigned its own memory location. But the union members, all share
a common memory location.

The amount of memory required to store a structure variable is the sum of memory size of all members.

But, the memory required to store a union variable is the memory required for the largest element of an
union.

Programming in C (B.Sc.IT) Page 30


STRING FUNCTIONS IN C

Example:
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char name[20];
int length;
printf(“Enter your name\n”);
scanf(“%s”,name);
length=len(name);
printf(“Length of your name=%d”,length);
getch();
}

Programming in C (B.Sc.IT) Page 31


//String Copy //String Compare
#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
#include<string.h> #include<string.h>
void main() void main()
{ {
char s1[20]; char s1[20],s2[20];
strcpy(s1,”Welcome”); printf(“Enter First String\n”);
printf(“%s”,s1); gets(s1);
getch(); printf(“Enter Second String\n”);
} gets(s2);
if(strcmp(s1,s2)==0)
printf(“Strings are identical\n”);
else
printf(“Strings are not identical\n”);
getch();
}

//String Reverse
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char s[20];
printf(“Enter String\n”);
gets(s);
printf(“Reverse of string=%s”,strrev(s));
getch();
}

Programming in C (B.Sc.IT) Page 32


Pointers
The pointer is special type of variables that hold the address of the variables, structures and functions
that are used in the program. It contains only the memory location of the variable.

Advantages of Pointer:
 Pointers provide direct access to memory
 Pointers provide a way to return more than one value to the functions
 Reduces the storage space and complexity of the program
 Reduces the execution time of the program
 Provides an alternate way to access array elements
 Pointers allows us to perform dynamic memory allocation and deallocation.
 Pointers allows us to resize the dynamically allocated memory block.
 Addresses of objects can be extracted using pointers.

Operators used in Pointer are & and *.


& (ampersand) means ‘address of’ operator and * (asterik) means ‘value at the address of’ operator.
Example: int i;
i Location Name
8 Value at location

6485 Location no. (Address)

void main()
{
int i=8;
int *j; //j is a pointer to integer means j is pointing to integer variable.
j=&i;
printf(“i=%d\n”,i);
printf(“i=%d\n”,*j); //
getch();
}
O/P
i=8
i=8

Note: If we want to point integer variable then we must use integer pointer and for float use float
pointer and so on.

Programming in C (B.Sc.IT) Page 33


Example : int i=67;
float j=3.14;
int *a;
float *b;
a=&i;
b=&j;

Bin eq. of 67 Binary equivalent of 3.14

2008 2009 7006 7007 7008 7009

2008 7006
7602 9118

In above figure, i is an integer variable of 2 bytes that why its address sequence is 2008 & 2009 which
pointed by pointer a, which hold the address of i. Similarly j is floating point variable of size 4 bytes and
pointer b points to j.

// Program for call by reference // Pointers and Array


#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
void swap(int *x.int *y) void main()
{ {
int t; int num[]={24,34,12,44,56,17};
t=*x; int i=0,*j;
*x=*y; j=&num[0];
*y=t; while(i<5)
} {
void main() Printf(“element=%d”,*j);
{ i++;
int a=10; j++;
int b=20; getch();
swap(&a,&b); }
printf(“a=%d\n”,a); }
printf(“b=%d\n”,b);
}

Programming in C (B.Sc.IT) Page 34


File Handling

A file represents a sequence of bytes on the disk where a group of related data is stored.
File is created for permanent storage of data. We can read content from file and perform
operation according to our requirement and can also write to file.
In C language, we use a structure pointer of file type to declare a file.
FILE *fptr.

Function Description

fopen() create a new file or open a existing file

fclose() closes a file

getc() reads a character from a file

putc() writes a character to a file

fscanf() reads a set of data from a file

fprintf() writes a set of data to a file

getw() reads a integer from a file

putw() writes a integer to a file

fseek() set the position to desire point

ftell() gives current position in the file

rewind() set the position to the begining point

Programming in C (B.Sc.IT) Page 35


mode Description

r opens a text file in reading mode

w opens or create a text file in writing mode.

a opens a text file in append mode

r+ opens a text file in both reading and writing mode

w+ opens a text file in both reading and writing mode

a+ opens a text file in both reading and writing mode

rb opens a binary file in reading mode

wb opens or create a binary file in writing mode

ab opens a binary file in append mode

rb+ opens a binary file in both reading and writing mode

wb+ opens a binary file in both reading and writing mode

ab+ opens a binary file in both reading and writing mode

Programming in C (B.Sc.IT) Page 36


There are two types of files
1. Text file (.txt)
2. Binary file (.bin)

Difference between Append and Write Mode


Write (w) mode and Append (a) mode, while opening a file are almost the same. Both are used to write
in a file. In both the modes, new file is created if it doesn't exists already.
The only difference they have is, when you open a file in the write mode, the file is reset, resulting in
deletion of any data already present in the file. While in append mode this will not happen. Append
mode is used to append or add data to the existing data of file(if any). Hence, when you open a file in
Append(a) mode, the cursor is positioned at the end of the present data in the file.

//Writing to a text file //Reading from a text file


#include <stdio.h> #include <stdio.h>
#include<conio.h> #include<conio.h>
#include<stdlib.h> #include<stdlib.h>
int main() void main()
{ {
int num; int num;
FILE *fptr; FILE *fptr;
fptr = fopen("C:\\program.txt","w"); fptr = fopen("C:\\program.txt","r");
if(fptr == NULL) if (fptr== NULL)
{ {
printf("Error!"); printf("Error! opening file");
exit(1); exit(1);
} }
printf("Enter num: ");
scanf("%d",&num); fscanf(fptr,"%d", &num);
fprintf(fptr,"%d",num); printf("Value of n=%d", num);
fclose(fptr); fclose(fptr);
getch(); getch();
} }

Programming in C (B.Sc.IT) Page 37

You might also like