Вы находитесь на странице: 1из 93

CHAPTER 1 ABOUT C5

C is a programming language develop at AT & T’s Bell Laboratories of USA in 1972. It was designed and
write by man named Dennis Ritchie. C is called the mother of all languages.

STEPS IN LEARNING ENGLISH LANGUAGE


Alphabets  Words  Sentences  Paragraphs

STEPS IN LEARNING C

Alphabets Constants
Digits Variables Instructions Program
Special symbols keywords

TYPE OF C CONSTANTS
(a) Primary Constants
(b) Secondary Constants

C Constants

Primary Constants Secondary


Constants

Integer Constant Array


Real Constant Pointer
Character Constant Structure
Union
Enum. Etc.

RULES FOR CONSTRUCTING INTEGER CONSTANTS


a. An integer constants muse have at least on digit
b. It must not have a decimal point
c. It can be either positive or negative
d. If no sign precedes an integer constant, it is assumed to be positive
e. No commas or blanks are allowed within an integer constant.
f. Allowable range for integer constant is -32768 to 32767
RULES FOR CONSTRUCTING REAL CONSTANTS
Real constants are often called floating point constants.
a. A real constant must have at least one digit
b. It must have a decimal point
c. It could be either positive or negative
d. Default sign is positive
e. No commas or blanks are allowed within a real constant

RULES FOR CONSTRUCTING CHARACTER CONSTANTS


a. A character constant is a single alphabet, a single digit or a single special symbol enclosed within
single inverted commas. Both the inverted commas should point to the left. For e.x. ʼAʼis a
valid character constant whereas ‘A‘
is not.
b. The maximum length of character constant can be 1 character.
e.g. ‘A’ ‘I’ ‘5’ ‘=’

TYPE OF C VARIABLES
An entity that may vary during program execution is called variable. Variable names are names given to
location in memory. These locations can contain integer, real or character constants.

Rules for constructing variable namesnrscores. Some compilers allow variable names whose length
could be up to 247 characters.
a. The first character in the variable name must be an alphabet or underscore.
b. No commas or blanks are allowed with a variable name.
c. No special symbol other than an underscore (as in gross_sal) can be used in a variable name.
e.g. si_int, m_har, pop_e_89

C KEYWORDS
Keywords are the words whose meaning has already been explained to the c compiler. The keywords
cannot be used as variable names because if we do so, we are trying to assign a new meaning to the
keyword , which is not allowed by the computer.

e.g
auto , break, case char const continue, default, do, double, else, enum, extern, float, for, goto, if, int,
struct, switch, typedef, union, unsigned, void, volatile, while

assuming that you are using a turbo c or turbo c++ compiler here are the steps that you need to
follow to compile and execute your first c program

a. Start the compiler at c> prompt. The compiler (tc.exe is usually preset in c:\tc\bin directory).
b. Select new from the file menu
c. Type the program.
d. Save the program using F2 under a proper name (say program1.c)
e. Use ctrl + f9 to compile and execute the program.
f. Use alt + f5 to view the output

1ST PROGRAM IN C :- PRINT YOUR NAME ON SCREEN

#include <stdio.h>
#include <conio.h>
void main()
{
clrscr();
printf(“my name is harish”);
getch();
}

2ND. HOW TO BREAK LINE IN PRINTF

#include <stdio.h>
#include <conio.h>
void main()
{
clrscr();
printf(“my name is harish \n my class is 12th”);
getch();
}
3RD how to use comment in c

#include<stdio.h>
#include<conio.h>
Void main()
{
Clrscr();
Printf(“hello”);
/* printf(“fine”);*/
getch();
}

4thHow write a basic program in notepad ++

#include<stdio.h>
int main()
{
printf("hello");

return 0;
}

Open cmd
Goto program folder f

Gcc ss.c (compile)


Run a (run)
5th how to add two umber
Pre define value

#include<stdio.h>
#include<conio.h>
Void main()
{
Int a=10,b=20,c=0;
Clrscr();

Printf(“the value of a is%d”,a)


Printf(“\nthe value of b is%d”,b)

C=a+b;

Printf(“\n the sum of a and b %d”,c);


Getch();
}

6th how to add two umber


Value enter by the user

#include<stdio.h>
#include<conio.h>
Void main()
{
Int a=0,b=0,c=0;
Clrscr();

Printf(“enter the value for a”);


Scanf(“%d”,&a)
Printf(“\n enter the value for b”);
Scanf(“%d”,&b)
C=a+b;
Printf(“\n the sum of a and b %d”,c);
Getch();
}
HOW TO USE FLOAT VALUE IN THE PROGRAM

#include<stdio.h>
#include<conio.h>
Void main()
{ In case of scanf
floata=10.1,b=12.3,c=0;
Printf(“enter the value of a”);
Clrscr();
Scanf(“%f”,&a);
Printf(“\n enter the value of b”);
Printf(“The value of a is:- %f”,a);
Scanf(“%f”,&b);
Printf(“\n The value of b is:- %f”,b);
c=a+b;

Printf(“\n the sum of a and b %f”,c);


Getch();
}

7th Write The Program To Add 5 Number And Also Get Average Of Marks by the user

8th writer the program of si and also get total pay amount by the user

CHAPTER 2:- THE DECISION CONTROL STRUCTURE

a decision control instruction. As mentioned earlier, a decision control instruction can be implemented
in c using.

a. The if statement
b. The if – else statement
c. The conditional operators
The if statement
The keyword if tells the compiler that follows is a decision control instruction. The condition following
the keyword if is always enclosed within a pair of parentheses. If the condition, whatever it is, is true,
then the statement is executed. If the condition is not true, then the statement not executed;

This expression Is true if


X==Y X IS EQUAL TO Y
X!=Y X IS NOT EQUALTO Y
X<Y X IS LESS THAN Y
X>Y XIS GREAER THAN Y
X<=Y X IS LESS THAN OR EQUAL TO Y
X>=Y X IS GREATER THAN OR EQUAL TO Y

Write a code for salary if user enter num greater than 10 code show “your salary
is 15000

#include<stdio.h>
#include<conio.h>
Void main()
{
Int num;
Clrscr();
Printf(“enter a number greater than 10”);
Scanf(“%d”,&num);

If(num>10)
Printf(“your salary is 15000”)
Getch();

}
PROGRAM OF FIND OUT GRATER NO IN NOTEPAD ++
#include<stdio.h>
void main()
{
int A,B,C;

printf("enter the value of A");


scanf("%d",&A);
printf("enter the value of B");
scanf("%d",&B);
printf("enter the value of C");
scanf("%d",&C);
if((A>B)&&(A>C))
{
printf("A is greater number");
}
else if((B>A)&&(B>C))
{
printf("B is greater number");
}
else
{
printf("C is greater number");
}
getch();
}

PROGRAM FOR & OPERATOR ON NOTEPAD ++


#include<stdio.h>
int main()
{
int A,B,C;

printf("enter the value of A");


scanf("%d",&A);
printf("enter the value of B");
scanf("%d",&B);
printf("enter the value of C");
scanf("%d",&C);
if((A>B)&&(A>C))
{
printf("A is greater number");
}
else if((B>A)&&(B>C))
{
printf("B is greater number");
}
else
{
printf("C is greater number");
}
return 0;
}

/*PROGRAM TO FIND OUT THE DIVISION OF MARKS */


#include<stdio.h>
int main()
{
int marks;
printf("enter the marks");
scanf("%d",&marks);
if(marks>80)
{
printf("marks are of 1st division");
}
else if((marks>50)&&(marks==60))
{
printf("marks are of 2nd division");
}
else if((marks>60)&&(marks==40))
{
printf("marks are of 3rd division");
}
else
{
printf("better luck next time");
}
return 0;
}

/*PROGRAM TO FIND THE GIVEN YEAR IS LEAP YEAR OR NOT */

include<stdio.h>

int main()

int year;

printf("enter any year:");

scanf("%d",&year);

if(((year%4==0)&&(year%100!=0))||(year%400==0))

printf("%d is a leap year",year);


}

else

printf("%d is not a leap year",year);

return 0;

/*PROGRAM TO FIND THE NUBMER IS POSITIVE OR NEGATIVE*/


#include<stdio.h>
int main()
{
int a;
printf("enter any number");
scanf("%d",&a);
if(a>0)
{
printf("number is positive");
}
else if(a<0)
{
printf("number is negative");
}
else
{
printf("number is zero");
}
return 0;
}

/* EVEN ODD PROGRAM*/IF THE NUMBER IS DIVIDED BY TWO AND WE GET THE
REMAINDER ZERO THEN THE NUMBER IS EVEN OR IT IS ODD.% MEANS THE WE CAN
CHECK THE REMAINDER.BY / WE SEE THE QUOTIENT.

#include<stdio.h>
int main()
{
int a;
printf("enter the value of a");
scanf("%d",&a);
if(a%2==0)
{
printf("the number is even");
}
else
{
printf("the number is odd");
}
return 0;
}

While the purchasing certain items, a discount of 10% is offered if the quantity purchased is more
than 1000. If quantity and price per item are input through the keyboard, write a program to calculate
the total expenses

/* calculation of total expenses */

#include<stdio.h>
#include<conio.h>
Void main()
{

Int qty,dis=0;

Float rate,tot;

Printf(“enter the quantity and rate”)

Scanf(“%d%f”,&qty,&rate);

If(qty>1000)

Dis=10;

Tot=(qty*rate)-(qty*rate*dis/100);

Printf(“total expenses =rs %f”,tot);

Getch();

}
The current year and the year in which the employee joined the organization are entered through the
keyboard. If the number of year for which the employee has served the organization is grater than 3,
then a bonus of rs 2500/- is given to the employee. If the years of service are not greater than 3, then
the program do nothing,

#include<stdio.h>

#include<conio.h>

void main()

int bonus,cy,yoj,yr_of_ser,yos;

clrscr();

printf("enter currrent year:-");

printf("enter year of joing:-");

scanf("%d%d",&cy,&yoj);

yos=cy-yoj;

if(yos>3)

bonus=2500;

printf("bonus rs %d",bonus);

getch();

}
In the company an employee is paid as under:- if his salary is less than rs. 1500, then hra =105 of basic
salary and da=90% of basic salary. If his salary either equal to or above rs 15,00, than hra = rs 500, and
da = 98% of basic salary. If the employee’s salary is input through keyboard write a program to find his
salary.

start

Input bs

Is
Bs<1500

start start

start start

start

Input bs

start

#include<stdio.h>

#include<conio.h>

void main()

float bs,gs,da,hra;

clrscr();

printf("enter the basic salary");


scanf("%f",&bs);

if(bs<1500)

hra=bs*10/100;

da=bs*90/100;

else

hra=500;

da=bs*90/100;

gs=bs+hra+da;

printf("gross salary=rs%f",gs);

getch();

Nested if- elses

It is perfectly all right if we weite an entire if-else construct with in either the body of the if statement
or the body of an else statement . this is called nesting of ifs. This is show in the following program.

#include<stdio.h>

#include<conio.h>

void main()

int i;

clrscr();

printf("enter either 1 or 2");


scanf("%d",&i);

if(i==1)

printf("this is print for 1");

else

if(i==2)

printf("this is print for 2");

else

printf("this is not 1 or 2 its another no");

getch();

The marks obtained by a student in 5 different subject are input throught the keyboard. The student
gets a division as per the following ruels.

Percentage above or equal to 60 – first division

Percentage above 50 and 59 – second division

Percentage above 40 and 49 – third division

Percentage less than 40 – fail

There are two ways in which we can write a program for the example

#include<stdio.h>

#include<conio.h>

void main()

int m1,m2,m3,m4,m5,per,marks;
clrscr();

printf("enter the marks of five subject");

scanf("%d%d%d%d%d",&m1,&m2,&m3,&m4,&m5);

marks=m1+m2+m3+m4+m5;

per=marks/5;

if(per>=60)

printf("firt division");

else

if(per>=50)

printf("second division");

else

if(per>=40)

printf("third division");

else

printf("fail");

getch();

If condition with && operator

#include<stdio.h>

#include<conio.h>

void main()

{
int m1,m2,m3,m4,m5,per,marks;

clrscr();

printf("enter the marks of five subject");

scanf("%d%d%d%d%d",&m1,&m2,&m3,&m4,&m5);

marks=m1+m2+m3+m4+m5;

per=marks/5;

if(per>=60)

printf("firt division");

if((per>=50)&&(per<60))

printf("second division");

if((per>=40)&&(per<50))

printf("third division");

if(per<40)

printf("fail");

getch();

}
Chapter 3:- the loop control structure

C Loops
The loops in C language are used to execute a block of code or a part of the program
several times.

In other words, it iterates a code or group of code many times.

Why use loops in C language?


Suppose that you have to print table of 2, then you need to write 10 lines of code.

By using the loop statement, you can do it by 2 or 3 lines of code only.

Advantage of loops in C
1) It saves code.

2) It helps to traverse the elements of array (which is covered in next pages).

Types of C Loops
There are three types of loops in C language that is given below:

1. do while

2. while

3. for

There are three methods by way of which we can repeat a part of a program. They are:
(a) Using a for statement
(b) Using a while statement
(c) Using a do – while statement
Loop condition is two type
1. Control statement (a) entry controlled Loop, (b) exit controlled loop
2. Body of loop

(a) Entry controlled loop

Enter the program


|
|

Conditi False
on ?

True

Body of Loop

Statement x
(b) exit controlled loop
|
|
Body of Loop

Conditi True ----------


on ?

|
False
|
Statement x

(a) While or for Loop is under taken Entry controlled loop


(c) Do while loop is under taken exit controlled loop
while loop in C
The while loop in C language is used to iterate the part of program or statements many
times.

In while loop, condition is given before the statement. So it is different from the do while
loop. It can execute the statements 0 or more times.

When use while loop in C


The C language while loop should be used if number of iteration is uncertain or unknown.

The while loop:-


Write a code for print your name at five time.

#include<stdio.h>
int main()
{
int i=1;
while(i<5)
{
printf("suraj");
i++;
}
return 0;
}
Example of while loop in C language
Let's see the simple program of while loop that prints table of 1.

1. #include<stdio.h>
2. int main(){
3. int i=1;
4. while(i<=10){
5. printf("%d \n",i);
6. i++;
7. }
8. return 0;
9. }

Output 1 2 3 4 5 6 7 8 9 10

Program to print table for the given number using


while loop in C
1. #include<stdio.h>
2. int main(){
3. int i=1,number=0;
4. printf("Enter a number: ");
5. scanf("%d",&number);
6. while(i<=10){
7. printf("%d \n",(number*i));
8. i++;
9. }
10. return 0;
11. }

Output
Enter a number: 50
50
100
150
200
250
300
350
400
450
500

Calculation of simple interest for 3 sets of p,n,r

#include<stdio.h>
#include<conio.h>
Void main()
{
Int count,p,n;
Float r,si;
Clrscr();
Printf(“enter the count for si”);
Scanf(“%d”,& count);
While(count<=5)
{
Printf(“enter the p n r”);
Scanf(“%d%d%f”,&p,&n,&r);
Si=p*n*r/100;
Printf(“the si is %f”,si);
Count=count+1;
}
Getch();
}

Enter count by the user and program run number of time which user enter

#include<stdio.h>
#include<conio.h>
Void main()
Int count=0,a=1,p,n;
Float si,r;
Clrscr();
Printf(“enter the count for run the code”);
Scanf(“%d”,&count);
While(a<=count)
{
Printf(“enter p n r”);
Scanf(“%d%d%f”,&p,&n,&r);
Si=p*n*r/100;
Printf(“%f”,si);
a=a+1;
}
Getch();
}

While loop Factorial Program


#include<stdio.h>
#include<conio.h>v
Void main()
{
int i,n,f=1;
clrscr();
printf("enter a number");
scanf("%d",&n);
i=1;
while(i<=n)
{
f=f*i;
i++;
printf("%d\n",f);

}
Getch();
}

do while loop in C
To execute a part of program or code several times, we can use do-while loop of C
language. The code given between the do and while block will be executed until condition is
true.

In do while loop, statement is given before the condition, so statement or code will be
executed at lease one time. In other words, we can say it is executed 1 or more times.

It is better if you have to execute the code at least once.


do while example
There is given the simple program of c language do while loop where we are printing the
table of 1.

1. #include<stdio.h>
2. int main(){
3. int i=1;
4. do{
5. printf("%d \n",i);
6. i++;
7. }while(i<=10);
8. return 0;
9. }

Output
1 2 3 4 5 6 7 8 9 10

Program to print table for the given number using do while loop
1. #include<stdio.h>
2. int main(){
3. int i=1,number=0;
4. printf("Enter a number: ");
5. scanf("%d",&number);
6. do{
7. printf("%d \n",(number*i));
8. i++;
9. }while(i<=10);
10. return 0;
11. }

Output
;- 5 10 15 20 25 30 35 40 45 50

for loop in C
The for loop in C language is also used to iterate the statement or a part of the program
several times, like while and do-while loop.

But, we can initialize and increment or decrement the variable also at the time of checking
the condition in for loop.

Unlike do while loop, the condition or expression in for loop is given before the statement,
so it may execute the statement 0 or more times.

When use for loop in C


For loop is better if number of iteration is known by the programmer.
Flowchart of for loop in C

Example of for loop in C language


Let's see the simple program of for loop that prints table of 1.

1. #include<stdio.h>
2. int main(){
3. int i=0;
4. for(i=1;i<=10;i++){
5. printf("%d \n",i);
6. }
7. return 0;
8. }

Output
1
2
3
4
5
6
7
8
9
10

C Program : Print table for the given number using


C for loop
1. #include<stdio.h>
2. int main(){
3. int i=1,number=0;
4. printf("Enter a number: ");
5. scanf("%d",&number);
6. for(i=1;i<=10;i++){
7. printf("%d \n",(number*i));
8. }
9. return 0;
10. }

Output
Enter a number: 2
2
4
6
8
10
12
14
16
18
20

Program to print *

#include<stdio.h>

#include<conio.h>

void main()

int i,j,row;

printf("enter the numner of row");

scanf("%d",&row);

for(i=1;i<=row;i++)

for(j=1;j<=i;j++)

printf("*");

printf("\n");

getch();

Print star pattern

#include<stdio.h>

#include<conio.h>

void main()

int i,j,row;

printf("enter the number of rown:");

scanf("%d",&row);
for(i=1;i<=row;i++)

for(j=row;j>=i;j--)

printf("*");

printf("\n");

getch();

C break statement
The break statement in C language is used to break the execution of loop (while, do while
and for) and switch case.

In case of inner loops, it terminates the control of inner loop only.

There can be two usage of C break keyword:

1. With switch case


2. With loop
Flowchart of break in c

#include<stdio.h>

#include<conio.h>

void main()

int i=1;

for(i=1;i<=10;i++)

printf("%d \n", i);

if(i==5)

break;

getch();

Output 1 2 3 4 5

C break statement with inner loop


In such case, it breaks only inner loop, but not outer loop.
#include<stdio.h>

#include<conio.h>

void main()

int i=1,j=1;

clrscr();

for(i=1;i<=3;i++)

for(j=1;j<=3;j++)

printf("%d %d\n",i,j);

if(i==2 && j==2)

break;

getch();

Output
1 1
1 2
1 3
2 1
2 2
3 1
3 2
3 3

C continue statement
The continue statement in C language is used to continue the execution of loop (while, do
while and for). It is used with if condition within the loop.

In case of inner loops, it continues the control of inner loop only.

#include<stdio.h>
#include<conio.h>

void main()

int i=1;

for(i=1;i<=10;i++)

if(i==5)

continue;

printf("%d\n",i);

getch();

Output
1
2
3
4
6
7
8
9
10
As you can see, 5 is not printed on the console because loop is continued at i==5.

C continue statement with inner loop


In such case, C continue statement continues only inner loop, but not outer loop.

#include<stdio.h>

#include<conio.h>

void main()

int i=1,j=1;

clrscr();
for(i=1;i<=3;i++)

for(j=1;j<=3;j++)

if(i==2 && j==2)

continue;

printf("%d%d\n",i,j);

getch();

Output
1 1
1 2
1 3
2 1
2 3
3 1
3 2
3 3

As you can see, 2 2 is not printed on the console because inner loop is continued at i==2
and j==2.

C goto statement
The goto statement is known as jump statement in C language. It is used to unconditionally
jump to other label. It transfers control to other parts of the program.

It is rarely used today because it makes program less readable and complex.
goto example
#include<stdio.h>

#include<conio.h>

void main()

int age;

ineligible:printf("you are not eligible to vote!!!!\n");

printf("enter your age");

scanf("%d",&age);

if(age<18)

goto ineligible;

else

printf("you are eligible to vot!!!!!\n");

getch();

Type Casting in C // force fully conversion


Type casting allows us to convert one data type into other. In C language, we use cast
operator for type casting which is denoted by (type).

Without casting With casting

#include<stdio.h> #include<stdio.h>

#include<conio.h> #include<conio.h>

void main() void main()

{ float b; { float b;

clrscr(); clrscr();

b=5/2; b=(float) 5/2;

printf("value of %f",b); printf("value of %f",b);

getch(); } getch(); }
Functions in C
The function in C language is also known as procedure or subroutine in other
programming languages.

To perform any task, we can create function. A function can be called many times. It
provides modularity and code reusability.

advantage of functions in C
There are many advantages of functions.

1) Code Reusability
By creating functions in C, you can call it many times. So we don't need to write the same
code again and again.

2) Code optimization
It makes the code optimized, we don't need to write much code.

Suppose, you have to check 3 numbers (781, 883 and 531) whether it is prime number or
not. Without using function, you need to write the prime number logic 3 times. So, there is
repetition of code.

But if you use functions, you need to write the logic only once and you can reuse it several
times.

Types of Functions
There are two types of functions in C programming:

1. Library Functions: are the functions which are declared in the C header files such
as scanf(), printf(), gets(), puts(), ceil(), floor() etc.
2. User-defined functions: are the functions which are created by the C programmer,
so that he/she can use it many times. It reduces complexity of a big program and
optimizes the code.
Parameters in C Function
A c function may have 0 or more parameters. You can have any type of parameter in C
program such as int, float, char etc. The parameters are also known as formal arguments.

Example of a function that has 0 parameter:

1. void hello(){
2. printf("hello c");
3. }

Calling a function in C
If a function returns any value, you need to call function to get the value returned from the
function. The syntax of calling a function in c programming is given below:

1) variable: The variable is not mandatory. If function return type is void, you must not
provide the variable because void functions doesn't return any value.

2) function_name: The function_name is name of the function to be called.

3) arguments: You need to provide arguments while calling the C function. It is also
known as actual arguments.

Example to call a function:


1. ello();//calls function that doesn't return a value
2. int value=get();//calls function that returns value
3. int value2=add(10,20);//calls parameterized function by passing 2 values

Example of C function with no return statement


Let's see the simple program of C function that doesn't return any value from the function.

#include<stdio.h>
#include<conio.h>
void hello()
{ printf("hello c function "); }

void main()
{
clrscr();
hello();
hello();

getch();
}
Example of C function with return statement
Let's see the simple program of function in c language.

#include<stdio.h>
#include<conio.h>
//defining fuction

int cube(int n)
{
return n*n*n;

void main()
{
int result1=0,result2=0;
result1=cube(2); //calling function
result2=cube(3);

printf("%d \n", result1);


printf("%d \n", result2);
getch();
}

Output 8 , 27
Impt. In function
1. function definition
2. function calling

void fun() // function definition

Main ()

Fun(); // function calling

What is call by value and call by reference?

1st we need to know two things

Formal arguments and actual arguments

When we make function “to take something” nature

e.g.

void fun(int a, int b) // this is take something type function

void fun () // this is take nothing type function

void fun() // in the function variable can be two type 1. Ordinary variable 2. Pointer variable

void fun(int a) // this is ordinary variable

void fun (int *a) // this is pointer variable


Formal argument
void fun(int a) // function definition

Main ()

Int x=5;
actual argument
Fun(x); // function calling

Call by value and call by reference in C


There are two ways to pass value or data to function in C language: call by
value and callbyreference. Original value is not modified in call by value but it is modified
in call by reference.

void fun2(int *a) // function definition , pointer variable only for maintain for address

Main ()

Int x=5; 1000


Fun2(&x); // function calling
}

e.g.

understand parameter
to under stand call by value and call by reference we should under stand

actual parameter and formal parameter

Void drop(int x ); // this is function declaration here is x argument and x is parameter this is
formalparameter or formalargument

Void drop(int x);

} Value of a will be copy in to x

Actual parameter will be copy in to formal


Void main () parameter

Int a=100;

Drop (a); // here is a this is actual parameter

/* when we declared function this is parameter called formal parameter and when called
function in program and that time which argument supply that is actual parameter .
Call by value in C
In call by value, original value is not modified.

In call by value, value being passed to the function is locally stored by the function
parameter in stack memory location. If you change the value of function parameter, it is
changed for the current function only. It will not change the value of variable inside the
caller method such as main().

Call by value

Add (a, b);

Add (int x, int y)


X=A // here we are copy value of a in to x and value of b into y

Y=B

A B
10 20
// here value of a and b copy into x and y (a and b is actual argument they
will not change, change will be x and y
10 20

X Y

Let's try to understand the concept of call by value in c language by the example given
below:

In this case value will be two one is have actual and another in formal parameter, after
define actual value actual value never will be change

#include<stdio.h>

#include<conio.h>

void change(int num)

printf("the value adding funciton %d \n " , num);

num=num+100;

printf("add function value %d \n" , num);

}
void main()

int x=100;

clrscr();

printf("Print value of x= %d \n ",x);

change(x); //passing value in function

printf("new value of x %d \n", x);

getch();

Elements of user define function

1. function declaration //as we need variable to define int a;, same as we need to define function
2. function call // where need to apply, we call
3. function definition // here is function code, who function work

Function declaration

1. function type (return type )

when we need to declare function, so 1st we should tell function returned value or not, a function can
be return int, float value, but only return one value,

2. function name

as function task we can take any name of function

3. parameter list (augment )

how much input give to function (formal augment where value will be copy )

4. terminating semicolon

when function close we should give ; to function at the end of program.

Add two no with function


#include<stdio.h>

#include<conio.h>

int add(int, int); //function prototype or function declaration, how many argument we supply and what
is type of argument.

int add( int a, intb); // also type this in function declaration

#include<stdio.h>

#include<conio.h>

int add(int n, int m)

int c;

c=n+m;

return(c);

void main()

int a,b,ans;

clrscr();

printf("ente two number");

scanf("%d%d",&a,&b);

ans=add(a,b); //function calling

printf("%d", ans);

getch();

}
Call by reference in C
In call by reference, original value is modified because we pass reference (address).

Here, address of the value is passed in the function, so actual and formal arguments shares
the same address space. Hence, value changed inside the function, is reflected inside as
well as outside the function.

// we not work on value, we work on variable address


10 20

A b

Add (&a &B) ; // we work on variable address & is address or operator

Add (int *x, int *y) // two variable declare it’s a pointer variable, pointer variable use to store address
or another variable

int a
10
A

3005 // this is address of variable a note:- &a (address of a )

Int *x // we store address variable

X=&a;

if we want see a dress so we need to print it

Printf (“addres of a % u”, x) ;

Ans will be 3005

If we want print value

Printf(“print value a %d, *x);

Ans will be 10

#include<stdio.h>
#include<conio.h>

void main()

int x=10;

printf("\n the address of x is %u", &x);

getch();

#include<stdio.h>

#include<conio.h>

void change(int *num) // * is pointer

printf("printing value of x %d \n" , *num);

(*num)+=100;
printf("after value inside the function %d \n", *num);

printf(“the address of x \n %u” &num);

void main()

int x=100;

clrscr();

printf("i m printting value of x = %d \n", x);

change(&x); // passing reference in function & use use for

printf("printing funciton x = %d \n", x);

getch();

Recursion in C
When function is called within the same function, it is known as recursion in C. The
function which calls the same function, is known as recursive function.

A function that calls itself, and doesn't perform any task after function call, is know as tail
recursion. In tail recursion, we generally call the same function with return statement. An
example of tail recursion is given below.

Let's see a simple example of recursion.

When function call itself it is recursion, we know any function can call to any one function so
any function call it self. To understand is topic we have to should understand memory
concept.

e.g.
1. recursionfunction(){
FUN(3);
REMOVE
2. recursionfunction();//calling
K=6 self function
3. }

1st main function get memory


Main()
{ K k=fun(3);
Int k; Printf(“%d”,k);

K=fun(3); Fun(int a)

Printf(“%d”,k) a 3 if(a==1) a 3 if(a==1)


return (a);
} return (a);
6
s s=a+fun(a-1);
s s=a+fun(a-1); return(s);
Int fun(int a) return(s);
{ Fun(int a)

Int s;
a 2 if(a==1) a 2 if(a==1)
If(a==1) return (a); return (a);
s s=a+fun(a-1);
Return(a); s 3 s=a+fun(a-1);
return(s);
return(s);
S=a+fun(a-1);
Fun(int a)
Return(s);
} a 1 if(a==1) a 1 if(a==1)
return (a); return (a);
s s=a+fun(a-1);
s s=a+fun(a-1);
return(s);
return(s);
#include<stdio.h>

#include<conio.h>

void main()

int k;

k=fun(3);

printf("%d",k);

getch();

int fun(int a)

int s;

if(a==1)

return(a);

s=a+fun(a-1);

return(s);

}
Storage Classes in C
Storage classes are used to define scope and life time of a variable. There are four storage
classes in C programming.

e.g.

int x=5; // dos base c 2 byte, window base 4 byte

4 bytes

Now you can tell tree things

1. X // variable name
2. Size of memory block 4 byte
3. Data type //int

So int x=5; is DS (declaration statement )

But left of three properties data type has some more properties

1. Default value
2. Storage
3. Scope
4. Life

Default value // if we don’t have declare value of variable x;

Then what have x? your answer will be garbage value…

But here value will be garbage or other (who is responsible for that) its also depend on some things

We have to understand it

Storage where get memory ram or cpu (register ) we have two chooses

Scope from where u can access variable

Life :- its not must, that variable life is equal to program life. It can be possible a variable life is less then
program life. Variable make n destroy .
These 4 things I can get to see data type declaration

Int x=5;

Data declaration can be in 4 type

Int x=5;

What is before int, it can be four things,

Auto storage class

Register storage class

Static storage class

External storage class

torage Storage Default Scope Life-time


Classes Place Value

Auto RAM Garbage Limited to the block Within function or till the
Value in which it is execution of the block in
declared (only which it is declared
access in block not (when block end x life is
out side this is end this is life)
scope)

extern RAM Zero Global Till the end of main


program, May be
declared anywhere in
the program

Static RAM Zero Limited to the block Till the end of main
in which it is program, Retains value
declared between multiple
functions call

register Register Garbage Limited to the block Within function or till the
Value in which it is execution of the block in
declared which it is declared

1) auto
The auto keyword is applied to all local variables automatically. It is the default storage
class that is why it is known as automatic variable.

e.g.

#include<stdio.h>

#include<conio.h>

void main()

int x=5;

clrscr();

printf("%d",x);

int x=2;

printf("%d", x);

printf("%d",x);

getch();

In this program value x variable make and destroyed

2nd e.g.

1. #include<stdio.h>
2. int main(){
3. int a=10;
4. auto int b=10;//same like above
5. printf("%d %d",a,b);
6. return 0;
7. }

2) register
The register variable allocates memory in register than RAM. Its size is same of register
size. It has a faster access than other variables.

It is recommended to use register variable only for quick access such as in counter.

Here is defiance only in storage , and storage location is cpu register

e.g.

main()

Register int x=4;

Int y;

Y=x++;

x--;

y=x+5;

In this program x using again and again

1st program come in ram, and program get memory

ram

memory
Cpu
X=5 instruction register
Here x using again n again , and x value again and again going to cup. So cpu is free maximum time.. bcz
value taking distance ram to cpu for information . now we use register before declarer data type

(note:- register int x=5;)

Now in this case cpu store x value into the cpu register. So in this case cpu don’t need to ram for use x.

Overall program speed going to increase. When we use register its means u r using register storage
class.. by the class program gong to boots up..

But some rule there:-

It you r assign data type register.. there is no grantee variable got register. Its depend on free space on
cpu register if there no blank register it will be store in ram location.

Register always use for int and car, for big data type register don’t use,

Register Storage Class :

1. register keyword is used to define local variable.

2. Local variable are stored in register instead of RAM.

3. As variable is stored in register, the Maximum size of variable = Maximum Size of

Register

4. unary operator [&] is not associated with it because Value is not stored in RAM instead

it is stored in Register.

5. This is generally used for faster access.

6. Common use is “Counter“

#include<stdio.h>

#include<conio.h>

void main()

int num1, num2;

register int sum;

printf("\n enter the 1st number");


scanf("%d",&num1);

printf("\n enter the 2nd number");

scanf("%d",&num2);

sum=num1+num2;

printf("ths sum of num1 and num2 %d",sum);

getch();

Why we need Register Variable ?

1. Whenever we declare any variable inside C Program then memory will be randomly

allocated at particular memory location.

2. We have to keep track of that memory location. We need to access value at that memory

location using ampersand operator/Address Operator i.e (&).

3. If we store same variable in the register memory then we can access that memory location

directly without using the Address operator.

4. Register variable will be accessed faster than the normal variable thus increasing the

Summary of register Storage class

Keyword register

Storage Location CPU Register

Initial Value Garbage

Life Local to the block in which variable is declared.

Scope Local to the block.


3) static
The static variable is initialized only once and exists till the end of the program. It retains
its value between multiple functions call.

The static variable has the default value 0 which is provided by compiler.

Variable never destroy upto end of program.

E.g

#include<stdio.h>
#include<conio.h>
void f1();

void main()
{
f1();
f1();
}
void f1()
{
int i=0;

i++;
printf("\n i=%d ",i);
getch();

}
Out put:-

I=1

I=1

E.g 2

#include<stdio.h>
#include<conio.h>
void f1();

void main()
{
f1();
f1();
}
void f1()
{
static int i;

i++;
printf("\n i=%d ",i);

getch();

}
Output
I=1
I=2

External Storage

External ( extern ) storage class in C Programming


1. Variables of this storage class are “Global variables”

2. Global Variables are declared outside the function and are accessible to all

functions in the program

3. Generally , External variables are declared again in the function using keyword

extern

4. In order to Explicit declaration of variable use ‘extern’ keyword

Storage Memory

Scope Global / File Scope

Life time  Exists as long as variable is


running
 Retains value within the function

Default initial Zero


Value

#include<stdio.h>

#include<conio.h>

void main()

int x=5;

clrscr();

printf("%d",x);

int x=2;

printf("%d", x);

}
printf("%d",x);

getch();

Note :

1. Declaration within the function indicates that the function uses external variable

2. Functions belonging to same source code , does not require declaration (no need

to write extern)

3. If variable is defined outside the source code , then declaration using extern

keyword is required

C Array
Array in C language is a collection or group of elements (data). All the elements of c array
are homogeneous (similar). It has contiguous memory location.

C array is beneficial if you have to store similar elements. Suppose you have to store marks
of 50 students, one way to do this is allotting 50 variables. So it will be typical and hard to
manage. For example we can not access the value of these variables with only 1 or 2 lines
of code.

Another way to do this is array. By using array, we can access the elements easily. Only few
lines of code is required to access the elements of array.

Advantage of C Array

1) Code Optimization: Less code to the access the data.

2) Easy to traverse data: By using the for loop, we can retrieve the elements of an array
easily.

3) Easy to sort data: To sort the elements of array, we need a few lines of code only.

4) Random Access: We can access any element randomly using the array
Disadvantage of C Array

1) Fixed Size: Whatever size, we define at the time of declaration of array, we can't
exceed the limit. So, it doesn't grow the size dynamically like LinkedList which we will learn
later.

Int a[6]; //signaldimension array // group of variables

0 1 2 3 4 5

code of single array sum

#include<stdio.h>

#include<conio.h>

void main()

int a[3],i,sum=0;

clrscr();

printf("enter three no:-");

for(i=0;i<=2;i++)

scanf("%d",&a[i]);

for(i=0;i<=2;i++)

sum=sum+a[i];

printf("ths sum or 3 number %d", sum);

getch();

Code array even or odd find out

#include<stdio.h>

#include<conio.h>
void main()

int array[100],i,num;

clrscr();

printf("enter the size of n array \n");

scanf("%d",&num);

printf("enter the element of array \n");

for (i=0; i<num; i++)

scanf("%d", &array[i]);

printf("even numner in the array are:=");

for(i=0; i<num; i++)

if(array[i]%2==0)

printf("%d \t",array[i]);

printf("\n odd number in tha array:=");

for(i=0; i<num; i++)

if(array[i] % 2 !=0)

printf("%d \t ", array[i]);

getch();

}
int b[2][3]; // two dimension array // 2 * 3 =6 still this is 6 variable // array of arrays

int c[2][3][4]// three dimension array

0 1

0 1 2 0 1 2

0
0 1 2

1
0 1 2

#include<stdio.h>

#include<conio.h>

void main()

int a[3][3] ,b[3][3], c[3][3],i,j;

clrscr();

printf ("enter a number for first metix");

for(i=0;i<=2;i++)

for(j=0;j<=2;j++)

scanf("%d",&a[i][j]);

printf("enter a number for second metrix");

for(i=0;i<=2;i++)

for(j=0;j<=2;j++)
scanf("%d",&b[i][j]);

for(i=0;i<=2;i++)

for(j=0;j<=2;j++)

c[i][j]=a[i][j] + b[i][j];

printf("%d",c[i][j]);

printf("\n");

getch();

Find out big no in program

#include<stdio.h>

#include<conio.h>

void main()

int i,maxi=0, mark[5];

int sn=1;

clrscr();

for(i=0;i<5;i++)

printf("\n studnet no. %d", sn++);

scanf("%d",&mark[i]);

for (i=0;i<5;i++)
{

if(mark[i]>maxi)

maxi=mark[i];

printf("\n maximun maris of studnt is %d \n ", maxi);

getch();

C language passing array to function


#include<stdio.h>

#include<conio.h>

void main()

int i,a[10];

input (a);

for(i=0;i<=9;i++)

printf("%d",a[i]);

getch();

input(int b[])

int i;

clrscr();

printf("enter the 10 number");

for(i=0;i<=9;i++)

scanf("%d",&b[i]);

}
return 0;

C Pointers
The pointer in C language is a variable, it is also known as locator or indicator that points
to an address of a value.

Advantage of pointer
1) Pointer reduces the code and improves the performance, it is used to retrieving
strings, trees etc. and used with arrays, structures and functions.

2) We can return multiple values from function using pointer.

3) It makes you able to access any memory location in the computer's memory.

Usage of pointer
There are many usage of pointers in c language.

1) Dynamic memory allocation

In c language, we can dynamically allocate memory using malloc() and calloc() functions
where pointer is used.
2) Arrays, Functions and Structures

Pointers in c language are widely used in arrays, functions and structures. It reduces the
code and improves the performance.

Symbols used in pointer


Symbol Name Description

& (ampersand sign) address of operator determines the address of a variable.

* (asterisk sign) indirection operator accesses the value at the address.

Pointer is a variable which holds the address of another variables.

Int x=10;

X 10 1000 (address)

Value

#include<stdio.h>

#include<conio.h>

void main()

int number=50;

int *p;

clrscr();

p=&number;

printf("address of p variable is %x \n",p);

printf("value of p variable is %d \n", *p);


getch();

& this is address of operator

* indirection of operator

Pointer Program to swap 2 numbers without using


3rd variable
#include<stdio.h>

#include<conio.h>

void main()

int a=10,b=20,*p1=&a, *p2=&b;

clrscr();

printf("before swap *p1=%d *p2=%d", *p1,*p2);

*p1=*p1 + *p2;

*p2=*p1 - *p2;

*p1=*p1-*p2;

printf("\n after wap *p1=%d *p2%d", *p1,*p2);

getch();

Pointer Arithmetic in C
In C pointer holds address of a value, so there can be arithmetic operations on the pointer
variable. Following arithmetic operations are possible on pointer in C language:
o Increment
o Decrement
o Addition
o Subtraction
o Comparison

Incrementing Pointer in C
Incrementing a pointer is used in array because it is contiguous memory location. Moreover,
we know the value of next location.

Increment operation depends on the data type of the pointer variable. The formula of
incrementing pointer is given below:

ew_address= current_address + i * size_of(data type)

2 bit

For 32 bit int variable, it will increment to 2 byte.

64 bit

For 64 bit int variable, it will increment to 4 byte.

Let's see the example of incrementing pointer variable on 64 bit OS.

Increment or decrement on pointer

Pointer hold address of another variable. We use increment or decrement for pointer when we access
array or which is constitute memory location for e.g

Int var [5];

0 1 2 3 4

12 23 35 46 23
2156 2158 2160 2162 2164
Int will be take 2 byte gape

Float will be take 4 byte gape

Char will be take 1 bye gape

Increment or decrement
++ /--

Int no=100;

Int *p;

P=&no; note:- e.g. no address is 2256

P++ (2258, 2260, 2262)

p- - (2256, 2254, 2252)

we use for access array

#include<stdio.h>

#include<conio.h>

void main()

int a[]={10,20,30,40},i;

234566 234568 234570 234572


10 20 30 40
A[0] A[1] A[[2] A[3]

int *p; // int *p=a; or int*p=&a[0];

clrscr();

p=&a[0]; //p=a;

printf("output vai pointer \n");

printf("address \t value");
for(i=0; i<4;i++)

printf("\n %u", p);

printf("\n %d", *p);

p++; // increment of address or p=p+1;

getch();

Sum of Two Numbers Using Pointers in


c Programming

#include <stdio.h>

#include <conio.h>

void main()

int a,b,c,*p1,*p2,*p3;

printf("enter two number");

scanf("%d%d",&a,&b);

p1=&a;

p2=&b;

p3=&c;

*p3=(*p1)+(*p2); // option can access value of address in the program

// *p1 is access value a

// *p2 is access value of b

printf("\n sum =%d",c);


getch();

#include<stdio.h>

#include<conio.h>

void main()

float *p; // this is sma

clrscr();

p=(float*)malloc(4); // this is dma // malloc always has function type is void don’t int and flot//
malloc return address which blog malloc make// in malloc we can only pass one argument // *p hold
the address of malloc(4) // malloc(4) hold always garbage value.

*p=3.5;

printf("%u",p);

printf("%f",*p);

getch();

C Strings
String in C language is an array of characters that is terminated by \0 (null character).

There are two ways to declare string in c language.

1. By char array
2. By string literal

Let's see the example of declaring string by char array in C language.

. sequence of characters terminated at null character.

. ASCII code of null character is 0(zero)

e.g.

#include<stdio.h>
#include<conio.h>

void main()

char s[10]={'s','u','r','a','j','\0'};

int i;

clrscr();

for(i=0;i<=6;i++)

printf("%c",s[i]);

getch();

E.g 2
#include<stdio.h>

#include<conio.h>

void main()

char s[10]={'s','u','r','a','j','\0'};

int i;

clrscr();

for(i=0;s[i]!='\0';i++)

printf("%c",s[i]);

getch();

e.g. 3
#include<stdio.h>
#include<conio.h>

void main()

char s[10]={'s','u','r','a','j','\0'};

int i;

clrscr();

/*

for(i=0;s[i]!='\0';i++)

printf("%c",s[i]); */

printf("%s",s);

getch();

e.g. 4
#include<stdio.h>

#include<conio.h>

void main()

char s[10]={'s','u','r','a','j','\0'};

int i;

clrscr();

/*

for(i=0;s[i]!='\0';i++)

printf("%c",s[i]);

printf("%s",s); */

puts(s);
getch();

String manipulation

Write a program to calculate length of the string

- Without using predefined function


- With using predefined function

e.g. 5

#include<stdio.h>

#include<conio.h>

void main()

char s[20];

int i;

clrscr();

printf("enter the string");

gets(s); // &s[0] gets is predefine function

for(i=0;s[i]!='\0';i++)

printf("%d",i);

getch();

e.g.6

#include<stdio.h>

#include<conio.h>
#include<string.h>

void main()

char s[20];

int i;

clrscr();

printf("enter the string");

gets(s); // s==&s[0] gets is predefine function

i=strlen(s);

printf("%d",i);

getch();

e.g. 7

#include<stdio.h>

#include<conio.h>

void main()

char s[20];

clrscr();

printf("enter your name");

scanf("%s",&s[0]);

puts(&s[0]); //puts(s);

getch();

e.g. 8

#include<stdio.h>

#include<conio.h>
void main()

char s[20];

clrscr();

printf("enter your name");

//scanf("%s",&s[0]); //scanf("s",s) //scanf can not print multi word, scanf take delimited as space,
tab , enter

gets(s); // gets get print multi input

puts(&s[0]); //puts(s);

getch();

e.g.9

#include<stdio.h>

#include<conio.h>

#include<string.h>

void main()

char s[20];

printf("enter a string");

gets(s); // gets(&s[0]);

strrev(s);

printf("%s",s);

getch();

}
e.g.10

#include<stdio.h>

#include<conio.h>

#include<string.h>

void main()

char s[20];

printf("enter a string");

gets(s); // gets(&s[0]);

strupr(s);

printf("%s",s);

getch();

e.g.11

#include<stdio.h>

#include<conio.h>

#include<string.h>

void main()

char s[20];

printf("enter a string");

gets(s); // gets(&s[0]);

strlwr(s);

printf("%s",s);

getch();
}

e.g. 12

#include<stdio.h>

#include<conio.h>

#include<string.h>

void main()

char s[20];

char target[25];

printf("enter a string");

gets(s); // gets(&s[0]);

strcpy(target,s);

printf("%s",s);

printf("%s",target);

getch();

e.g. 13

#include<stdio.h>

#include<conio.h>

#include<string.h>

void main()

char str1[10] ="RAMA";


char str2[10] ="Arma";

int n;

clrscr();

n=stricmp(str1, str2);

printf("\n %d ",n);

getch();

e.g. 14

#include<stdio.h>

#include<conio.h>

#include<string.h>

void main()

int n;

char str[20]="ram";

char str1[10]="RAM";

clrscr();

n=strcmpi (str,str1);

printf("\n %d",n);

getch();
}

e.g.15

#include<stdio.h>

#include<conio.h>

#include<string.h>

void main()

int n;

char str[20]="ramsingh";

char str1[10]="ramsangela";

clrscr();

n=strncmp(str,str1,4);

printf("\n %d",n);

getch();

e.g. 16

#include<stdio.h>

#include<conio.h>

#include<string.h>

void main()

char str1[20],str2[20];

printf("enter 1st string");

gets(str1);

printf("enter 2nd string");


gets(str2);

if(strcmp(str1,str2)==0)

printf("\nstring are equal");

else

printf("\string not =");

getch();

File Handling in C
File Handling in c language is used to open, read, write, search or close file. It is used for
permanent storage.

Advantage of File
It will contain the data even after program exit. Normally we use variable or array to store
data, but data is lost after program exit. Variables and arrays are non-permanent storage
medium whereas file is permanent storage medium.

Functions for file handling


There are many functions in C library to open, read, write, search and close file. A list of file
functions are given below:

No. Function Description


1 fopen() opens new or existing file

2 fprintf() write data into file

3 fscanf() reads data from file

4 fputc() writes a character into file

5 fgetc() reads a character from file

6 fclose() closes the file

7 fseek() sets the file pointer to given position

8 fputw() writes an integer to file

9 fgetw() reads an integer from file

10 ftell() returns current position

11 rewind() sets the file pointer to the beginning of the file

next →← prev

File Handling in C
File Handling in c language is used to open, read, write, search or close file. It is
used for permanent storage.

Advantage of File
It will contain the data even after program exit. Normally we use variable or array to
store data, but data is lost after program exit. Variables and arrays are non-permanent
storage medium whereas file is permanent storage medium.

Functions for file handling


There are many functions in C library to open, read, write, search and close file. A list of
file functions are given below:

No. Function Description

1 fopen() opens new or existing file

2 fprintf() write data into file

3 fscanf() reads data from file

4 fputc() writes a character into file

5 fgetc() reads a character from file

6 fclose() closes the file

7 fseek() sets the file pointer to given position

8 fputw() writes an integer to file

9 fgetw() reads an integer from file

10 ftell() returns current position

11 rewind() sets the file pointer to the beginning of the file


Opening File: fopen()
The fopen() function is used to open a file. The syntax of fopen() function is given below:

1. FILE *fopen( const char * filename, const char * mode );

You can use one of the following modes in the fopen() function.

Mode Description

R opens a text file in read mode

W opens a text file in write mode

A opens a text file in append mode

r+ opens a text file in read and write mode

w+ opens a text file in read and write mode

a+ opens a text file in read and write mode

Rb opens a binary file in read mode

Wb opens a binary file in write mode

Ab opens a binary file in append mode

rb+ opens a binary file in read and write mode

wb+ opens a binary file in read and write mode


ab+ opens a binary file in read and write mode

Why file handling

1. Date
2. Data persistence
3. Files
4. File handling

1. Put data into file and take out data from file that is file handling.
2. Write something into file and stract date in to variable.

Ram

Memory for the program

HDD

. file is a structure

Typedefstruct

Short level;

Unsigned flags;

Char fd;

Unsigned char hold;

Short bsize;

Unsigned char *butter;


Unsigned char *curp;

Unsigned istemp;

Short token;

} FILE;

e.g. 1

#include <stdio.h>

#include<conio.h>

vodi main(){

FILE *fp;

fp = fopen("file1.txt", "w");//opening file

fputc('a',fp);//writing single character into file

fclose(fp);//closing file

getch();

e.g. 2

C fputs() and fgets()


The fputs() and fgets() in C programming are used to write and read string from stream.
Let's see examples of writing and reading file using fgets() and fgets() functions.

#include<stdio.h>

#include<conio.h>

void main(){

FILE *fp;

clrscr();
fp=fopen("myfile2.txt","w");

fputs("hello c programming",fp);

fclose(fp);

getch();

e.g.3
Reading File : fgets() function
The fgets() function reads a line of characters from file. It gets string from a stream.

#include<stdio.h>

#include<conio.h>

void main(){

FILE *fp;

char text[300];

clrscr();

fp=fopen("myfile22.txt","r");

printf("%s",fgets(text,200,fp));

fclose(fp);

getch();

e.g.4.

e.g.
#include <stdio.h>

#include<conio.h>

void main()

FILE *fptr;

int id;

char name[30];

float salary;

fptr = fopen("nainae.txte", "w");/* open for writing */

if (fptr == NULL)

printf("File does not exists \n");

return;

printf("Enter the id\n");

scanf("%d", &id);

fprintf(fptr, "Id= %d\n", id);

printf("Enter the name \n");

scanf("%s", name);

fprintf(fptr, "Name= %s\n", name);

printf("Enter the salary\n");

scanf("%f", &salary);

fprintf(fptr, "Salary= %.2f\n", salary);

fclose(fptr);

getch();

}
Reading File : fgetc() function
The fgetc() function returns a single character from the file. It gets a character from the stream. It returns
EOF at the end of file

#include<stdio.h>

#include<conio.h>

#include<stdlib.h>

void main()

FILE *fp;

char ch;

clrscr();

fp=fopen("data2.txt","r");

if(fp==NULL)

printf("\n error in file open");

exit(0);

printf("\n file contents \n");

while((ch=fgetc(fp))!=EOF)//fgetc its work read char from file

//EOF end of file cf

printf("%c",ch);

fclose(fp);

getch();

}
C fseek() function
The fseek() function is used to set the file pointer to the specified offset. It is used to write data into file at
desired location.

Вам также может понравиться