C Book

Download as pdf or txt
Download as pdf or txt
You are on page 1of 104

C-LANGUAGE

A computer is an electronic device which accept instruction from user


and according to user sended instruction it produce result.
Computer knows only one language that is binary language. As a
programmer when we required to interact with a computer we need a
communication channel called programming language.
A programming language is a special kind of instructions which is used
to communicate with computer.
As a programmer if we knows the programming language then it is not
possible to interact with computer because computer can understand
binary code only.
In above case, recommended to use translator. As a programmer if the
instruction came from programming language, translator will converts
programming language code into binary format.

PL Binary
Programmer Translator Computer Software

Trnaslators:
A translator is a system software which converts programming language
code into binary format.
Translators are 3 types:
1. Compiler
2. Interpreter
3. Assembler
Compiler: - It is a system software which converts programming language
code into binary format in a single step except those lines are having error.

Interpreter: - It is a system software which converts programming


language code into binary format step by step that is line by line
compilation takes place.
(When first error is occur it stop compilation process)

Assembler: - By using assembler we can convert assembly language


instructions into binary format.

“C” is a programming language developed at AT&T Bell Laboratories of


USA in 1972. It was designed and written by Dennis Ritchie.
History of “C”
In 1960, computer languages are designed for specific purpose. For
example, COBOL was being used for commercial Applications,
FORTRAN is used for Engineering and Scientific purposes. At this stage
people started thinking that instead of learning and using so many
languages, each for different purpose, why not use only one language,
which can program all possible applications.

1
C-LANGUAGE

Therefore, an international committee was developing such a


language called “ALGOL”(Algorithmic Language). However, ALGOL 60
never really became popular it seemed too abstract, too general.
To reduce the limitations of “ALGOL” language to create a new
language is called “CPL” [Combined Programming Language] was
developed at Cambridge University. However, CPL turned out to be so
big, having so many features, that it was hard to learn and difficult to
implement.
“BCPL”[Basic Combined Programming Language] developed by
Martin Richards at Cambridge University aimed to solve this problem by
bringing CPL. But unfortunately it turn out to be too less powerful and too
specific. At the same time a language called “B” was written by Ken
Thomson at AT&T(American Telephone and Telegraph) Bell Laboratories,
as a further simplification of CPL. But like BCPL, B too turned out to be
very specific.
The “BCPL” and “”B” are types less languages. “C” is a type
language. Ritchie inherited the features of “BCPL” and “B”.
In the year of 1972 Dennis Ritchie devoloped C programming
language at AT&T Bell laboratories for developing system software.
In the year of 1978, Dennis Ritchie and Brian Kemighan released
next version of C language K&R-C.
K&R introduced several language features:
1. Standard I/O library.
2. long int datatype.
3. Unsigned int datatype.
4. Compound assignment operators (+=,/=…)
5. void functions
6. enumerated types.
7. Functions returning struct or union.

In the year of 1988, ANSI is released next version C language called


ANSI-C (American National Standard Institute).
ANSI-C introduced several language features:
1. Function prototypes
2. void pointers.
3. Support for international character set.
4. Preprocessor enhancements

In the year of 2000, ISO standard C is released called C99.


C99 introduced several language features:
1. Inline functions
2. Variable length arrays.
3. IEEE 754 floating point.
4. Variadic Macros

2
C-LANGUAGE

On the 8th of December 2011, latest version of C is released with the name
called C11.
C11 introduced several language features:
1. Anonymous structures.
2. Improved Unicode support.
3. Bounds checked functions.
4. Generic Macros

Applications of C
C programming language can be used for different types of applications
like:
- System software development that is operating systems and
compiler. Unix operating system is developed by using “C”.
- Graphic related applications like PC and Mobile games.
- Application software development.
- Any kind of mathematical expressions can be evaluated,

C is a high level procedure oriented structured programming


language.
Which programming language is syntactically similar to English and easy
to understand is called high level language.
When the programming language supports module or function
implementation then it is called procedure oriented language.
Top down approach in the form of blocks is called structured programming
language.

“C” is a middle level language. “C” stands between two types of


languages it is good programming efficiency (as compared to machine
oriented languages) and relatively good machine efficiency (as compared
to problem oriented languages).

Structure of a “C” program: -


preprocessor directives
main()
{
Declaration of variables;
Input statements;
Expression statements;
Output statements;
}

Rules for write a program in “C”: -


1) Every statement ends with a semicolon (;).
2) “C” is case sensitive.
3) All key words are in lower case.

3
C-LANGUAGE

4) Key words cannot be used for any other purpose like variable
names (or) function names.

Key words: -
There are 32 key words in “C”.
auto, break, case, char, const, continue, default, do, double , else, enum,
extern, float, for, goto, if, int, long, register, return, short, signed, size of,
static, struct, switch, type def, union, unsigned, void, volatile, while

Constants: - It is a fixed one never change during the execution of a


program.
In C language constants are classified into two types:
1. Alpha numeric constants.
2. Numeric constants.
Alpha numeric constants: - By using this constant we can represent
alphabets and 0-9 numbers.
Alpha numeric constants are classified into two types:
a. Character constant.
b. String constant.
Any data if we are representing in single quotes then it is called character
constant.
Ex: ‘A’, ‘d’, ‘t’, ‘5’, ‘#’
When we are representing the data within the double quotes then it is
called string constant.
Ex: “satish”, “hello”
Numeric constant: - By using numeric constant we can represent value
type data numeric constant are classified into two types:
a. Integer
b. Float
When we are representing the numeric values without any fraction parts
then it is called integer.
Ex: 12, -45, 1234…
When we are representing the numeric values with fractional parts then it
is called float.
Ex: 12.3, 12.34, 98.0…

Preprocessor directives:-
These are used to pass the instructions to the compilers. This is
always begin with a hash(#) sign. Two most frequently used directives are
#include and #define.

i) #include:- It is used to instruct the compiler to include a header file.


Specified with in angled brackets(< >) or double codes(“ “). Header files
are generally have an extension of .h. The # sign indicates the statement
is an instruction to the pre compiler.

4
C-LANGUAGE

#include<stdio.h>
stdio.h stands for Standard Input and Output header file.
Ex: printf(),scanf()….
#include<math.h>
Ex: sqrt(),pow(),sin()
#include<string.h>
Ex: strlen(), strcmp()
ii) #define:- This is used to modify programs by declaring and defining a
word as representing a constant value.
#define A 10
#define PI 3.14
The pre compiler substitute the value of 3.14 whenever “PI” is appears.

main():- Every “C” program should contain at least one function i.e
main(). Every program execution starts at main function. Every
program should contain only one main().

Declaration of variables:-
Variable:- Variable is used to refer the memory location where a
particular value is to be stored.
Rules for defining variables:-
1) Every variable starts with alphabet.
2) Commas(,) or blank spaces are not allowed. It allows only a
special character i.e,underscore(_).
3) Variables are case sensitive.
4) Variables names cannot be same as keywords.
5) Max. length of variable is 32 characters.
Data type:-
A data type decides the amount of memory allocated to a variable to
store a particular type of data.
“C” has five basic data types. They are char, int, float, double, void.

Data type Size Range


char 1 -128 to127
int 2 -32,768 to 32,767
long int 4 -2,14,74,83,647to 2,14,74,83,646
float 4 -3.4e38 to 3.4e38
double 8 -1.7e308 to 1.7e308

Rules for character data type :- It is used to store a single character of


information. A char type must be enclosed in single quotes .
Ex:-
char s;
s=’a’.

5
C-LANGUAGE

Rules for int data type :- An int data type must have at least one digit it
accepts only whole numbers. It does not have a decimal point.
Ex: int a;
a=10;
a=10.5 //10.

Rules for float data type:- It accepts both whole numbers and fractional
numbers.
Ex: float a;
a=10;
a=10.5;

Format specifies:-
Char  %c
int  %d
float  %f
long int  %ld
double  %lf

string  %s
Escape sequences:-
\n  next line
\t  tab space
\0  null value

Operators :- Operator is a special kind of symbol which perform a


particular task.
1) Arithmetic operators :- +, -, *, /,%, ^.
2) Relational operators :- <, >, <=, >=, ==, != or <>.
3) Logical operators :- and (&&), or(||), not(!).
4) Arithmetic assignment operators :-+=, -=, *=, /=, %=.
5) Increment & decrement operators :- ++,--.
6) Conditional operators :- ?, :.
7) Bit wise operators:- shift left(<<), shift right(>>), complement(~).
8) Special operators:- comma (,)
The ‘sizeof()’ operator : The ‘size of()’ is a compile time operator and
when used with an operand returns the number of bytes the operand
occupies.
Ex: sizeof(int) =2

Comments in ‘C’:
Comments in C begin with /*……………………. */.
These are ignored by the C compiler.

Input and Out put functions:-


putchar():- This is used to display character on the screen.

6
C-LANGUAGE

Syntax :-
putchar(character); or
putchar(variable name);
Ex: putchar(‘A’); or ch=B
putchar(ch);

#include<stdio.h>
main()
{
char ch;
ch=’R’;
putchar(ch);
putchar(‘*’);
}

puts():- It is used to display information on the screen.


Syntax :-
puts(“Information”); or
puts(variable);
Ex:- puts(“ APEL COMPUTER EDUCATION”);
#include<stdio.h>
main()
{
puts(“This is my first program”);
}

printf():- This is used to display particular information on the screen.


Syntax:
printf(“Format string with data specifiers”,variable);
Eg: int a=10;
printf(“A value is %d”,a);

#include<stdio.h>
main()
{
char ch;
int a;
long int b;
float c;
double d;
clrscr();
ch='A';
a=55;
b=45000;
c=4.5;
d=123.444;

7
C-LANGUAGE

printf("\n character is %c\t",ch);


printf("\n integer is %d\t",a);
printf("\n long int is %ld\t",b);
printf("\n float is %f\t",c);
printf("\n double is %lf\t",d);
getch();
}

clrscr():- It is used to clear the screen.


getch():- It is used to stop the program execution temporarily.

getchar():- It reads a character from the keyboard and waits for carriage
return.
Syntax:- variable=getchar();
Eg:- ch=getchar();

#include<stdio.h>
main()
{
char ch;
clrscr();
puts("Enter a character:\t");
ch=getchar();
printf("characters is %c\t",ch);
getch();
}

getche():- It is used to read a character from the keyboard and does not
waits for carriage return.
Syntax:- variable=getche();
Ex: ch=getche();

#include<stdio.h>
main()
{
char ch;
clrscr();
puts("Enter a character:\t");
ch=getche();
printf("characters is %c\t",ch);
getch();
}
gets():- It reads a string from the keyboard.
Syntax:- gets(variable);
Ex: gets(s);

8
C-LANGUAGE

#include<stdio.h>
main()
{
char s[30];
clrscr();
puts("Enter a name:\t");
gets(s);
printf("name is %s\t\t",s);
getch();
}

scanf():- It reads any type of data from the keyboard.


Syntax:- scanf(“Format specifier”, &variable);
Ex: int a;
scanf(“%d”,&a);

#include<stdio.h>
main()
{
char ch,s[20];
int a;
long int b;
float c;
double d;
clrscr();
printf("Enter a character");
scanf("%c",&ch);
printf("Enter a integer value");
scanf("%d",&a);
printf("Enter a long integer");
scanf("%ld",&b);
printf("Enter a float value");
scanf("%f",&c);
printf("Enter a double");
scanf("%lf",&d);
printf("Enter a string");
scanf("%s",&s);
getch();
}

Accept two numbers and display the sum.


#include<stdio.h>
main()
{
int a,b,sum;
clrscr();

9
C-LANGUAGE

printf("Enter two numbers \t");


scanf("%d%d",&a,&b);
sum=a+b;
printf("sum is %d",sum);
getch();
}

 Designing a program on Linux OS.


- Open the terminal and type following command:
vi <filename>.c
Ex:
vi file1.c
- To make typing enable just press “i" button and type program.
Ex:
#include<stdio.h>
int main()
{
printf("Satish");
return 0;
}
- Press “Esc” button, then write following command.
:wq
- For compiling and linking the page, we are required to use
following command.
gcc –o file1 file1.c
- To load or execute the program, we required to use following
command:
./file1

Calculate the area of the triangle.


#include<stdio.h>
main()
{
int b,h,area;
clrscr();
printf("Enter base, height values \t");
scanf("%d%d",&b,&h);
area=0.5*b*h;
printf("area is %d",area);
getch();
}

Accept a number and display the square root of a given number.


#include<stdio.h>
#include<math.h>
main()

10
C-LANGUAGE

{
float a,s;
clrscr();
printf("Enter a number \t");
scanf("%f",&a);
s=sqrt(a);
printf("square is %f",s);
getch();
}

Exercises:
1) Calculate the simple interest.
2) Accept two numbers and swap them using third variable.
3) Accept roll number, name and three subjects of marks of student
and calculate the total, average and display roll number, name,
three subject of marks, total and average.
4) Accept two numbers and display the sum and average.
5) Accept n Kilometers and convert to meters.
6) Accept n meters and convert to kilometers.

11
C-LANGUAGE

Control Flow statements


In C programming language, control flow statements are classified into
three types:
1. Selection statements.
Ex: if, else, else if, switch
2. Iterative statements.
Ex: while,for, do-while
3. Jumping statements
Ex: break, continue, goto

SELECTION STATEMENTS
 These are also called decision making statements.
 By using them, we can create conditional oriented block.
 When we are working with selection statements, if condition is true
then block is executed, if condition is false then corresponding block
will be ignored.
a. if condition.
b. switch statement.
c. conditional operators.
d. goto statement.
if condition:-
simple if:-
syntax:-
if<condition>
{
statement(s);
}

Accept employee number, name and salary. if salary is greeter than


5000 then display the bonus is 500. Display the salary of the
employee.

#include<stdio.h>
main()
{
int empno,salary;
char name[25];
clrscr();
printf("enter employee number”);
scanf("%d”,&empno);
printf(“Enter employee name:”);
scanf(“%s”,&name);
printf(“Enter salary:”);
scanf(“%d”,&salary);
if(salary>5000)
{

12
C-LANGUAGE

salary=salary+500;
}
printf(“Salary=%d”,salary);
getch();
}

if-else statement:--
syntax:-
if<condition>
{
statement(s);
}
else
{
statement(s);
}

Accept two numbers and display the biggest number.


#include<stdio.h>
main()
{
int a,b;
clrscr();
printf("enter two numbers");
scanf("%d%d",&a,&b);
if(a>b)
printf("a is big");
else
printf("b is big");
getch();
}

if-else-if ladder statement:-


syntax:-
if<condition 1>
{
statements 1;
}
else
if< condition 2>
{
statements 2;
}
else
if< condition 3>
{

13
C-LANGUAGE

statements 3;
}
else
{
statement 4;
}

Accept three numbers and display the smallest number.


#include<stdio.h>
main()
{
int a,b,c;
clrscr();
printf("enter three numbers");
scanf("%d%d%d",&a,&b,&c);
if((a<b)&&(a<c))
printf("a is small");
else
if(b<c)
printf("b is small");
else
printf("c is small");
getch();
}

nested if
syntax:
if(condition1)
{
if(condition2)
{
statements1;
}
else
{
statements2;
}
}
else
if(condition3)
{
statements3;
}
else
{
statements4;

14
C-LANGUAGE

if condition1 is true then execution goes to condition2, if condition2 is true


then condition2 statements are executed. If condition2 is false then else
statements are executed.
If condition1 is false then execution goes to condition3.

Accept three numbers and display the biggest number.


#include<stdio.h>
main()
{
int a,b,c;
clrscr();
printf(“Enter three numbers:”);
scanf(“%d %d %d”,&a,&b,&c);
if(a>b)
{
if(a>c)
printf(“%d is big”,a);
else
printf(“%d is big”,c);
}
else
if(b>c)
printf(“%d is big”,b);
else
printf(“%d is big”,c);
getch();
}

Accept a character and display the character is capital letter or not.


#include<stdio.h>
main()
{
char ch;
clrscr();
printf("enter a character");
scanf("%c",&ch);
if(ch>=65&&ch<=90)
printf("CAPITAL LETTER");
else
printf("IT IS NOT CAPITAL LETTER");
getch();
}

15
C-LANGUAGE

Accept a number and display the number is positive or negative or


zero.
#include<stdio.h>
main()
{
int a;
clrscr();
printf("enter a value");
scanf("%d",&a);
if(a>0)
printf("%d IS POSITIVE",a);
else
if(a<0)
printf("%d IS NEGATIVE",a);
else
printf(“ZERO”);
getch();
}

Find the roots of quadratic equation.


#include<stdio.h>
main()
{
float a,b,c,r,r1,r2;
clrscr();
printf("enter the values of a,b,c");
scanf("%f%f%f",&a,&b,&c);
r=(b*b)-(4*a*c);
if(r<0)
printf("ROOTS ARE NOT POSSIBLE");
else
if(r==0)
{
r1=-b/2*a;
printf(“Roots are Equal\n”);
printf(“Root=%f”,r1);
}
else
{
r1=(-b+sqrt(r))/2*a;
r2=(-b-sqrt(r))/2*a;
printf("\nROOTS ARE R1=%f\nR2=%f",r1,r2);
}
getch();
}

16
C-LANGUAGE

Accept a number and display the number is even number or odd


number.
#include<stdio.h>
main()
{
int a,r;
clrscr();
printf("enter a number");
scanf("%d",&a);
r=a%2;
if(r==0)
printf("%d IS EVEN",a);
else
printf("%d IS ODD",a);
getch();
}

Exercises
1) Accept a character and display the character is capital letter or small
letter or digit or other special symbol.
2) Accept a character and display the character is vowel of consonant.
3) Accept a year and check the year is leap year or not.
4) Accept roll no, name and three subjects of marks and calculate the
total, average, result and class display the student details.

17
C-LANGUAGE

CONDITIONAL OPERATORS
Conditional operators are used to execute a condition in a single
line. This also called as ternary operation.

Syntax:
variable=(condition)? value if true: value if false.

If condition is true then value if true statements are executed.


If condition is false then value if false statements are executed.

Accept two numbers and display the smallest number.


#include<stdio.h>
main()
{
int a,b,small;
clrscr();
printf("enter two values");
scanf("%d%d",&a,&b);
small=(a<b)?a:b;
printf("SMALL IS %d",small);
getch();
}

Accept a number and display the number is even or odd.


#include<stdio.h>
main()
{
int a,b;
clrscr();
printf("enter a number");
scanf("%d",&a);
b=(a%2==0)?printf("EVEN"):printf("ODD");
getch();
}

Exercises:
1) Accept four numbers and display the biggest number (using
ternary operation)

18
C-LANGUAGE

SWITCH STATEMENT
Switch Statement:- switch statement is multi decision statement. It is
similar to if-else-if statement.
syntax:-
switch(expression)
{
case<constant 1>
statements;
break;
case<constant 2>
statements;
break;
case<constant 3>
statements;
break;
default:
statements;
}

switch is fallowed by an expression. Expression must enclosed in


parentheses and statements are must be enclosed in braces.
If any case statement is true then fallowing case statements are
executed. If all case statements are false then default statements are
executed. Default is optional.

Accept a character and display the fallowing names A=Amalapuram,


K=Kakinada, R=Rajahmundry.
#include<stdio.h>
main()
{
char ch;
clrscr();
printf("Enter a character");
scanf("%c",&ch);
switch(ch)
{
case 'A':
printf("AMALAPURAM");
break;
case 'K':
printf("KAKINADA");
break;
case 'R':
printf("RAJAHMUNDRY");
break;
default:

19
C-LANGUAGE

printf("INVALID CITY");
}
getch();
}

Accept a character and display the character is vowel or consonant.


#include<stdio.h>
main()
{
char ch;
clrscr();
printf("Enter a character");
scanf("%c",&ch);
switch(ch)
{
case 'a':
case 'A':
printf("VOWEL");
break;
case 'e':
case 'E':
printf("VOWEL");
break;
case 'i':
case 'I':
printf("VOWEL");
break;
case 'o':
case 'O':
printf("VOWEL");
break;
case 'u':
case 'U':
printf("VOWEL");
default:
printf("CONSONENT");
}
getch();
}

(OR)

#include<stdio.h>
main()
{
char ch;

20
C-LANGUAGE

clrscr();
printf("Enter a character");
scanf("%c",&ch);
switch(ch)
{
case 'a':
case 'A':
case 'e':
case 'E':
case 'i':
case 'I':
case 'o':
case 'O':
case 'u':
case 'U':
printf("VOWEL");
break;
default:
printf("CONSONENT");
}
getch();
}

Exercises:

1) Accept employee name, number, salary, grade display the salary


details of the employee.
Grade=’a’ Grade=’b’ Grade=’c’
Hra=15% of basic Hra=12% of basic Hra=10% of basic
Da=12% of basic Da=10% of basic Da=8% of basic
Pf=10% of basic Pf=8% of basic Pf=5% of basic

2) Accept two numbers and display the 1 for sum, 2 for subtraction, 3
for multiplication and 4 for division and 5 for exit.(using switch
statement for particular operation)

3) Accept a number and display the number is even or odd.

21
C-LANGUAGE

LOOPS
LOOPS:- loops are used to execute set of statements more then once
until to reach the given condition is true.
Basic purpose of loop is code repetition.
In implementation when the repetitions are required then recommended to
go for loops.

Types of loops:- loops are three types.


i. while loop
ii. for loop
iii. do-while loop
while loop:-
The simplest of all the looping structures in “C” is the while
statement. The basic format of the while statement is
syntax:-
while(condition)
{
statements;
}
 The while is an entry-controlled loop statement.
 When we are working with while loop pre-checking process is
occurred that is before execution of statements block condition part
is executed.
 While loop always repeats in clock direction.
 According to syntax “while” condition is true then control will pass
within the body.
 After execution of the body, once again control will pass back to the
condition and until the condition false. It repeats n no of times.
 When while condition become false, then control will pass outside
the body. If condition is not false, then it becomes an infinite loop.

Display first ten natural numbers.


#include<stdio.h>
main()
{
int i;
clrscr();
i=1;
while(i<=10)
{
printf("%d \n",i);
i=i+1;
}
getch();
}

22
C-LANGUAGE

Display first N natural numbers.


#include<stdio.h>
main()
{
int i,n;
clrscr();
i=1;
printf(“Enter N value:”);
scanf(“%d”,&n);
while(i<=n)
{
printf("%d \n",i);
i=i+1;
}
getch();
}

Display even numbers between 1 to n.


#include<stdio.h>
main()
{
int i,n;
clrscr();
printf("Enter range");
scanf("%d",&n);
i=2;
while(i<=n)
{
printf("%d \t",i);
i=i+2;
}
getch();
}

Accept a numbers and display is reverse order.


#include<stdio.h>
main()
{
int n,d,r=0;
clrscr();
printf("Enter a number");
scanf("%d",&n);
while(n>0)
{
d=n%10;
r=d+(r*10); /*printf("%d",d); */

23
C-LANGUAGE

n=n/10;
}
printf(“Reverse no=%d”,r);
getch();
}

Accept a number and display the number is Armstrong number or


not.
(Sum of cubes of each digit equal to given number
Armstrong numbers 153, 370, 371, 402)
#include<stdio.h>
main()
{
int s=0,n,d,x;
clrscr();
printf("Enter a value");
scanf("%d",&n);
x=n;
while(n>0)
{
d=n%10;
s=s+(d*d*d);
n=n/10;
}
if(x==s)
printf("%d is Armstrong number",x);
else
printf("%d is not Armstrong number",x);
getch();
}

6. Program for finding GCD of two given numbers using while


#include<stdio.h>
main()
{
int m, n, x, y, r;
printf("Enter any two numbers: ");
scanf("%d%d",&m,&n);
x = m;
y = n;
r = x % y;
while (r != 0)
{
x = y;
y = r;
r = x % y;

24
C-LANGUAGE

}
printf("GCD of %d and %d is %d",m,n,y);
}

Exercises:
1) Display “n” numbers in reverse order.
2) Accept a number and display sum of digits.
3) Accept a number and display sum of even digits and sum of odd
digits.
4) Accept a number and display the number is palindrome or not.
(Reverse number is given number)
5) Accept a number and display the number is prime number or not.
A number is divisible by one and itself.

25
C-LANGUAGE

for loop:-
syntax:-
for(initialization; condition; iteration)
{
statements;
}
 When we are working with for loop, always execution process will
start from initialization.
 Initialization part will be executed only once when we are passing
the control within the body first time.
 After execution of initialization part, control will pass to condition, if
condition evaluated is true, then control will pass to statement block.
 After execution of statement block, control will pass to iteration, from
iteration once again it will pass back to condition.
 Always repetition will come between condition, statement block and
itetation only.
 When we are working with for loop, everything is optional but
mandatory to place 2 semicolons.
while()  error
for(;;)  valid
 When the condition part is not given in for loop, then it repeats
infinite times.
 When we are working with for loop, it repeats in anti clock direction.
 The difference between while loop and for loop is in while loop
initialization declare the before beginning of the loop. Condition
declared in the loop and change of condition declared in body of the
loop.

Display first 10 numbers


#include<stdio.h>
main()
{
int i;
clrscr();
for(i=1;i<=10;i++)
{
printf(“%d\t”,i);
}
getch();
}

Display odd numbers between 1 to n.


#include<stdio.h>
main()
{

26
C-LANGUAGE

int n,i;
clrscr();
printf("Enter a range");
scanf("%d",&n);
for(i=1;i<=n;i=i+2)
printf("%d\t ",i);
getch();
}

Display sum of first 10 numbers.


#include<stdio.h>
main()
{
int i,sum=0;
clrscr();
for(i=1;i<=10;i=i++)
{
sum=sum+i;
}
printf("sum of first ten numbers %d ",sum);
getch();
}

Accept a number and display the factorial value.


#include<stdio.h>
main()
{
int i,n;
long int fact=1;
clrscr();
printf("Enter a number");
scanf("%d",&n);
for(i=1;i<=n;i++)
fact=fact*i;
printf("factorial value is %ld ",fact);
getch();
}

Display the following series.


5 10 15 20……………..50
#include<stdio.h>
main()
{
int i;
clrscr();
for(i=5;i<=50;i=i+5)

27
C-LANGUAGE

printf(“%d\t”,i);
getch();
}

Display the following series 0 1 1 2 3 5 8 13 21…..(Fibonacci Series)


#include<stdio.h>
main()
{
int n,i,n1=0,n2=1,n3;
clrscr();
printf("Enter a number");
scanf("%d",&n);
printf("%d\t%d",n1,n2);
for(i=1;i<=n-2;i++)
{
n3=n1+n2;
printf("\t%d",n3);
n1=n2;
n2=n3;
}
getch();
}

Accept 10 number and display the biggest number.


#include<stdio.h>
main()
{
int i,a,big;
clrscr();
for(i=1;i<=10;i++)
{
printf("Enter %d numbers\n",i);
scanf("%d",&a);
if(i==1)
big=a;
if(big<a)
big=a;
}
printf("Biggest number is %d",big);
getch();
}

Accept a number and display multiplication table.


#include<stdio.h>
main()
{

28
C-LANGUAGE

int i,n,s;
clrscr();
printf("Enter n value");
scanf("%d",&n);
for(i=1;i<=20;i++)
{
s=i*n;
printf("%d * %d = %d\n",i,n,s);
}
getch();
}

Nested Loops
 It is a procedure of constructing a loop within an existing loop body.
 When the repetitions are required then go for loops, if complete loop
body required to repeat n number of times then go for nested loop.
 In C programming language, we can place upto 255 nested blocks.
 When we are working with nested loops, always execution is started
from outer loop condition.
 When the outer loop condition is true, then control will pass to outer
loop body.
 In order to execute the outer loop body, if any loop occur those are
called inner loops.
 When the inner loop occurs, then check inner loop condition.
 If inner loop condition is true then control will pass within the inner
loop body and until the inner loop condition become false. When
inner loop condition is false then control will pass to outer loop and
again check the condition.

Display the following series.


1
12
123
1234
1 2 3 4 5.
#include<stdio.h>
main()
{
int i,n,s,j;
clrscr();
for(i=1;i<=5;i++)
{
printf("\n");
for(j=1;j<=i;j++)
printf("%3d",j);
}

29
C-LANGUAGE

getch();
}

Display Palindrome numbers between 1 to n


#include<stdio.h>
main()
{
int s,n,d,x,i;
clrscr();
printf("Enter a value");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
s=0;
x=i;
while(x>0)
{
d=x%10;
s=d+s(*10);
x=x/10;
}
if(s==i)
printf("%d is Palindrome number\n",i);
}
getch();
}

 In printf statement, when we are using %2d format specifier then it


indicates that 2 digit decimal values required to print, if 2 digits are
not occur then go for right alignment, that is digits will be printed
towards right side and space will be printed toward left side.
 When we are using “%-2d” format specifier then it indicates 2 digit
decimal value required to print, if 2 digits are not occur then go for
left alignment that is digit will be printed towards left side and space
will be printed towards right side.
 When we are using "%5.3d” format specifier then it indicates 5 digit
decimal value with right alignment mandatory to print 3 digits, if 3
digits are not occur then fill with zeros.
 When we are using "%-5.3d” format specifier then it indicates 5 digit
decimal value with left alignment mandatory to print 3 digits, if 3
digits are not occur then fill with zeros.

Display the following series


1

30
C-LANGUAGE

2 2
3 3 3
4 4 4 4
5 5 5 5 5
#include<stdio.h>
main()
{
int i,j,k;
clrscr();
for(i=1;i<=5;i++)
{
printf("\n");
for(k=1;k<=5-i;k++)
printf(“ “);
for(j=1;j<=i;j++)
printf("%3d",i);
}
getch();
}

To print the series(use for loop)


*
* *
* * *
* * * *
#include<stdio.h>
main()
{
int i,j,k,n;
clrscr();
printf(“Display how many lines:”);
scanf(“%d”,&n);
for(i=1;i<=n;i++)
{
printf("\n");
for(k=1;k<=n-i;k++)
printf(“ “);
for(j=1;j<=i;j++)
printf(" * “);
}
getch();
}

Pascal triangle.
1
1 1

31
C-LANGUAGE

1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
#include<stdio.h>
main()
{
int q,n,x,bin,r;
clrscr();
printf("Enter how many rows:");
scanf("%d",&n);
for(q=0;q<n;q++)
{
for(r=40-3*q;r>=0;r--)
printf(" ");
for(x=0;x<=q;x++)
{
if(x==0 || q==0)
bin=1;
else
bin=bin*(q-x+1)/x;
printf("%3d ",bin);
}
printf("\n");
}
getch();
}

Exercises:
1) Display the following series.
5 55 555 5555
2) Accept a number and display the number is prime number or not.
3) write the Fibonacci series program for end value.
1) Display the following series 1 2 2 4 8 32 …….
2) Display the following series
1 2 8 48 384 …………
3) display the following series 0 1 3 6 10 15 21 …………n, given
number .
4) Display the following series
x x2 x3 x4…….
8) Display the following series
1/x 1/x2 1/x3 1/x4 …………..
9)Accept “n” number and display the smallest number.
7) To display big , small values of “n” numbers.
8) Accept a number and display the number is perfect number or not.
Sum of factors equal to given number.

32
C-LANGUAGE

9) Display multiplication table between 1 to 20.


10) Display Armstrong number between 1 to n.
11) Display Prime numbers between 1 to n
12) Display Perfect numbers between 1 to n
16) Display the following series 1
22
333
4444
55555

17) Display the following series 5


54
543
5432
54321
18) Display the series
12345
1234
123
12
1

5 4 3 2 1
5 4 3 2
5 4 3
5 4
5

1
1 *
1 * 3
1 * 3 *
1 * 3 * 5

1
* *
1 2 3
* * * *
1 2 3 4 5

19) Display the following series.


1
1 2
12 3

33
C-LANGUAGE

1234
12345

1
0 1
1 0 1
0 1 0 1
1 0 1 0 1

1
2 3
4 5 6
7 8 9 10
11 12 13 14 15

34
C-LANGUAGE

DO WHILE LOOP
Syntax:-
do
{
statements;
}
while(condition);
 In implementation when we required to repeat the statement block
atleast once then go for while loop.
 When we are working with do-while loop, post checking process
occurs that is after execution of statement block, condition part is
executed.
 When we are working with do-while loop, it repeats in clock
direction.
 According to syntax, semicolon must be required at the end of the
body.
 It is similar to while loop. The main difference between “while” loop
and “do while” loop is in “while” loop first checks the condition then
executes the loop. In do while loop first execute the statements and
then checks the condition.
 Do while loop execute at least one time.

Display first 10 numbers.


#include<stdio.h>
main()
{
int i;
clrscr();
i=1;
do
{
printf("%d \n",i);
i=i++;
}
while(i<=10);
getch();
}

Accept two numbers and display the sum until user enter the choice
is Y.
#include<stdio.h>
main()
{
int a,b,s;
char ch;
clrscr();

35
C-LANGUAGE

do
{
printf("Enter two numbers:");
scanf("%d %d",&a,&b);
s=a+b;
printf("Sum=%d\n",s);

printf("Check another two numbers(Y/N)?");


fflush(stdin);
scanf("%c",&ch);
}
while(ch=='Y' || ch=='y');
}

Accept a number and display in reveres order until user enter the
choice is y.
#include<stdio.h>
main()
{
int a,b,s;
char ch;
clrscr();
do
{
s=0;
printf("Enter a numbers:");
scanf("%d",&a);
while(a>0)
{
b=a%10;
s=b+(s*10);
a=a/10;
}

printf(“Reverse number=%d\n”,s);
printf("Check another numbers(Y/N)?");
fflush(stdin);
scanf("%c",&ch);
}
while(ch=='Y' || ch=='y');
getch();
}

36
C-LANGUAGE

break and continue:


 break is a keyword, it is used to terminate the loop body or switch
body.
 Using break is always optional but it should be required to palce
within the loop body or switch body only.
 In implementation, where we knows the maximum number of
repetitions but depends on the condition, if we require to stop the
repetition process then go for break statement.
 continue is a keyword, by using continue we can skip the statements
from loop body.
 Using continue is always optional, but it should be required to place
within the loop body only.
 In implementation, where we know the maximum number of
repetitions but depending on the condition if we require to skip the
statements then go for continue.

Ex1: break statement.


#include<stdio.h>
main()
{
int i=1;
while(i<=10)
{
printf("%d\t", i);
if(i>3)
break;
++i;
}
}
In the above program, when if condition is true then break statement is
executing. When the break statement is executed, then control is passed
outside of the loop body.

Ex: continue statement.


#include<stdio.h>
main()
{
int i=0;
while(i<=40)
{
i=i+2;
if(i>=10 && i<=30)
continue;
printf("%d\t", i);
}
}

37
C-LANGUAGE

output: 2 4 6 8 32 34 36 38 40
When the continue statement is executing within the loop body then
control will pass back to the condition without executing remaining
statements.

GOTO STATEMENT
 goto is a keyword, by using this we can pass the control anywhere
within the program.
 goto keyword always required an identifier called label.
 Any valid identifier followed by colon is called label.
 Generally goto statement is called unstructured programming
statement because it breaks the role of structured programming
language.
 In implementation, we required to take the repetition process without
using loop then recommended to go for goto statement.

Syntax:-
<label>:
statement;
goto<label>;

Ex:
#include<stdio.h>
main()
{
printf("A");
printf("B");
goto ict;
printf("Welcome");
ict:
printf("C");
printf("D");
getch();
}

Display first ten numbers using goto statement


#include<stdio.h>
main()
{
int i;
clrscr();
i=1;
ict:
if(i<=10)
{
printf("%d\n",i);

38
C-LANGUAGE

i=i+1;
goto ict;
}
getch();
}

Exercises:

1) Display even numbers 1 to 100.

39
C-LANGUAGE

ARRAYS
 An array is a derived datatype in C which is constructed from
fundamental data type of C programming language.
 An array is a collection of similar types of data elements in a single
entity.
 In implementation when we require ‘n’ no. of values of same data
type, then recommended to create an array.
 When we are working with arrays always static memory allocation
will happen that is compile time memory management.
 When we are working with arrays always memory is constructed in
continuous memory location that’s why possible to access the data
randomly.
 When we are working with arrays all values will share same name
with unique identification value called “index”.
 Always array index must be required to start with ‘0’ and ends with
size-1.
 When we are working with arrays we required to use array subscript
operator is [ ].
 Always array subscript operator requires ‘1’ argument of type
unsigned integer constant, whose value is always ‘>0’ only.

Declaration of array :-

Syntax:-
datatype arrayname[size or subscript or boundary];
Ex:- int a[5];

Properties of Array:
Size no. of elements, sizeof  no.of bytes.
1. int a[5];
Size  5
sizeof(a)  10 bytes

2. int a[5];
int a[0]
int a[1]
int a[2]
int a[3]
int a[4]

a [0] a[1] a[2] a[3] a[4]


3. int a[ ]; error

4. int a[0]; error

5. int a[-5]; error

40
C-LANGUAGE

 In declaration of array size must be require to specify or else it gives


an error: Size of a is unknown.
 In declaration of array size must be unsigned integer constant,
whose value is ‘>0’ only. (Array must have at least one element)

6. int a[5]={20,10,43,45,59}; (a[0]=20,a[1]=10,a[2]=43,a[3]=45,a[4]=59)

7. int a[5]={20,10,43}; (a[0]=20,a[1]=10,a[2]=43,a[3]=0,a[4]=0)


In initialization of array, if specified no.of elements are not initialized, the
remaining all elements are automatically initialized with zero.

8. int a[2]={20,10,43,15,65}; error


In initialization of array we can’t initialize more than size of array
elements, if we are initializing then it gives an error is array initializations.

9. int a[ ]={10,20,14,34,22}; valid


In initialization of array specifying the size is optional, in this case how
many elements are initialized that size will be created automatically.

10. On DOS based compiler at compile time we can create maximum of


64KB of data that is 65536bytes.
Ex:
int a[4000];  valid
long int b[20000];  error

11. int size=10;


int a[size];  error

12. #define size 10


int a[size];

Types of arrays:-
There are three types of arrays available in “c” language.

Single dimensional array:- Variable can have only one subscript is called
single dimensional arrays.
Ex:- int a[5]

a [0] a[1] a[2] a[3] a[4]


int a[5]={2,3,5,6,4};

Double dimensional Array:-


 In 2D array, elements are arranged in rows, columns format.

41
C-LANGUAGE

 When we are working with 2D array, we required to use 2 subscript


operators which indicates row size and column size.

Ex:- int a[2][2];


Int a[2][2]={[2,2],[2,4]};
Properties :
1. int arr[3][4];
Size  3*4
sizeof(arr)  24 bytes

2. int arr[ ][ ];  Error

3. int arr[3][ ];  Error

4. int arr[ ][3];  Error

5. int arr[2][3]={10,20,30,40,50,60};
10arr[0][0] 20arr[0][1] 30arr[0][2]
40arr[1][0] 50arr[1][1] 60arr[1][2]
 By using above initialization process, we required to initialize all
elements in sequence only that is selected no. of elements cannot
be initialized.

6. int arr[3][3]={
{10},
{20,30},
{40,50,60}
};
arr[0][0]=10 arr[0][1]=0 arr[0][2]=0
arr[1][0]=20 arr[1][1]=30 arr[1][2]=0
arr[2][0]=40 arr[2][1]=50 arr[2][2]=60
 In initialization of 2D array, it specific no. of elements are not
initialized then remaining all elements are initialized with zero.

THREE DIMENSIONAL ARRAYS:-


 In 3D array elements are arranged in blocks, rows and columns
format.
 When we are working with 3D array we required to three subscript
operator which indicates block size, row size and columns sizes.
 The main memory of 3D array is blocks, sub main memory is rows
and elements are available in columns.
Ex:
int a[2][3][4];

42
C-LANGUAGE

Accept 5 numbers and display these numbers.


#include<stdio.h>
main()
{
int i,a[5];
clrscr();
printf("Enter 5 Values:");
for(i=0;i<5;i++)
scanf("%d",&a[i]);
printf("The values are:\n");
for(i=0;i<5;i++)
printf("%d\t",a[i]);
getch();
}

Accept n elements into an array and accept search number than


display the search number found or not and display the position of
the search number.
#include<stdio.h>
main()
{
int i,a[50],n,sno;
clrscr();
printf("Enter how many elements:");
scanf("%d",&n);
printf("Enter %d Values:",n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("Enter Search number:");
scanf("%d",&sno);
for(i=0;i<n;i++)
{
if(sno==a[i])
{
printf("Search number is found\n");
printf("Position is %d",i+1);
break;
}
}
if(i==n)
printf("Search number is not found");
getch();
}
Accept n elements and display in ascending order. (bubble sorting)
#include<stdio.h>

43
C-LANGUAGE

main()
{
int i,j,a[50],n,temp;
clrscr();
printf("Enter how many elements:");
scanf("%d",&n);
printf("Enter %d Values:",n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
printf("The elements in ascending order is:\n");
for(i=0;i<n;i++)
printf("%d\t",a[i]);
getch();
}

Exercises:
1) Enter 5 elements into an array and display in reverse order.
2) Accept n elements into an array and display that elements.
3) Accept n elements into an array and display in reverse order
4) Accept n elements into an array and display sum of elements and
average of elements.
5) Accept “n” elements into an array and display big and smallest
numbers of the array.
6) Accept n elements and display descending order.
7) Accept n numbers of students to display the student details.

DOUBLE DIMENSIONAL ARRAYS


1) Display 2*2 matrix.
#include<stdio.h>
main()
{
int a[2][2],i,j;
clrscr();
printf("Enter 4 elements:");

44
C-LANGUAGE

for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
scanf("%d",&a[i][j]);
}
printf("\nMatrix is:\n");
for(i=0;i<2;i++)
{
printf("\n");
for(j=0;j<2;j++)
printf("%d\t",a[i][j]);
}
getch();
}

Shortcut keys:-
Ctrl+kb  beginning of the block.
Ctrl+kk  end of the block.
Ctrl+kc copy of the block.
Ctrl+kv move the block.
Ctrl+kh hide the block.
Ctrl+y  delete the entire line.

Accept m*n matrix and display transpose of the given matrix.


#include<stdio.h>
main()
{
int a[20][20],i,j,m,n;
clrscr();
printf("Enter how many Rows &columns:");
scanf("%d %d",&m,&n);
printf("Enter %d elements:",m*n);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
}
printf("\nMatrix is:\n");
for(i=0;i<m;i++)
{
printf("\n");
for(j=0;j<n;j++)
printf("%d\t",a[i][j]);
}
printf("\nTranspose Matrix is:\n");
for(i=0;i<n;i++)

45
C-LANGUAGE

{
printf("\n");
for(j=0;j<m;j++)
printf("%d\t",a[j][i]);
}
getch();
}

Accept m*n matrix and display the sum of elements.


#include<stdio.h>
main()
{
int a[20][20],i,j,m,n,sum=0;
clrscr();
printf("Enter how many Rows &columns:");
scanf("%d %d",&m,&n);
printf("Enter %d elements for matrix A:",m*n);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
}
printf("\nMatrix A is:\n");
for(i=0;i<m;i++)
{
printf("\n");
for(j=0;j<n;j++)
{
sum=sum+a[i][j];
printf("%d\t",a[i][j]);
}
}
printf("\nSum of Elements=%d",sum);
getch();
}

Accept 2*2 matrix and display inverse of the given matrix.


#include<stdio.h>
main()
{
int a[2][2],i,j;
float det,b[2][2];
clrscr();
printf("Enter 4 elements:");
for(i=0;i<2;i++)
{

46
C-LANGUAGE

for(j=0;j<2;j++)
scanf("%d",&a[i][j]);
}
printf("\nMatrix is:\n");
for(i=0;i<2;i++)
{
printf("\n");
for(j=0;j<2;j++)
printf("%d\t",a[i][j]);
}
det=a[0][0]*a[1][1]-a[0][1]*a[1][0];
if(det==0)
printf("INVERSE IS NOT POSSIBLE");
else
{
det=1/det;
b[0][0]=a[1][1];
b[1][1]=a[0][0];
b[0][1]=-a[0][1];
b[1][0]=-a[1][0];
printf("\nThe inverse of matrix is:\n");
for(i=0;i<2;i++)
{
printf("\n");
for(j=0;j<2;j++)
printf("%.2f\t",det*b[i][j]);
}
}
getch();
}

Accept two m*n matrix and display the sum of matrix.


#include<stdio.h>
main()
{
int a[20][20],b[20][20],c[20][20],i,j,m,n;
clrscr();
printf("Enter how many Rows &columns:");
scanf("%d %d",&m,&n);
printf("Enter %d elements for matrix A:",m*n);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
}
printf("Enter %d elements for matrix B:",m*n);

47
C-LANGUAGE

for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
scanf("%d",&b[i][j]);
}
printf("\nMatrix A is:\n");
for(i=0;i<m;i++)
{
printf("\n");
for(j=0;j<n;j++)
printf("%d\t",a[i][j]);
}
printf("\nMatrix B is:\n");
for(i=0;i<m;i++)
{
printf("\n");
for(j=0;j<n;j++)
printf("%d\t",b[i][j]);
}
printf("\nResult Matrix is:\n");
for(i=0;i<m;i++)
{
printf("\n");
for(j=0;j<n;j++)
{
c[i][j]=a[i][j]+b[i][j];
printf("%d\t",c[i][j]);
}
}
getch();
}

To calculate the multiplication of two matrix.


#include<stdio.h>
main()
{
int a[20][20],b[20][20],c[20][20],i,j,m1,n1,m2,n2;
clrscr();
printf("Enter how many Rows &columns matrix A:");
scanf("%d %d",&m1,&n1);
printf("Enter how many Rows &columns matrix B:");
scanf("%d %d",&m2,&n2);
if(n1!=m2)
printf("MATRIX MULTIPLICATION IS NOT POSSIBLE");
else
{

48
C-LANGUAGE

printf("Enter %d elements for matrix A:",m1*n1);


for(i=0;i<m1;i++)
{
for(j=0;j<n1;j++)
scanf("%d",&a[i][j]);
}
printf("Enter %d elements for matrix B:",m2*n2);
for(i=0;i<m2;i++)
{
for(j=0;j<n2;j++)
scanf("%d",&b[i][j]);
}
printf("\nMatrix A is:\n");
for(i=0;i<m1;i++)
{
printf("\n");
for(j=0;j<n1;j++)
printf("%d\t",a[i][j]);
}
printf("\nMatrix B is:\n");
for(i=0;i<m2;i++)
{
printf("\n");
for(j=0;j<n2;j++)
printf("%d\t",b[i][j]);
}
for(i=0;i<m1;i++)
{
for(j=0;j<n2;j++)
{
c[i][j]=0;
for(k=0;k<n1;k++)
c[i][j]=c[i][j]+a[i][k]*b[k][j];
}
}
printf("\nResult Matrix is:\n");
for(i=0;i<m1;i++)
{
printf("\n");
for(j=0;j<n2;j++)
printf("%d\t",c[i][j]);
}
}
getch();
}

49
C-LANGUAGE

Exercises:
1) Display m*n matrix.
2) Accept m*n matrix and display the sum of diagonal elements.
3) Accept two m*n matrix and display the subtraction of matrix.

50
C-LANGUAGE

STRINGS
 Character array or group of characters or collection of characters
are called strings.
 In implementation when we are manipulating multiple characters
then recommended to go for strings.
 Within the ' ' any constant is called character constant, within the " "
any content is called string constant.
 Character constant always returns an integer value that is ASCII
value of a character.
 String constant always returns base address of a string.

Syntax:-
char variable [size];
Ex:- char name[25];

The compiler assigns string to a character array it automatically


supplies a null character “\0”(zero) at end of the string. That’s why the size
should be equal to maximum number of characters in the string.

Eg:- char s[9] = “NEW YEAR”;


Char s[9] = {‘N’,’E’,’W’,’ ‘,’Y’,’E’,’A’,’R’};
Char s[] = “Amalapuram”;

Reading Strings:-
The “scanf ” function can be used with “%s” format specification to
read the string.
Ex:- scanf(“%s”,&name);
The problem with scanf function is that it terminates we can
enter the space.

gets:-It is used to accept string from the keyboard until we can press
enter.
gets(name);

String Functions:-
(1) Strlen: -This function is used to count the number of character in a
string.
Syntax: - n=strlen(string)

Accept a string and display the length of the string using string
function.
#include<stdio.h>
#include<string.h>
main()
{
char str[50];

51
C-LANGUAGE

int l;
clrscr();
printf("Enter a string:");
gets(str);
l=strlen(str);
printf("String length=%d",l);
getch();
}

Accept a string and display the length of the string without using
string function.
#include<stdio.h>
main()
{
char str[50];
int l=0,i;
clrscr();
printf("Enter a string:");
gets(str);
for(i=0;str[i]!='\0';i++)
l++;
printf("String length=%d",l);
getch();
}

Strcpy:-This function copy the contents of one strings to another .The


address of the source and target strings should by supply in this function.
Syntax:- strcpy (string1,string2);

Copy the string using string function.


#include<stdio.h>
#include<string.h>
main()
{
char s1[50],s2[50];
clrscr();
printf("Enter a string:");
gets(s1);
strcpy(s1,s2);
printf("String 1=%s\n",s1);
printf("String 2=%s\n",s1);
getch();
}

String copying without using string function.


#include<stdio.h>

52
C-LANGUAGE

main()
{
char s1[50],s2[50];
int i;
clrscr();
printf("Enter a string:");
gets(s1);
for(i=0;s1[i]!='\0';i++)
s2[i]=s1[i];
s2[i]='\0';
printf("String 1=%s\n",s1);
printf("String 2=%s",s2);
getch();
}

Strcat :- This function is to combine the two strings. This process is called
as concatenation.
Syntax:- strcat(string1,string2);

Combine the two Strings using string function.


#include<stdio.h>
#include<string.h>
main()
{
char s1[50],s2[50];
clrscr();
printf("Enter first string:");
gets(s1);
printf("Enter Second string:");
gets(s2);
strcat(s1,s2);
printf("Result String =%s\n",s1);
getch();
}

Combine the two Strings without using string function.


#include<stdio.h>
main()
{
char s1[50],s2[50],s3[80];
int i,j;
clrscr();
printf("Enter first string:");
gets(s1);
printf("Enter Second string:");
gets(s2);

53
C-LANGUAGE

for(i=0;s1[i]!='\0';i++)
s3[i]=s1[i];
s3[i]=' ';
for(j=0;s2[j]!='\0';j++)
s3[i+j+1]=s2[j];
s3[i+j+1]='\0';
printf("Result String =%s\n",s3);
getch();
}

Strcmp:-This function is used to compare the two strings are equal or not.
If two strings are equal then this function returns the value is zero.
If two strings are not equal, it returns numeric difference between
the ASCII values of non-matching characters.
Syntax:- i=strcmp(string1, string2);

Compare the two strings using string function.


#include<stdio.h>
#include<string.h>
main()
{
char s1[50],s2[50];
int i;
clrscr();
printf("Enter first string:");
gets(s1);
printf("Enter Second string:");
gets(s2);
i=strcmp(s1,s2);
if(i==0)
printf("STRINGS ARE EQUAL");
else
printf("STRINGS ARE NOT EQUAL");
getch();
}

Strings comparison without using function


#include<stdio.h>
#include<string.h>
main()
{
char s1[50],s2[50];
int i,j=0;
clrscr();
printf("Enter first string:");
gets(s1);

54
C-LANGUAGE

printf("Enter Second string:");


gets(s2);
if(strlen(s1)==strlen(s2))
{
for(i=0;s1[i]!='\0';i++)
{
if(s1[i]==s2[i])
j++;
else
break;
}
}
if(j==strlen(s1))
printf("STRINGS ARE EQUAL");
else
printf("STRINGS ARE NOT EQUAL");
getch();
}

Strrev: This function is used to reverse the given string.


Syntax: strrev(string);

Reverse the given string using string function.


#include<stdio.h>
#include<string.h>
main()
{
char s1[50];
clrscr();
printf("Enter a string:");
gets(s1);
strrev(s1);
printf("Reverse String =%s\n",s1);
getch();
}

Reverse the given string without using string function.


#include<stdio.h>
#include<string.h>
main()
{
char s1[50],s2[50];
int i,l,j=0;
clrscr();
printf("Enter a string:");
gets(s1);

55
C-LANGUAGE

l=strlen(s1);
for(i=l-1;i>=0;i--)
{
s2[j]=s1[i];
j++;
}
s2[j]='\0';
printf("Reverse String =%s\n",s2);
getch();
}

Exercises:
1)Accept a name and display number of vowels and consonants in that
strings
2) Accept a string and display the string is palindrome or not
3) Accept a string and count the number of words in that string
4) Accept n strings and display in ascending order.

56
C-LANGUAGE

FUNCTIONS
Self contained block of one or more statements which is designed for a
particular task is known as function.
Advantages: -
1. Module approach: - By using functions we can develop the application
in module format that is procedure oriented language concept.
2. Reusability: - By using functions we can create reusability blocks that
is develop once and use multiple times.
3. Easy to Debug: - By using functions, we can easily debug the program.
4. Code maintenance: - When we are developing the application by using
functions, then it is easy to maintain code for future enhancements.

Syntax of Function:-
returntype functionname (arguments list)
{
declaration of local variables;
Statements;
return statement;
}
According to syntax, specifying the return type, parameters and return
statements are optional.
All the rules of variable declarations are applicable to function name also

C Function can be classified into two types .


(1)Library functions/ Built-in functions/ Pre-defined functions.
Eg:-sqrt().,strlen ,printf ,scanf,etc…
(2)User defined functions.
Eg:-main().
Library Functions: -
 Library functions are set of pre implemented functions which are
available along with compiler.
 The implementation part of library functions are available in .lib or
.obj files which is available in lib directory (folder).
 .lib or .obj files contains pre-compiled object code.
 When we are working with pre-defined functions for avoiding the
compilation error we required to go for forward declaration that is
prototype is required.
 When we are required to provide of prototype of pre-defined
functions, then required to go for header files.
 .h file does not provide any implementation part of pre defined
functions, it provides only prototype that is forward declaration of
function.
Limitations:
 All pre-defined functions contain limited task only that is for what
purpose function is developed, for same purpose we required to
use.

57
C-LANGUAGE

 As a programmer, we doesn’t having control on predefined


functions.
 As a programmer, it is not possible to alter or modify the behavior of
any pre-defined functions.
 When pre-defined functions are not supporting user requirement
then go for user defined functions.
User defined functions: -
 As per client or project requirements, the functions we are
developing are called user-defined functions.
 Always user defined functions are client specific functions or project
specific functions only.
 As a programmer, we are having full control on user defined
functions.
 As a programmer, it is possible to alter or modify the behavior of any
user defined function if it is required because coding part is available
 These depends on return type and parameter type.
 User defined functions are classified into four types:
o No return type with no parameters.
o No return type with parameter.
o With return type without parameters.
o With return type with parameter.
Note: All pre-defined functions are user defined functions only because
somewhere else another programmer developed these functions and we
are using in the form of obect code or compile code.

About main(): -
 main is an identifier in the program which indicates startup point of
an application.
 main is a user defined functions with pre-defined signature for
Linker.
 A Linker is a assembly language program which always decides
startup point of the program is main.
 It is possible to develop a program without using main function also.
In this case compilation is success but linking is failure.
 Multiple main functions are not possible.
 When we are developing .lib/.obj files for other projects then doesn’t
required to include main function.
 A C program is a combination of pre-defined and user defined
functions, compilation process starts from top to bottom and
execution process starts on main() and ends with main() only.

Rules of functions :-
C program is a collection of one or more functions .
A function “gets” called when the function name is followed by “;”.
Ex:- c=sum(a,b);

58
C-LANGUAGE

A function is defined when function name is followed by a pair of braces


with one more statements.
Any function can be called number of times.
Ex:-
#include<stdio.h>
main()
{
clrscr();
message();
message();
message();
getch();
}

message()
{
printf(“Data Info tech computers\n”);
}

The order in which the function are defined in a program and the order
in which they get called need not necessary to be same.
Ex:-
#include<stdio.h>
main()
{
clrscr();
printline();
message();
printline();
getch();
}
message()
{
printf(“Data Info tech computers\n”);
}
printline()
{
printf(“--------------------------------------\n”);
}

From any function we can call any other function.


Ex:
#include<stdio.h>
main()
{
clrscr();

59
C-LANGUAGE

show();
getch();
}
message()
{
printf(“Data Info tech computers\n”);
}
show()
{
printf("Hello");
message();
}

After execution of any function, automatically control roll pass back to


the calling place that is from which location we called the function to same
location it will pass.

Accept two numbers and display the sum using function.


#include<stdio.h>
main()
{
int a,b,s;
clrscr();
printf("Enter two numbers:");
scanf("%d %d",&a,&b);
s=sum(a,b);
printf("Sum=%d",s);
getch();
}
sum(int x,int y)
{
int t;
t=x+y;
return(t);
}

Formal arguments and Actual arguments:


 In function declarator, what variables we are creating those are
called formal arguments or parameters.
 In function calling statement what data we are passing those are
called actual arguments.

Function categories:-
These are three types.
1) Function with no of arguments and no return values.
2) Function with arguments but no return values.

60
C-LANGUAGE

3) Function with arguments and return values.


1)No arguments and no return values:-when a function has no
arguments it does not receive any data from calling function. Similarly it
does not return value.

Calculate the area of the rectangle


#include<stdio.h>
main()
{
clrscr();
area();
getch();
}
area()
{
int l,b,a;
printf("Enter length and breadth:");
scanf("%d %d",&l,&b);
a=l*b;
printf("Rectangle Area =%d",a);
}

Passing arguments but no return values:-


The nature of data communication between the calling function and the
called function with arguments but no return values.

Area of rectangle
#include<stdio.h>
main()
{
int l,b;
clrscr();
printf("Enter length and breadth:");
scanf("%d %d",&l,&b);
area(l,b);
getch();
}
area(int l,int b)
{
int a;
a=l*b;
printf("Rectangle Area =%d",a);
}

Passing arguments with return values:-The function receive data from


the calling function through arguments and return values. In this type of

61
C-LANGUAGE

program, two way data communication between the calling and called and
functions.

Area of rectangle
#include<stdio.h>
main()
{
int l,b,a;
clrscr();
printf("Enter length and breadth:");
scanf("%d %d",&l,&b);
a=area(l,b);
printf("Rectangle Area =%d",a);
getch();
}
area(int l,int b)
{
int t;
t=l*b;
return(t);
}
Exercises:
1) Accept three numbers and display the biggest number.
a) Using no arguments and no return values.
b) Passing arguments but no return values.
c) Passing arguments and return values.
2) Accept a number and display in reverse order.
a) Passing no arguments and no return values.
b) Passing arguments but no return values.
c) Passing arguments and return values.

HANDLING OF NON-INTEGER FUNCTIONS:- We mentioned earlier that


a “C” function returns a value of the type int as the default case when no
other type is specified explicitly. The function value of all calculations using
floats but the return statement
return(sum);
returns only the integer part of sum. This is due to the absence of the type-
specified in the function header. In this case, we can accept the integer
value of sum because the truncated decimal part is insignificant compared
to the integer part. However, there will be times then we may find it
necessary to receive the float or double type of data. For example, a
function value in either float or double.
We must do two things to enable a calling function to receive a non-
integer value from a called function:

62
C-LANGUAGE

1) The explicit type-specifies, corresponding to the data type required


must be mentioned in the function header. The general from of the
function definition is
type-specifier function-name(argument list)
{
function statements;
}
The type-specifier tells the compiler, the type of data the function is
to return.
2) The called function must be declared at the start of the body in the
calling function, like any other variable. This is to tell the calling
function the type of data that the function is actually returning.

Accept three numbers and display the average.


#include<stdio.h>
main()
{
float a,b,c,s;
float avg(float,float,float);
clrscr();
printf(“Enter three numbers:”);
scanf(“%f %f %f”,&a,&b,&c);
s=avg(a,b,c);
printf(“Average=%f”,s);
getch();
}
float avg(float x,float y,float z)
{
flaot d;
d=(a+b+c)/3;
return(d);
}

63
C-LANGUAGE

RECURSION:-
Recursion is a process by which a function calls itself repeatedly
until specified condition has been satisfied.
Many iterative (loops) programs can be written in this form.

Advantages:
 By using recursion process only, function calling information will be
maintained in program.
 By using recursion process stack evalution takes place.
 With the help of recursion only – infix, postfix, prefix notations are
evaluated.
 By using recursion process only trees and graphs are implemented.
Drawbacks:
 It is a very slow process due to stack overlapping.
 Recursion based programs can create stack overflow.
 Recursion based functions can create infinity loop.

Calculate the factorial of a given numbers(using recursion).


#include<stdio.h>
main()
{
int n,s;
clrscr();
printf("Enter a number:");
scanf("%d",&n);
s=fact(n);
printf("Factorial value=%d",s);
getch();
}
fact(int x)
{
if(x==1)
return(1);
else
return(x*fact(x-1));
}

Accept a number and display sum of the digits of given number


#include<stdio.h>
main()
{
int n,s;
clrscr();
printf("Enter a number:");
scanf("%d",&n);
s=sum(n);

64
C-LANGUAGE

printf("Sum of digits=%d",s);
getch();
}
sum(int x)
{
if(x==0)
return(0);
else
return((x%10)+sum(x/10));
}

Functions With Arrays:- Like the value of simple variables, it is also


possible to pass the values of an array to a function. To pass an array to a
called function, it is sufficient to list the name of the array, without any
subscripts, and the size of the array as arguments.. for example, the call
largest(a,n);
will pass all the elements contents in the array a of size in n. The called
function expecting this call must be appropriately defined. The function
largest is defined to take two arguments, the array name and the size of
the array to specify the number of elements in the array.
Syntax:- int big (a,n)
int a[];
int n;
{
statements;
}

Accept n numbers into an array and display that numbers.


#include<stdio.h>
main()
{
int a[50],n;
clrscr();
printf("Enter how many elements:");
scanf("%d",&n);
printf("Enter %d Values:",n);
accept(a,n);
printf("The elements are:\n");
display(a,n);
getch();
}
accept(int a[],int n)
{
int i;
for(i=0;i<n;i++)
scanf("%d",&a[i]);

65
C-LANGUAGE

}
display(int a[],int n)
{
int i;
for(i=0;i<n;i++)
printf("%d\t",a[i]);
}
Exercises:
1) Accept “n” numbers into an array and display the biggest number.
2) Accept n numbers and display in ascending order.

Functions using in Double dimensional arrays:


1) Display m*n Matrix
#include<stdio.h>
main()
{
int a[20][20],m,n;
clrscr();
printf("Enter how many Rows &columns:");
scanf("%d %d",&m,&n);
printf("Enter %d elements:",m*n);
accept(a,m,n);
printf("\nMatrix is:\n");
display(a,m,n);
getch();
}
accept(int a[][20],int m,int n)
{
int i,j;
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
}
}
display(int a[][20],int m,int n)
{
int i,j;
for(i=0;i<m;i++)
{
printf("\n");
for(j=0;j<n;j++)
printf("%d\t",a[i][j]);
}
}

66
C-LANGUAGE

Exercises:
1) Display sum of two matrix
2) Matrix multiplication

67
C-LANGUAGE

STORAGE CLASSES
Variable in “c” different behaviour from most of the other languages.
In “C” there are different ways to characterize variables by data type and
storage class.
Storage class of C will provide following information to the compiler:
1. Storage area of variable.
2. Scope of a variable that is in which block that variable is visible.
3. Life time of a variable that is how long that variable will be there in
active mode.
4. Default value of a variable if it is not initialized.

There are four different storage classes in “C”.


i) Automatic Variables.
ii) External Variables.
iii) Static Variables.
iv) Register Variables.

Automatic Variables:- Automatic variables are defined inside a function


in which they are utilized. They are created when the function is called and
destroyed automatically when the function is exited. Automatic variables
are also reffered to as local or internal variables. The important feature of
automatic variable is that their value can not be changed.
A variable declared inside a function without storage class specification is,
by default, an automatic variable. Automatic variables are stored in stack
memory.

Syntax:-auto datatype variable;


Ex:-auto int a;

Using automatic variables.


#include<stdio.h>
main()
{
auto int a=1;
{
auto int a=2;
{
auto int a=3;
printf(“%d\t”,a);
}
printf(“%d\t”,a);
}
printf(“%d\t”,a);
}

output:- 3 2 1

68
C-LANGUAGE

External variables:- External variables are both alive and active though
out the entire program. These are also known as global variable. External
variables are declared outside a function.External variables are stored in
memory.External variables default value is zero(“0”).
Syntax:- extern datatype variable;
extern int a;

Using external variables.


#include<stdio.h>
extern int a;
main()
{
printf(“%d\t”,a);
increment();
increment();
getch();
}
increment()
{
a++;
printf(“%d\t”,a);
}

output: 0 1 2

Static variables:- The value of static variables persists until the end of
the programm. A static variables may be either internal or external
depending on the place of declaration. The default value of static variables
is zero. Static variables are stored in static memory.
Internal static variables are those, which are declared inside a
function. The scope of internal static variable extend up to the end of the
function in which they are defined. Therefore, internal static variables are
similar to auto variables, except that they remain in existence(alive)
throughout the remainder of the program.
An external static variable is declared outside of all functions and is
available to all the functions in that program. The difference between a
static external variable and simple external variable is that the static
variable is available only with in the file where it is defined while the simple
external variable can be accessed by other files.

Syntax:-static datatype variable;


static int i;

Using static variable.


#include<stdio.h>

69
C-LANGUAGE

main()
{
increment();
increment();
increment();
getch();
}

increment() increment()
{ {
static int a=1; auto int a=1;
printf(“%d\t”,a); printf(“%d\t”,a);
a++; a++;
} }
output: 1 2 3 output: 1 1 1

Register Variables:-
 It is a special kind of variables which stores in CPU registers.
 The basic advantage of register variable is it is faster than normal
variables.
 In implementation, when we are accessing a variable throught the
program n number of times then go for register variable.
Limitations:
 Register memory is limited so it is not possible to create n number of
register variables.
 On register variables we can’t apply pointers because register
variables doesn’t allow to access address.

Syntax:-register datatype variable;


register int i;

Using register variables.


#include<stdio.h>
main()
{
register int I;
clrscr();
for(I=1;I<=100;I++)
{
printf(“%d\t”,I);
}
getch();
}

70
C-LANGUAGE

POINTERS
Find the address of the variable
#include<stdio.h>
main()
{
int a;
clrscr();
printf("Enter a number \t");
scanf("%d",&a);
printf("\nValue of a =%d",a);
printf("\nAddress of a =%u",&a);
printf("\nValue of a =%d",*(&a));
getch();
}

The “&” is the address operator in “C”. the other pointer operator available
in “C” in *. It is called value at address operator as indirection operator.

Pointers are another important feature of C language.


Definition: A pointer is a memory variable which is used to store address
of the another variable.
Syntax:- datatype *variablename;
Ex: int *p;
According to syntax, indirection operator must be required between data
type and pointer name.
Space is not mandatory to place in declaration of pointer variable.

Advantages of pointer:
1. Data Access: - C programming language is a procedure oriented
language that is applications are developed by using functions.
From one function to another function, when we are required to access the
data, pointer is required.
2. Memory Management: - By using pointers only, dynamic memory
allocation is possible.
3. Database/Datastrucrtures: - Any kind of data structures required to
develop by using pointers only, if data structures are not available then
database is not possible to create.
4. Performance: - By using pointers, we can increase the execution of
the program.

Using pointer variable


#include<stdio.h>
main()
{
int a,b,*p,*q;
clrscr();

71
C-LANGUAGE

a=10;
b=20;
p=&a;
q=&b;
printf("Value of a=%d\n",a);
printf("Address of a=%u\n",&a);
printf("Value of a = %u\n",*p);
printf("Address of p=%u\n",p);
printf("Value of b=%d\n",b);
printf("\Address of b= %u\n",&b);
printf("Value of b = %u\n",*q);
printf("Address of q = %u",q);
getch();
}

Pointer rules:
Rule1:
Address+number=address(next specified address)
Address-number=address( Previous address)
Address++=next address
Address- -=previous address
++Address=next address
--Address=previous address
Ex:
int i1,i2;
int *p1,*p2;
p1=&i1;
p2=&i2;
p1+p2;  Error
p1+1;  Next address
++p1;  Next address
p1++;  next address
p2-1;  Previous address
p2--;  Previous address
--p2;  Previous address

Rule2:
Address-address=number of elements/size difference
int *p1=(int*)100;
int *p2=(int*)200;
p2-p1=50
Rule3:
Address+address= illegal p1+p2
Address+address= illegal p1*p2
Address+address= illegal p1/p2
Address+address= illegal p1%p2

72
C-LANGUAGE

Rule 4:
We can use relational operators and and conditional operators between
two pointers. (<, >, <=, >=, ==, !=, ? :)
Address>address p1>p2 True/false

Pointer to pointer:
 It is a procedure of holding the pointer address into another pointer
variable.
 In a C programming language, pointer to pointer relations can be
applied upto 12 stages.
 When we are increment pointer pointer relations then performance
will be decreased.
Ex:
Int i;
int *ptr;
int **pptr;
int ***ppptr;
ptr=&i;
pptr=&ptr;
ppptr=&pptr;

Store the address of the pointers variable in the another pointer


variable.
#include<stdio.h>
main()
{
int a,*p,**q;
clrscr();
a=10;
p=&a;
q=&p;
printf("Value of a=%d\n",a);
printf("Address of a=%u\n",&a);
printf("Value of a= %u\n",*p);
printf("Address of p=%u\n",&p);
printf("Value of a=%d\n",**q);
printf("\Address of q= %u\n",&q);
printf("Value of q = %u",q);
getch();
}

void pointer:
 Generic pointer of ‘C’ and ‘C++’ is called void pointer.
 Generic pointer means it can access and manipulate any kind of
data properly.
 Size of void pointer is 2 bytes.

73
C-LANGUAGE

 By using void pointer, when we are accessing the data, we required


to use type casting.
 When we are working with void pointer, Type specification will be
decided at runtime only.
 When we are working with void pointer, arithmetic operations are
not allowed, that is incrementation and decrementation of pointer is
restricted.

Ex:
#include<stdio.h>
main()
{
int i;
float f;
char ch;
int *iptr;
float *fptr;
char *cptr;
clrscr();
iptr=&i;
i=10;
printf("%d %d\n",i,*iptr);
fptr=&f;
f=12.6;
printf("%f %f\n",i,*fptr);
cptr=&ch;
ch='A';
printf("%c %c\n",ch,*cptr);
getch();
}
 In the above program, in place of constructing 3 types of pointers, we
can create a single pointer variable which can access and manipulate any
kind of variable properly that is void pointer required to use.
Ex:
#include<stdio.h>
main()
{
int i;
float f;
char ch;
void *ptr;
clrscr();
ptr=&i;
i=10;
printf("%d %d\n",i,*(int*)ptr);
ptr=&f;

74
C-LANGUAGE

f=12.6;
printf("%f %f\n",i,*(float*)fptr);
ptr=&ch;
ch='A';
printf("%c %c\n",ch,*(char*)cptr);
getch();
}

Accept two numbers and display the sum using pointer.


#include<stdio.h>
main()
{
int a,b,*p,*q,sum;
clrscr();
p=&a;
q=&b;
printf("Enter two numbers");
scanf("%d%d",p,q);
sum=*p+*q;
printf("Sum = %d",sum);
getch();
}

Display 10 numbers using pointers.


#include<stdio.h>
main()
{
int a,*p;
clrscr();
for(a=0;a<=10;a++)
{
*p=a;
printf(" %d",*p);
}
getch();
}

Exercises:
1) Accept three numbers and display the biggest number using
pointers.
2) Accept a number and display in reverse order.

Pointers With Function :-


Parameter passing techniques:
In C language we have two types of parameter passing techniques:
1) Call by value.

75
C-LANGUAGE

2) Call by address.

Call By Value:-
 When we are calling a function by passing a value type data then it
is called call by value.
 In call by value, both actual arguments and formal arguments are
value type variables only.
 In call by value, if any modifications are occur on formal arguments
then those modifications doesn’t pass to actual arguments.
Ex: printf(), sqrt()…
Call By Address:-
 When we are passing address type data to a function then it is
called call by address.
 In call by address, actual arguments are address type and formal
arguments are pointer type.
 In call by address, if any modifications occurred on formal
arguments then those changes will pass to actual arguments.
Ex: scanf(), strcpy()….

Accept two numbers and swap them (using call by value method).
#include<stdio.h>
main()
{
int a,b;
clrscr();
printf("Enter TWO numbers\n");
scanf("%d%d",&a,&b);
printf("Before Swapping\n");
printf("a=%d \t b=%d",a,b);
swap(a,b);
getch();
}
swap(int x,int y)
{
int temp;
temp=x;
x=y;
y=temp;
printf("\nAfter Swapping\n");
printf("\na=%d \t b=%d",x,y);
}

2) Write the above program using call by reference method.


#include<stdio.h>
main()
{

76
C-LANGUAGE

int a,b;
clrscr();
printf("Enter TWO numbers\n");
scanf("%d%d",&a,&b);
printf("Before Swapping\n");
printf("a=%d \t b=%d",a,b);
swap(&a,&b);
printf("\nAfter Swapping\n");
printf("\na=%d \t b=%d",*x,*y);
getch();
}

swap(int *x,int *y)


{
int temp;
temp=*x;
*x=*y;
*y=temp;
}

Exercises:
1) Accept two numbers and display the sum.
2) Accept three numbers and display the biggest number.
3) Accept a number and display in reverse order.

77
C-LANGUAGE

Pointers With Arrays:- When an array is declared, the compiler a base


address and sufficient amount of storage to contain all the elements of the
array in contiguous memory’ locations. The base address is the location of
the first element (index o)of the array.The compiler also defines the array
name as a constant pointer to the first element. Suppose we declare an
array x as follows:
int x[5] = {1,2,3,4,5};
Suppose the base address of x is 1000 and assuming that each integer
requires two bytes, the five elements will be stored as follows:
Element x[0] x[1] x[2] x[3] x[4]
Value 1 2 3 4 5 

Address  1000 1002 1004 1006 1008


The name x is defined as integer pointer pointing to the first
element,x[o]and therefore the vale of x is 1000,the location where x[0]is
stored. That is,
X = &x[0] =1000
If we declare p as an integer pointer, then we can make the pointer p to
point the array x by the following assignment:
P = x;
This is equivalent to P = &x[0];
(ANSI standereD permits a pointer to an array to be obtained by applying
the &operator to the array name itself.)
Eg:- int a[5]={2,4,5,6,8};
int *p;
p+0=&a[0];
p+1=&a[1];
p+2=&a[2];
p+3=&a[3];

Array is declared then the compiler allocates a base address and


sufficient amount of storage to contain all the elements.

Write a program using pointers calculate the sum of five numbers.


#include<stdio.h>
main()
{
int a[5],*p,sum,i;
clrscr();
p=&a[0];
sum=0;
printf("Enter FIVE elements\n");
for(i=0;i<5;i++)
scanf("%d",p+i);
printf("Element --> Address --> Value\n");
for(i=0;i<5;i++)

78
C-LANGUAGE

{
printf("a[%d] %u %d\n",i,p,*p);
sum=sum+*p;
p++;
}
printf("Sum of elements = %d",sum);
getch();
}

Write the above program using functions.


#include<stdio.h>
main()
{
int a[5],i;
clrscr();
printf("Enter 5 elements:");
for(i=0;i<5;i++)
scanf("%d",&a[i]);
sum(&a,5);
getch();
}
sum(int *j,int n)
{
int s=0,i;
printf("Element Address value\n");
for(i=0;i<n;i++)
{
printf(" a[%d] %u %d\n",i,j+i,*(j+i));
s=s+*(j+i);
}
printf("Sum of 5 elements =%d",s);
}

Accept n elements into an array and display the search no is found


or not.
#include<stdio.h>
main()
{
int a[50],i,n,*p,sno;
clrscr();
p=&a[0];
printf("Enter how many elements:");
scanf("%d",&n);
printf("Enter %d elements:",n);
for(i=0;i<n;i++)
scanf("%d",p+i);

79
C-LANGUAGE

printf("Enter search no:");


scanf("%d",&sno);
for(i=0;i<n;i++)
{
if(sno==*(p+i))
{
printf("Search no is found\n");
printf("Position is %d",i+1);
break;
}
}
if(i==n)
printf("Search no is not Found");
getch();
}

Exercises:
1) Accept n elements into an array and display in sorting order.

Double dimensional arrays:


1) Display mXn matrix program using functions.
#include<stdio.h>
main()
{
int a[10][10],m,n;
clrscr();
printf("Enter how many rows and columns:");
scanf("%d %d",&m,&n);
printf("Enter %d elements:",m*n);
accept(&a,m,n);
printf("\nThe matrix is:\n");
display(&a,m,n);
getch();
}

accept(int *p,int m,int n)


{
int i,j;
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
scanf("%d",(p+i)+j);
}
}
display(int *p,int m,int n)
{

80
C-LANGUAGE

int i,j;
for(i=0;i<m;i++)
{
printf("\n");
for(j=0;j<n;j++)
printf("%d\t",*(p+i)+j);
}
}

Exercises:
1) Accept mXn matrix and display the transpose of the given matrix.

POINTERS AND STRINGS :


A string is an array of characters stored in consecutive memory
locations. Strings are used to store text information and to perform
manipulations on them. A string must be terminated with a null character
at the end of the string.

Print string elements using pointer notation.


#include<stdio.h>
main()
{
char name[]=”data infotech”;
char *ptr;
clrscr();
ptr=name;
while(*ptr!=’\0’)
{
printf(“%c”,*ptr);
ptr++;
}
}

DYNAMIC MEMORY ALLOCATION:


In C programming language, we are having two types of memory
management.
1. Static memory management.
2. Dynamic memory management.

Static memory management: -


 When we are creating the memory at the time of compilation then it
is called static memory allocation or compile time memory
management.
 Static memory allocation is under control of compiler.

81
C-LANGUAGE

 When we are working with static memory allocation, it is not


possible to extend the memory at the time of execution, it is not
sufficient.
 When we are working with static memory allocation, we need to go
for pre allocation of memory that is how many bytes of data required
to be created is needed to be decided using coding only.
Ex: int a; //2B
int arr[20]; //40B

Dynamic memory management:


 It is a procedure of allocating or deallocating memory at run time
that is dynamically.
 By using DMA, we can utilize the memory more efficiently according
to the requirement.
 By using DMA, whenever we want create dynamically.
 DMA related all predefined functions are available in <alloc.h>,
<malloc.h>, <stdlib.h>.

DMA related pre defined functions are:


malloc() calloc() realloc() free()
farmalloc() farcalloc() farrealloc() farfree()

malloc(): By using this pre defined function, we can create the memory
dynamically at initial stage.
malloc function require one argument of type size_type that is data type
size.
malloc() creates memory in bytes format and initial value is garbage.
Syntax:
void* malloc(size_type);
when we are working with DMA related functions, we are required to
perform type casting because function returns void *.
Ex:
int *p;
p=(int*)malloc(sizeof(int));

float *p;
p=(float*)malloc(sizeof(float));

int *p;
p=(int*)malloc(sizeof(int)*10);

free():- By using this pre defined function, we can deallocate dynamically


allocated memory.
When we are working with DMA related memory, it stores in heap
area of data segment and it is permanent memory, if we are not
deallocating.

82
C-LANGUAGE

When we are working with DMA related programs, at the end of the
program recommended to deallocate memory by using free() function.
free() function requires one argument of type (void*) and retrurns
void type.

Syntax: void free(void *ptr);


Ex: free(p);

calloc(): - By using this pre defined function, we can create the memory
dynamically at initial stage.
calloc() requires two argument of type (count,type_size)
count will provide no of elements, size_type is data type size.
When we are working with calloc() function, it creates the memory in
block format and initial value is zero.

Syntax:
pointervariable=(datatype*)calloc(size,sizeof(datatype));
Ex: int *p;
We want to store 5 elements for the above variable
p=(int*)calloc(5,sizeof(int));

realloc: - By using this predefined function we can create the memory


dynamically at middle stage of the program.
Generally this function is required to use when we are reallocating
memory.
realloc() requires two argument of type void*, size_type.
When we are working with realloc() function, it creates the memory
in bytes format and initial value is garbage.
Syntax:
pointer variable=(datatype*)realloc(pointervarible,size);
Ex: char *s;
s=(char *)malloc(10);
s=(char*)realloc(s,15);

Accept two numbers and display the sum.


#include<stdio.h>
main()
{
int *p,*q,*sum;
clrscr();
p=(int*)malloc(sizeof(int));
q=(int*)malloc(2);
sum=(int*)malloc(2);
printf("Enter two numbers");
scanf("%d%d",p,q);
*sum=*p+*q;

83
C-LANGUAGE

printf("Sum = %d",*sum);
free(p);
free(q);
free(sum);
getch();
}
Exercises:
1) Accept three numbers and display the biggest number using
pointers.
2) Accept a number and display in reverse order.

Single dimensional arrays:


Write a program using accept n numbers and display that numbers.
(Using malloc function).
#include<stdio.h>
main()
{
int i,n,*p;
clrscr();
printf("Enter how many elements:");
scanf("%d",&n);
p=(int*)malloc(n*sizeof(int));
printf("Enter %d elements:",n);
for(i=0;i<n;i++)
scanf("%d",p+i);
printf("The elements are:\n");
for(i=0;i<n;i++)
printf("%d\t",*(p+i));
getch();
}

Write the above program using Using calloc function.


#include<stdio.h>
main()
{
int i,n,*p;
clrscr();
printf("Enter how many elements:");
scanf("%d",&n);
p=(int*)calloc(n,sizeof(int));
printf("Enter %d elements:",n);
for(i=0;i<n;i++)
scanf("%d",p+i);
printf("The elements are:\n");
for(i=0;i<n;i++)
printf("%d\t",*(p+i));

84
C-LANGUAGE

getch();
}

Exercises:
1) Accept n elements into an array and display the search no is found
or not.
2) Accept n elements into an array and display in sorting order.

Double dimensional arrays:


Display mXn matrix(using malloc function)
#include<stdio.h>
main()
{
int i,j,m,n,*p;
clrscr();
printf("Enter how many rows and columns:");
scanf("%d %d",&m,&n);
p=(int*)malloc(m*n*sizeof(int));
printf("Enter %d elements:",m*n);
for(i=0;i<m;i++)
{

for(j=0;j<n;j++)
scanf("%d",(p+i)+j);
}
printf("The Matrix is:\n");
for(i=0;i<m;i++)
{
printf("\n");
for(j=0;j<n;j++)
printf("%d\t",*(p+i)+j);
}
getch();
}

Display mXn matrix(using calloc function)


#include<stdio.h>
main()
{
int i,j,m,n,*p;
clrscr();
printf("Enter how many rows and columns:");
scanf("%d %d",&m,&n);
p=(int*)calloc(m*n,sizeof(int));
printf("Enter %d elements:",m*n);
for(i=0;i<m;i++)

85
C-LANGUAGE

{
for(j=0;j<n;j++)
scanf("%d",(p+i)+j);
}
printf("The Matrix is:\n");
for(i=0;i<m;i++)
{
printf("\n");
for(j=0;j<n;j++)
printf("%d\t",*(p+i)+j);
}
getch();
}

Exercises:
1) Accept mXn matrix and display the transpose of the given matrix.

86
C-LANGUAGE

STRUCTURES
A structure is a collection of different types of data elements in a single
entity.
A structure is a combination of primitive and derived data type variables.
By using structures we can create user defined data types.
Size of the structure is sum of all member variable sizes.

Syntax:-
struct <structurename>
{
datatype variable;
datatype variable;
datatype variable;
datatype variable;
};

ex:-
struct student
{
int rno;
char name[20];
int m1,m2,m2;
int tot;
float avg;
};

According to syntax of the structure, semicolon must be required at the


end of the structure body.
Ex1:
struct emp
{
int id;
char name[36];
int sal;
};
sizeof(struct emp)  40B

Ex2:
struct student
{
int rno;
char sname[20];
char fname[20];
int marks;
float avg
};

87
C-LANGUAGE

sizeof(struct emp)  48B

Declaring structure variables:


In the structure declaration: The structure variables can be specified
after the closing brace.
Ex: struct student
{
int rno;
char name[20];
float marks;
}s1,s2;
Using the structure tag: We can declare structure variables using the tag
name any where in the program.
Syntax:- struct <tagname> <structurevariable>;
Ex:- struct student s;

Accessing structure members:


 We can access structure members using structure variable.
Syntax:-
structurevariable. membervariable;
Ex:-
s.rno=10;
Scanf(“%d”,s.rno);
 The members of a structure are not variables. They do not occupy any
memory until they are associated with the structure variables.
 The template is terminated with a “;”.
 Structure name (tag name) is optional.
Ex: struct
{
int rno;
char name[20];
}s;

Accept two numbers and display the sum.


#include<stdio.h>
struct sum
{
int a;
int b;
}
struct sum s;
main()
{
int tot;
clrscr();

88
C-LANGUAGE

printf(“Enter two numbers:”);


scanf(“%d %d”,&s.a,&s.b);
tot=s.a+s.b;
printf(“Sum=%d”,tot);
getch();
}
Exercises:
1)Accept roll number, name and three subjects of marks and display
the total ,average, result and class.
1) Accept meterno,name,previous reading and present reading and
calculate the total units and charge.

Arrays Of Structures
We use structures to describe the format of a number of related
variables. For example, in analyzing the marks obtained by a class of
students, we may use a template to describe student name and marks
obtained in various subjects and then declare all the students as structure
variables. In such cases, we may declare an array of structures, each
element of the array representing a structure variable. For example,
struct class student[100];
defines an array called student, that consists of 100 elements. Each
element is defined to be of the type struct class. Consider the following
declaration:
struct marks
{
int subject1;
int subject2;
int subject3;
};
main()
{
static struct marks
student[3]={{45,68,81},{58,65,28},{12,92,75
}};
This declares the student as an array of three elements student[0],
student[1] and student[2] and initializes their members as follows:
student[0],subject1=85;
student[0],subject2=46;
………………………..
………………………..
student[2],subject3=72;

Accept five student details and display total, average, result and
class.
#include<stdio.h>

89
C-LANGUAGE

struct student
{
int rno,m1,m2,m3,tot;
char name[30],res,class;
float avg;
};
struct student s[5];
main()
{
int i;
clrscr();
for(i=0;i<5;i++)
{
printf("Enter rollno:");
scanf("%d",&s[i].rno);
printf("Enter name:");
scanf("%s",&s[i].name);
printf("Enter three subject marks:");
scanf("%d %d %d",&s[i].m1,&s[i].m2,&s[i].m3);
s[i].tot=s[i].m1+s[i].m2+s[i].m3;
s[i].avg=s[i].tot/3.0;
if(s[i].m1>=35 && s[i].m2>=35 && s[i].m3>=35)
{
s[i].res='p';
if(s[i].avg>=60)
s[i].class='1';
else
if(s[i].avg>=50)
s[i].class='2';
else
s[i].class='3';
}
}
for(i=0;i<5;i++)
{
clrscr();

printf("\t\t----------------------------------------\n");
printf("\t\t STUDENT MARKS REPORT \n");
printf("\t\t----------------------------------------\n");
printf("\t\tROLL NO :%d\n",s[i].rno);
printf("\t\tNAME :%s\n",s[i].name);
printf("\t\tMATHS :%d\n",s[i].m1);
printf("\t\tPHY :%d\n",s[i].m2);
printf("\t\tCHE :%d\n",s[i].m3);
printf("\t\tTOTAL :%d\n",s[i].tot);

90
C-LANGUAGE

printf("\t\tAVERAGE :%f\n",s[i].avg);
if(s[i].res=='p')
printf("\t\tRESULT :PASS\n");
else
printf("\t\tRESULT :FAIL\n");
if(s[i].class=='1')
printf("\t\tCLASS :FIRST\n");
else
if(s[i].class=='2')
printf("\t\tCLASS :SECOND\n");
else
if(s[i].class=='3')
printf("\t\tCLASS :THIRD\n");
else
printf("\t\tCLASS :NILL\n");
printf("\n\nPress any key to continue............\n");
getch();
}
}

Exersises:
1)Calculate the electricity bill for n members

Structure Within Structures:- Structure within a structure means nesting


of structures. Nesting of structures is permitted in “C”. Let us consider the
following structure defined to store information about the salary of
employees.

struct salary
{
char name[30];
char department[12];
int basic_pay;
int dearness_allowance;
int house_rent_allowance;
int city_allowance;
}employee;
This structure defines name, department, basic pay and three kinds of
allowances.we can group all the items related to allowance together and
declare them under a substructure as shown below:
struct salary
{
char name[20];
char department[10];
struct
{

91
C-LANGUAGE

int dearness;
int house_rent;
int city;
}
allowance;
}
employee;
The salary structure contains a member named allowance which itself is a
structure with three members. The members contained in the inner
structure namely dearness, house_rent, and city can be referred to as
employee.allowance.dearness
employee.allowance.house_rent
employee.allowance.city
Example
#include<stdio.h>
struct student
{
int rno;
char name[20];
};
struct marks
{
int m1,m2,m3;
int tot;
struct student s;
};
struct marks m;
main()
{
clrscr();
printf("Enter roll no:");
scanf("%d",&m.s.rno);
printf("Enter name:");
scanf("%s",&m.s.name);
printf("Enter three subject marks:");
scanf("%d %d %d",&m.m1,m.m2,&m.m3);
m.tot=m.m1+m.m2+m.m3;
printf("Total=%d",m.tot);
getch();
}

Structures With Pointers:-


We know that the name of an array stands for the address of its
zero element. The same thing of the names of arrays of structure
variables.

92
C-LANGUAGE

We can use structure variable as pointer variable then member


variables are accessed following form.
Syntax:- structvariable  membervariable;
Ex:- struct sss
{
int a,b,c;
}*p;
pa=10;

To calculate electricity bill.


#include<stdio.h>
struct ebill
{
int mno,lmr,pmr,units;
char name[20];
float charge;
};
struct ebill *e;
main()
{
clrscr();
printf(“Enter meter no:”);
scanf(“%d”,&e->mno);
printf(“Enter name:”);
scanf(“%s”,&e->name);
printf(“Enter previous Reding:”);
scanf(“%d”,&e->lmr);
printf(“Enter present reading:”);
scanf(“%d”,&e->pmr);
e->units=e->pmr-e->lmr;
if(e->units<=50)
e->charge=50;
else
if(e->units<=100)
e->charge=50+(e->units-50)*2;
else
if(e->units<=200)
e->charge=50+(50*2)+(e->units-100)*3;
else
if(e->units<=300)
e->charge=50+(50*2)+(100*3)+(e->units-200)*4;
else
e->charge=50+(50*2)+(100*3)+(100*4)+(e->units-300)*5;
clrscr();
printf(“-------------------------------------------------\n”);
printf(“ Electricity Bill \n”);

93
C-LANGUAGE

printf(“-------------------------------------------------\n”);
printf(“Meter no :%d\n”,e->mno);
printf(“Name :%s\n”,e->name);
printf(“Previous Reading :%d\n”,e->lmr);
printf(“Present Reading :%d\n”,e->pmr);
printf(“Total Units :%d\n”,e->units);
printf(“Charge :%f\n”,e->charge);
getch();
}

Structures With Functions:-


We know that the main philosophy of “C” language is the use of
functions. Therefore, it is natural that “C” supports the passing structure
values as arguments to functions. There are three methods by which the
values of a structure can be transferred from one function to another.
The first method is to pass each member of the structure as an
actual argument of the function call. The actual arguments are then
treated independently like ordinary variables. This is the most elementary
method and becomes unmanageable and inefficient when the structure
size is large.
The second method involves passing of a copy of the entire
structure to the called function. Since the function is working on a copy of
the structure, any changes to structure members within the function are
not reflected in the original structure ( in the calling function). It is,
therefore, necessary for the function to return the entire structure back to
the calling function. All compilers may not support this method of passing
the entire structure as a parameter.
The third approach employs a concept called pointers to pass the
structure as an argument. In this case, the address location of the
structure is passed to the called function. The function can access
indirectly the entire structure and work on it. This is similar to the way
arrays are passed to functions. This method is more efficient as compared
to the second one.
In this section. We discuss in detail the second method, while the
third approach using pointers is discussed in the next chapter, where
pointers are dealt in detail.
The general format of sending a copy of a structure to the called
function is:
To pass the structure variables similarly ordinary variables in the function.

To calculate sum using function.


#include<stdio.h>
struct sum
{
int a,b;
int t;

94
C-LANGUAGE

};
struct sum s;
main()
{
clrscr();
printf("Enter two numbers:");
scanf("%d %d",&s.a,&s.b);
s.t=add(s.a,s.b);
printf("Sum=%d",s.t);
getch();
}
add(int a,int b)
{
int r;
r=a+b;
return(r);
}

Passing entire structure to the function for above program.


#include<stdio.h>
struct sum
{
int a,b;
int t;
};
struct sum s;
main()
{
clrscr();
printf("Enter two numbers:");
scanf("%d %d",&s.a,&s.b);
s.t=add(s);
printf("Sum=%d",s.t);
getch();
}
add(struct sum k)
{
int r;
r=k.a+k.b;
return(r);
}

95
C-LANGUAGE

Unions:-
A Union is a collection of different types of data elements in a single
entity.
 Unions are similar to structures the major difference between storage.
In structures each member has its own location where as all members of a
union use the same location.
In implementation, for manipulation of the data, if we are using only one
member then it is recommended to go for Union.
When we are working with unions, all member variables will share same
memory location.
By using union, when we are manipulating multiple members then actual
data is lost.

Syntax:
Union <union name>
{
datatype variable1;
datatype variable2;
};
Ex:- union sss
{
int a;
float b;
}s;
The compiler allocates a space of storage location. i.e largest variable in
the union.

Example
#include<stdio.h>
union sample
{
int a;
float b;
};
union sample s;
main()
{
clrscr();
s.a=10;
s.b=123.45;
printf("\na=%d",s.a);
printf("\nb=%f",s.b);
getch();
}

96
C-LANGUAGE

FILE HANDLING
A file is a name of physical memory location in secondary memory area.
File contains sequence of bytes of data in secondary storage area in the
form of un structured manner.
In implementation, when we required to interact with secondary storage
area, then recommended to go for file operations.
By using files, primary memory related data can be send to secondary
storage area and secondary storage area information can be loaded to
primary memory.
In C programming language, I/O operations are classified into two types:
1. Standard I/O operations.
2. Secondary I/O operations.
When we interacting with primary I/O devices, then it is called standard
I/O operations.
When we interacting with secondary I/O devices, then it is called
secondary I/O operations.
Standard I/O related and Secondary I/O related predefined functions are
available in stdio.h.

File functions:
fopen fclose fprintf putc fputs
getc fscanf fgets fgetchar fread
fwrite flushall ftell feof fseek
remove rename rewind fflush

constants:
EOF NULL SEEK_CUR SEEK_END SEEK_SET

Data type:
FILE

Global variables:
stdin stdout stderr stdprn

fopen:- It is a pre defined function, which is declared in stdio.h.


By using this function we can open a file in specific path with specific
mode.
It requires two arguments of type and const char*.
On success, fopen() returns FILE, on failure returns NULL.
Generally fopen() is failed to open in following cases.
 Path is incorrect.
 Mode is incorrect.
 Permissions are not available.
 Memory is not available.

97
C-LANGUAGE

Syntax:- fopen(“file name”,”mode”);


Ex:- fp=fopen(“First”,”r”);

“fp” is a pointer variable. This variable is defined by “FILE” type.


“FILE” is a standard library I/O functions definitions. All files should be
declared as type is “FILE”. “FILE” is a defined data type.
Mode statement specify the purpose of file. There are three types of
modes.
i) r(read):- open the file for reading only.
ii) w(write):- open the file for writing.
iii) a(appending):- open the file for appending data.
Both file name and mode are specified as strings. They are enclose in a “”.

fclose():
 By using this predefined function, we can close the file after saving
data.
fclose() requires one argument of type FILE and returns an int value.

Syntax:- fclose(file pointer);


Ex:- fclose(fp);

File modes: -
Always file modes will indicate that for what purpose file need to be
open or create.
File modes are classified in to 3 types:
1. write
2. read
3. append
Depending on operations, file modes are classified into six types:
1.w(write): - Create file for writing, if file already exists, then it will
override. (old file is deleted and new file is created)
If file doesn’t exist then new file will be created.
In “w” mode, file exist or not, always new file is constructed.

2.r(read): - Open an existing file for reading, if the file does not exist then
fopen() returns null.

3.a(append): - Open an existing file for appending (write the data at end of
file) or create a new file for writing if it does not exist.

4.w+(write and read): - Create a file for update that is write and read, if
file already exists then it will override.
In w+ mode, if file is available or not, always new file is constructed.

5.r+(read and write): - Open an existing file for update that is read and
write.

98
C-LANGUAGE

Generally r+ mode is required, when we need to update existing


information.
In r+ mode, if file does not exist, new file is not constructed.

6.a+(w+ and r+): - Open an existing file for update or create a new file for
update.
By using a+ mode, we can perform random operations.

Character input & output functions:


1) putc: This is used to write a character to the file.
Syntax:- putc(character variable,pointer variable);
Ex:- char ch;
FILE *fp;
putc(ch,fp);

Enter information to data file using putc function.


#include<stdio.h>
main()
{
FILE *fp;
char ch;
clrscr();
fp=fopen(“data”,”w”);
printf(“Enter contents”);
while((ch=getchar())!=EOF)
putc(ch,fp);
fclose(fp);
}
EOF:- it means End Of File.

getc:- It is used to read a character from the file.


Syntax:- character variable= getc(pointer variable);
Ex: ch=getc(fp);

Display contents of data file using getc function.


#include<stdio.h>
main()
{
FILE *fp;
char ch;
clrscr();
fp=fopen(“data”,”r”);
while((ch=getc(fp))!=EOF)
putchar(ch);
fclose(fp);
}

99
C-LANGUAGE

fprintf:- This is used to write a set of data values into the file.
Syntax:- fprintf(pointer variable, “control string”, variable);
Ex:-fprintf(fp,”SUM=%d”,sum);
fscanf:- It is used to read set of values to the file.
Syntax:- fscanf(pointer variable,”control string”, variable);
Ex:-fscanf(fp,”%d”,&a,&b);

Write the contents of student details in student file.


#include<stdio.h>
main()
{
int rno,m1,m2,m3,tot;
float avg;
char name[30],res,class;
FILE *p;
clrscr();
printf("Enter Rollno");
scanf("%d",&rno);
printf("Enter name");
scanf("%s",&name);
printf("Enter three subjects marks");
scanf("%d%d%d",&m1,&m2,&m3);
tot=m1+m2+m3;
avg=tot/3.0;
if(m1>=35&&m2>=35&&m3>=35)
{
res='p';
if(avg>=60)
class='1';
else
if(avg>=50)
class='2';
else
if(avg>=35)
class='3';
}
p=fopen("student","w");
clrscr();
fprintf(p,"---------------------------------\n");
fprintf(p,"Student Report\n");
fprintf(p,"---------------------------------\n");
fprintf(p,"Rollno : %d\n",rno);
fprintf(p,"Name : %s\n",name);
fprintf(p,"Maths : %d\n",m1);
fprintf(p,"Physics : %d\n",m2);
fprintf(p,"Chemistry : %d\n",m3);

100
C-LANGUAGE

fprintf(p,"Total : %d\n",tot);
fprintf(p,"Average : %.2f\n",avg);
if(res=='p')
fprintf(p,"Result : Pass\n");
else
fprintf(p,"Result : Fail\n");
if(class=='1')
fprintf(p,"Class : First\n");
else
if(class=='2')
fprintf(p,"Class : Second\n");
else
if(class=='3')
fprintf(p,"Class : Third\n");
else
fprintf(p,"Class : Nill\n");
fprintf(p,"---------------------------------\n");
}

Using fscanf function.


#include<stdio.h>
main()
{
char s[80];
FILE *p;
clrscr();
p=fopen("student","r");
while((fscanf(p,"%s",&s))!=EOF)
printf("%s",s);
getch();
}

101
C-LANGUAGE

COMMAND LINE ARGUMENTS


 It is a procedure of passing the arguments to the main function from
command prompt.
 By using command line arguments, we can create user defined
commands.
 In implementation, when we required to develop an application for
DOS operating system then recommended to go for command line
arguments.
 DOS is character based or command based OS that is if we require
to perform any task, we need to use specific commands only.
 When we are developing a program in command line arguments,
then main function will take two arguments that is argc and argv.
 argc is a variable of type an integer, it maintains total number of
arguments count value.
 argv is a variable of type char*, which maintains actual argument
values which is passed to main().
 In C, by default total number of arguments are 1, that is
program.exe
Ex:
#include<stdio.h>
main(int argc, char *argv[])
{
int i;
printf("Total number of arguments=%d\n",argc);
for(i=0;i<argc;i++)
{
printf("%d argument is %s\n",i+1,argv[i]);
}
}
Save the file as mytest.c

 Load the command prompt and change the directory to specific


location where application available.
 To execute the program, just we required to use the program name
or program name.exe
 Command line arguments related programs not recommended to
execute by IDE because we can’t pass the arguments to main
function.
C:\tc>mytest 10 hello 20
Total no of arguments: 4
1 argument: mytest
2 argumetn:10
3 argumetn:hello
4 argumetn:20

102
C-LANGUAGE

1) Create a COPY CON command.


#include<stdio.h>
void main(int argc, char *argv[])
{
FILE *fp;
char ch;
if(argc<2)
{
printf(“\n Required parameter Missing\n”);
exit(0);
}
else if(argc<2)
{
printf(“\nToo many parametes\n”);
exit(0);
}
fp=fopen(argv[1],”w”);
while((ch=getchar())!=EOF)
putc(ch,fp);
fclose(fp);
}

2) Create DOS type command.


#include<stdio.h>
void main(int argc, char *argv[])
{
FILE *fp;
char ch;
clrscr();
if(argc<2)
{
printf(“\n Required parameter Missing\n”);
exit(0);
}
else if(argc<2)
{
printf(“\nToo many parametes\n”);
exit(0);
}
fp=fopen(argv[1],”r”);
if(fp==NULL)
{
printf(“\nFile not found”);
exit(0);
}

103
C-LANGUAGE

while((ch=getc(fp))!=EOF)
putchar(ch);
fclose(fp);
}

3) Create DOS copy command


#include<stdio.h>
void main(int argc, char *argv[])
{
FILE *fp1,*fp2;
char ch;
if(argc!=3)
{
printf("\n Invalid no. of parameters");
return;
}
fp1=fopen(argv[1],"r");
if(fp1==NULL)
{
printf("\n %s - File not found \n",argv[1]);
return;
}
fp2=fopen(argv[2],"w");
while((ch=getc(fp1))!=EOF)
putc(ch,fp2);
fclose(fp1);
fclose(fp2);
}

104

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy