National Business College: A Study Material For C' Programming According To Syllabus
National Business College: A Study Material For C' Programming According To Syllabus
National Business College: A Study Material For C' Programming According To Syllabus
According to syllabus
of
Developed for
IT Department (B.C.A)
Pankaj kumar
(Director)
3
National Business college.
Disclaimer
Author has obtained all the information contained in this
book from the resources believed to be reliable and true.
However, Author don’t take any responsibility for the
absolute accuracy or completeness of any information, and
the damage and loss suffered thereupon.
Any distribution (either commercial or noncommercial) of
this book should not be done without taking permission from
the author.
Author detail
Akash Dalmia
B.C.A
National Business College
BATCH 2016-19
Patna (Bihar)
Contact no:-7277993404
E-mail id-infoakashdalmia@gmail.com
4
National Business college.
A Programming
book For
B.C.A
Assigned for students of
National Business College
Acknowledgement
5
National Business college.
Contents
Introduction to c
Tokens
Operators
Decision making
if Statement
if…else Statement
if...else if...else Statement
switch Statement
Function
Parameter Argument
Recursion
Call by reference
Jump control
Storage class
String
Array
Pointer
Array of pointer
Double dimension array & pointer
Pointer to pointer
Dynamic memory location
Structure
Structure initialization
Array of structure
Enum(enumeration)
File handling
Command line argument
Block Input Output
6
National Business college.
1. Introduction to C
C is a general-purpose, high-level language that was originally developed by Dennis M.
Ritchie to develop the UNIX operating system at Bell Labs. C was originally first
implemented on the DEC PDP-11 computer in 1972.
In 1978, Brian Kernighan and Dennis Ritchie produced the first publicly available
description of C, now known as the K&R standard.
The UNIX operating system, the C compiler, and essentially all UNIX application
programs have been written in C. C has now become a widely used professional
language for various reasons:
⇒ Easy to learn.
⇒ Structured language.
⇒ It produces efficient programs.
⇒ It can handle low-level activities.
⇒ It can be compiled on a variety of computer platforms.
Facts about C
⇒ C was invented to write an operating system called UNIX.
⇒ C is a successor of B language which was introduced around the early 1970s.
Why To Use C?
C was initially used for system development work, particularly the programs that make-
up the operating system. C was adopted as a system development language because it
produces code that runs nearly as fast as the code written in assembly language. Some
examples of the use of C might be:
⇒ Operating Systems
7
National Business college.
1.Graphical character.
2.Non graphical character.
1. Graphical character:- Those character’s which are displayed on screen are called
graphical characters.
(1.) A To Z & a To z.
(2.) 0 To 9 digits.
(3.) Special character’s (+,-,#,<,> e.t.c).
2. Non graphical character:- Those character’s which are not displayed on screen are
called non graphical character.
Note :- The character’s which are represented with \ are called escape sequences
8
National Business college.
TOKENS
Tokens in C
A C program consists of various tokens and a token is either, a keyword, an identifier, a
constant, a string literal, or a symbol. For example, the following C statement consists
of five tokens:
printf("Hello, World! \n");
The individual tokens are:
printf ( "Hello, World! \n");
Semicolons
In a C program, the semicolon is a statement terminator. That is, each individual
statement must be ended with a semicolon. It indicates the end of one logical entity.
Given below are two different statements:
printf("Hello, World! \n");
Comments in c
Comments are like helping text in your C program and they are ignored by the
compiler. They start with /* and terminate with the characters */ as shown below:
2.Variable :- It represents memory location in which value is stored .it can vary its
value therefore it s called variable.
9
National Business college.
Note :-
Compiler :- It is a software used to transfer c language coding to machine level
language .
3.Constant :- Values or data which can be stored in a variable and is used in a variable
and is used in processing, it cannot change its value so it is called constant. Example :-
20,30,’a’,”ram” e.t.c.
2.Integer Constant :- The number in which decimal point is not available called
integer constant.
Ex. :- 25,45,89,67 etc.
Non Numeric Constant:- The Data which is not used in arithmetical operation is called
non numeric data or constant
Ex. :- ‘a’,’b’,’c’ etc.
10
National Business college.
(i) Assignment operator (=):- This operator is used assingn value into variable
Ex.:- a=30,d=7 etc.
(ii) Arithmetic operators:- These operator perform arithmetical operaton.
Ex.:- a=12%3
Note:- (%) is used for remainder in c.
(iii) Arithmetic Assignment operators:- This operators performs both Arithmetic &
Assignment together.
Ex.:- +-,-=, a=a-10
(iv) Increment & decrement operator(++,--):-
ii. Inprefix :- In it operator is written after its operants and operation is performed at
last in expression these are called post-increment & post- decrement ex. a++
Printf () :- This function is used to for outputting different types of data on screen
Printf(“format specifier”,variable);
11
National Business college.
Syntax:-
#include<stdio.h>
Void main()
{
Printf(“Ram”);
}
Scanf() :- This function is used to input different types of data from the keyboard.
Scanf(“format specifier”,&variable);
Syntax:-
#include<stdio.h>
Void main()
{
int n;
scanf(“%d”,&n);
}
Logical operator =Logical operators are used for logical operations in it &&(and)
and || (or) operators are used to combine more than one relational operator’s !(NOT)
but not operator is used to reverse logical value of a combination a>b &&a>c
&&(And) operators = In it all conditions are true then resultant is true otherwise false.
|| (or) = In it all conditions are false then resultant is false otherwise true.
12
National Business college.
2.Decision Making:-
Decision control :- In this statement computer makes decision that weather statement
are executed or not according to condition
If() :-In this condition if the statement under it is true then it executes otherwise not
{
/* statement(s) will execute if the boolean expression is true */
}
If the Boolean expression evaluates to true, then the block of code inside the ‘if’
statement will be executed. If the Boolean expression evaluates to false, then the first
set of code after the end of the ‘if’ statement (after the closing curly brace) will be
executed.
C programming language assumes any non-zero and non-null values as true and if it is
either zero or null, then it is assumed as false value.
Syntax
If(condition)
Or
If(cond…)
{……………
……………
Statement..;
}
Examle:- write a program to print pass if marks is greater than 50.
Soln :-
#include<stdio.h>
Void main()
{
int n;
printf(“Enter marks”);
scanf(“%d”,&n);
if(n>50)
printf(“pass”);
}
Examle :- Input marks of 3 subject and find average if average is greater than 70
13
National Business college.
print A+.
Soln :-
#include<stdio.h>
void main()
{
int a,b,c,d,e;
printf("Enter the marks of three subject");
scanf("%d%d%d",&a,&b,&c);
d=a+b+c;
e=d/3;
printf(“Average %d”,e);
if(d>70)
printf("A+");
}
14
National Business college.
if…else Statement:-
This statement is used to execute statement according to specified condition it means if
the condition of if statement is true then it executes statement under it otherwise else
statement executes.
Syntax
The syntax of an if...else statement in C programming language is:
If (condition)
{……………
……………
}
else
{………….
………….
}
Example :- write a program to printf pass if marks is greater than 35 else fail.
Soln :-
#include<stdio.h>
Void main()
{
Int n;
Printf(“Enter the marks “);
Scanf(“%d”,&n);
If(n>35)
{
Printf(“pass”);
}
else
{
Printf(“fail”);
}
Do it with yourself:-
(i) Input price of shirt and calculate discount if price is greater than
1000 Then discount will be 40% otherwise 30%.
(ii) Input two numbers if 1st number is greater then calculate
subtraction otherwise addition.
(iii) input three numbers and calculate average if average is between
50 to 100 then print very good otherwise bad.
15
National Business college.
Flow chart :-
⇒ An if can have zero to many else if's and they must come before the else.
Once an else if succeeds, none of the remaining else if's or else's will be tested.
Syntax:-
If(condtion)
{………………
……………….
}
else if(condition)
{………………
……………….
}
else if(conditon)
{…………
…………
}
else
16
National Business college.
{………….
…………..
}
Example:-
#include<stdio.h>
#include<conio.h>
void main()
{
int n;
clrscr();
printf("Enter marks");
scanf("%d",&n);
if(n>=80)
printf("Grade A");
else if(n>=60)
printf("Grade B");
else if(n>50)
printf("Grade c");
else
printf(" grade D");
getch();
}
Do it with yourself.
(i.) input basic salary and calculate grows salary.
Formulae.=BS+TA+DA
If bs>=15,000 then TA=20% &DA=60%
If bs<10,000 then TA=15% &DA=70%
Otherwise
TA=14%
DA=80%
(ii.) input value of electricity unit and calculate electricity bill according to
following:- unit<=200 fix price=500
Unit>=500 5rs.per/unit
Otherwise 6rs.per/unit
17
National Business college.
Nested if Statements :-
It is always legal in C programming to nest if-else statements, which means you can use
one if or else if statement inside another if or else if statement(s).
Syntax
The syntax for a nested if statement is as follows:
If(condition)
{……………..
…………….
If(condition)
{……………
…………..}
Example:-
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c;
printf("Enter marks of three subject");
scanf("%d%d%d",&a,&b,&c);
if(a>=50)
{
if(b>=50)
{
if(c>=50)
{
printf("pass");
}
}
}
else
printf("fail");
getch();
}
18
National Business college.
Switch Statement:-
A switch statement is used for option based or menu based programming in which more
than one options are given according to option selection specified operation performed
in it switch case statement is used.
Syntax
The syntax for a switch statement in C programming language is as follows:
The following rules apply to a switch statement:
⇒ The expression used in a switch statement must have an integral or enumerated
type, or be of a class type in which the class has a single conversion function to
an integral or enumerated type.
⇒ You can have any number of case statements within a switch. Each case is
followed by the value to be compared to and a colon.
⇒ The constant-expression for a case must be the same data type as the variable
in the switch, and it must be a constant or a literal.
⇒ When the variable being switched on is equal to a case, the statements following
that case will execute until a break statement is reached.
⇒ When a break statement is reached, the switch terminates, and the flow of
control jumps to the next line following the switch statement.
⇒ Not every case needs to contain a break. If no break appears, the flow of
control will fall through to subsequent cases until a break is reached.
⇒ A switch statement can have an optional default case, which must appear at the
end of the switch. The default case can be used for performing a task when none
of the cases is true. No break is needed in the default case.
Flow Diagram
19
National Business college.
20
National Business college.
Example :-
#include<stdio.h>
void main()
{
int a,b,c;
clrscr();
printf("Enter 2 no.");
scanf("%d%d",&a,&b);
printf("1:for additon\n2: subtraction");
scanf("%d",&c);
switch(c)
{
case 1:
a=a+b;
printf("Addition:--%d",a);
break;
case 2:
a=a-b;
printf("%d",a);
break;
default : printf("wrong input");
}
}
Do it with yourself
(i) Input no. and calculate area and circumference using switch case.
(ii) Input no and calculate 40% and 30% print using switch.
(iii) Input 3 no. and calculate multiplication, subtraction and addition using
switch case.
(iv) Write a program to print sum of even and odd no. less than the input no. using
switch case.
(v) Define switch statement? Why is it used?
21
National Business college.
3.Loop.
Loop Control :- In it statements are executed again & again repeatedly many times.
A loop statement allows us to execute a statement or group of statements multiple
times. Given below is the general form of a loop statement in most of the programming
languages:
According to condition :-
It is classified into 3 categories.
(i) for()
(ii) while()
(iii) do-while
for():- This statement executes for a number of times according to specified condition.
It accepts three parameter.
i. Initialization
ii. Condition
iii. Looping steps
Here is the flow of control in a ‘for’ loop:
i. The init step is executed first, and only once. This step allows you to declare and
initialize any loop control variables. You are not required to put a statement here, as
long as a semicolon appears.
ii. Next, the condition is evaluated. If it is true, the body of the loop is executed. If it
is false, the body of the loop does not execute and the flow of control jumps to the
next statement just after the ‘for’ loop.
iii. After the body of the ‘for’ loop executes, the flow of control jumps back up to the
increment statement. This statement allows you to update any loop control variables.
This statement can be left blank, as long as a semicolon appears after the condition.
Syntax:-
For(initialization,cond,steps)
{……………………….
……………………….
Statements;
…..…………………..
}
Example :-
#include<stdio.h>
Void main()
{
Int n,i;
22
National Business college.
Printf(“Enter a no.”);
Scanf(“%d”,&n);
for(i=1;i<=n;i++)
{
Printf(“%d,”,i);
}
}
Example :- write a program to sort elements in ascending order using bubble sort.
#include<stdio.h>
void main()
{
int no[5],i,j,t;
printf("input 5 No.");
for(i=0;i<5;i++)
scanf("%d",&no[i]);
for(i=0;i<5;i++)
{
for(j=0;j<5-1;j++)
if(no[j]>no[j+1])
{
t=no[j];
no[j]=no[j+1];
no[j+1]=t;
}
}
23
National Business college.
for(j=0;j<5;j++)
printf("%d,",no[j]);
}
1. input no. and print even no. less than the inputed no.
2. input no. and print odd no. equal to the inputed no.
3. input no. and printf sum of odd no less than the inputed no.
4. print x,x/2,x/3,x/4…….x/n.
5. print x,x/3,x/5,x/7…….x/n.
6. print x+x/3+x/5+x/7…….x/n.
7. print 1+2+3+4……….n.
8. print 1/x,2/x,3/x,4/x……..n/x.
9. write a program to print ram 10 times.
10. write a program to print factorial of the given no.
24
National Business college.
While() :- This statement is also used for looping in it statements are executed
Again and again until the termination condition of while statement is
Made
Syntax :-
While(condition)
{…………………
…………………
Statements;
………………….
}
Example :-
#include<stdio.h>
void main()
{
int n=1;
clrscr();
while(n<=10)
{
printf(",Ram");
n++;
}
}
Example :- write a program to reverse its digits.
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c=0;
printf("Enter no:");
scanf("%d",&a);
while(a>0)
{
b=a%10;
c=(c*10)+b;
a=a/10;
}
printf("%d",c);
getch();
}
25
National Business college.
26
National Business college.
do..while():- This statement is used for lopping it works same as while but difference is
that it checks the condition at the end of the loop body so either condition is true or
false it executes at least once.
It is guaranteed to execute at least one time.
Syntax :-
do..while():---
do{…………..
…...……...
...………...
Statement;
..………….
}while(cond);
Example:-
#include<stdio.h>
void main()
{
int a=1,n;
clrscr();
printf("Enter the no.");
scanf("%d",&n);
do{
printf("Deepak ");
a++;
}while(a<=n);
}
Nested loop:- In it one loop statement is defined under another loop statement.
2. Nested for():- In it one for statement is defined under it.
Syntax:-
For(initialization;condition;steps)
{………………………………….
For(initialization;condition;steps)
{………………………………
Statements;…………………
………………………………
}
}
27
National Business college.
Example :- print 1
22
333
4444
#include<stdio.h>
void main()
{
int i,j;
for(i=1;i<=4;i++)
{
for(j=i;j>=1;j--)
{
printf("%d",i);
}printf("\n");
}
}
Example.:- print *
* *
* * *
****
*****
****
* * *
* *
*
#include<stdio.h>
void main()
{
int i,j;
for(i=1;i<=5;i++)
{
for(j=i;j>=1;j--)
{
printf("* ");
}printf("\n");
}
for(i=4;i>=1;i--)
{
for(j=i;j>=1;j--)
{
printf("* ");
28
National Business college.
}printf("\n");
}
}
Example:- print 5
45
345
2345
1 2345
#include<stdio.h>
void main()
{
int i,j;
clrscr();
for(i=5;i>=1;i--)
{
for(j=i;j<=5;j++)
{
printf("%d ",j);
}printf("\n");
}
}
Do it with yourself
i. print * * * * *
* * * *
* * *
* *
*
* *
* * *
* * * *
* * * * *
ii. print @
@@@
@@@@@
@@@@@@@
29
National Business college.
III. printf 1 2 3 4
1 2 3
1 2
1
30
National Business college.
iv. print 1 2 3 4 3 2 1
1 2 321
1 21
1
3.Function
Function Name: This is the actual name of the function. The function name and
the parameter list together constitute the function signature.
Parameters: A parameter is like a placeholder. When a function is invoked, you
pass a value to the parameter. This value is referred to as actual parameter or
argument. The parameter list refers to the type, order, and number of the
parameters of a function. Parameters are optional; that is, a function may contain
no parameters.
Advantage of function :-
i. program complexity is reduced.
ii. using function we can divide our program into smaller unit.
iii. Using function program is solved quickly
Reusability of code :- Through function we can create codes once we can use it again&
again without rewriting it.
31
National Business college.
Types of function:-
Function is classified into 2 types.
i. library (inbuilt) function.
ii. User defined function
i. library (inbuilt) function:- Those function which are available with
compiler to help users for their application are called library function.
Ex.. printf(),scanf()etc.
ii. User defined function :- Those function which are created by the user for
their own purpose are called User defined function.
Creation of function :- A function is created by using following three
steps.
(i.) Function declaration
(ii.) Function calling
(iii.) Function definition
Function declaration :- At first function is declared with its name parameter with return
time
Syntax:-
Return –type-f-name(parameter)
i. Function calling :- in this step function is called by its name
and Required parameter.
Syntax:-f-
name(parameter)
sum(2,3);
sum(a,b);
ii. function definition :- in this step a function is defined with
its operation to perform specific task.
Syntax:-
Return-type f-name(parameter)
{…………………
………………….
Statement;……..
………………….
}
Example :-
#include<stdio.h>
void main()
{ int n, s, m;
int sum(int n,int m);
printf("Enter 2 no.");
scanf("%d%d",&n,&m);
32
National Business college.
s=sum(m,n);
printf("Sum:- %d",s);
}
int sum(int n,int m)
{
int s;
s=n+m;
return(s);
}
Example:- write a program to find area of circle.
#include<stdio.h>
void main()
{
float n,s;
float area(int);
printf("Enter the radius to find area:-");
scanf("%f",&n);
s=area(n);
printf("%3f",s);
}
float area(int r)
{
float b;
b=3.14*r*r;
return(b);
}
⇒ Different operational modes of function:-(i)Function
that accepts parameter and return a value As shown
in the solved example:-#include<stdio.h>
#include<conio.h>
void main()
{
float n,s;
clrscr();
float square(int);
printf("Enter the side to find area of square:-");
scanf("%f",&n);
s=square(n);
printf("%3f",s);
getch();
}
33
National Business college.
float square(int s)
{
float b;
b=s*s;
return(b);
}
(ii.) Function which accepts parameter and does not return value.
#include<stdio.h>
#include<conio.h>
void main()
{
int n;
void even(int);
printf("Enter the no. to print no. series: ");
scanf("%d",&n);
even(n);
getch();
}
void even(int b)
{
int i;
for(i=2;i<=b;i++)
printf("%d,",i);
}
(iii.)Function which does not accepts parameter and does not return value.
#include<stdio.h>
#include<conio.h>
void main()
{
void series();
series();
getch();
34
National Business college.
}
void series()
{
int i;
for(i=0;i<10;i++)
printf("%d,",i);
}
35
National Business college.
Function Argument:-
Parameter(Argument):-The value or variable which is passed in a function is
called parameter or (argument).
It is classified into two categories.
(i.) Formal Parameter.
(ii.) Actual Parameter.
36
National Business college.
Example:-
#include<stdio.h>
void main()
{
int a,c;
int add(int *);
printf("Enter the no.");
scanf("%d",&a);
c=add(&a);
printf("\n%d",c);
}
int add(int *a)
{
int c;
c=*a+10;
return(c);
}
Jump control
⇒ Jump statement are used to jump from one location to another in a program
These are following :-
(i.) break;
(ii.) continue;
(iii.) goto;
i. break :-This statement is used to jump from one location to another
location in a program.
Syntax:- break;
Note :- it is also used in switch case statement to break a case.
Example :-
#include<conio.h>
void main()
{
int i,j,n,d;
printf("Enter the no.");
scanf("%d",&n);
printf("Enter the no. to break the loop");
scanf("%d",&d);
for(i=0;i<n;i++)
{
If(i==d)
37
National Business college.
{
break;
}
printf("%d",i);
}
}
#include<conio.h>
#include<stdio.h>
void main()
{
int i,j,n;
printf("Enter the no.");
scanf("%d",&n);
for(i=0;i<n;i++)
{
if(i==5)
{
continue;
}
printf("%d",i);
}
getch();
}
#include<stdio.h>
void main()
{
int i=1,n;
printf("Enter the no.");
scanf("%d",&n);
38
National Business college.
start:
printf("%d,",i);
if(i<n)
{
i++;
goto start;
}
}
Do it with yourself:-
(i.) write a program to print Ram 10 times.
(ii.) Write a program to print odd no. from 1 to 10.
(iii.) Write a program to print even no. from 1 to 10.
39
National Business college.
4.Storage Class
Storage Class :-
It represents 4 properties.
Every variable has its certain properties these properties are dependent on storage class.
Properties are as fallows:-
(i.) storage –ram & register
(ii.) default initial value :- either garbage or 0 within the block or outside the
block.
(iii.) Scope.
(iv.) Life – Temporary or permanent.
i. Auto :- By default every variable is automatic. We can also declear with auto
keyword.
Example :- auto int a;
ii. Register :- The register storage class is used to define local variables that
should be stored in a register instead of RAM. This means that the variable
has a maximum size equal to the register size (usually one word) and can't
have the unary '&' operator applied to it (as it does not have a memory
location).
1. Storage :- Register
2. default initial value :-garbage
3. scope :- within the block
4. life :- Till the program execution within the block.
iii. Static :- The static storage class instructs the compiler to keep a local
variable in existence during the life-time of the program instead of creating and
destroying it each time it comes into and goes out of scope. Therefore, making local
variables static allows them to maintain their values between function calls.
The static modifier may also be applied to global variables. When this is done, it causes
40
National Business college.
iv. Extern :- The extern storage class is used to give a reference of a global
variable that is visible to ALL the program files. When you use 'extern', the variable
cannot be initialized, however, it points the variable name at a storage location that has
been previously defined.
When you have multiple files and you define a global variable or function, which will
also be used in other files, then extern will be used in another file to provide the
reference of defined variable or function. Just for understanding, extern is used to
declare a global variable or function in another file.
Syntax :- Even data type variable name is used for global variable.
Features :-1. Storage :- Ram
2. default initial value :- zero
3. scope :- In whole (program)
4. life:- Till the end of program
41
National Business college.
5. Array
Array is a kind of data structure that can store a fixed-size sequential collection of
elements of the same type. An array is used to store a collection of data, but it is often
more useful to think of an array as a collection of variables of the same type.
Instead of declaring individual variables, such as number0, number1, ..., and number99,
you declare one array variable such as numbers and use numbers[0], numbers[1], and
..., numbers[99] to represent individual variables. A specific element in an array is
accessed by an index.
All arrays consist of contiguous memory locations. The lowest address corresponds to
the first element and the highest address to the last element.
#include<stdio.h>
void main()
{
int a[10],i,n=0;
printf("Enter 10 no.");
for(i=0;i<=10;i++)
scanf("%d",&a[i]);
for(i=0;i<10;i++)
{
if(a[i]%2==!0)
n++;
}
printf("odd=%d",n);
42
National Business college.
#include<stdio.h>
#include<conio.h>
void main()
{
int a[3][3],b[2][3],c[2][3],i,j,k;
clrscr();
printf("1st Enter matrix in 3*3 form");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("2nd Enter matrix in 2*3 form");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
scanf("%d",&b[i][j]);
}
}
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
{
43
National Business college.
c[i][j]=0;
for(k=0;k<3;k++)
{ c[i][j]=c[i][j]+a[j][k]*b[k][j];
}}}
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
{
printf("%d ",c[i][j]);
} printf("\n");
}
getch();
}
}
}
}
printf("Sum :-%d",s);
getch();
}
Do it with yourself
(i.) input 10 no. and find greatest no.
(ii.) input 10 no. and arrange them in descending order using bubble sort.
(iii.) Input 10 and find a particular no.
(iv.) Input 5 no. and find average .
(v.) Input 10 no. and count only odd no.
(vi.) Input 10. and print sum of even no.
(vii.) Input 10 no. and print of all no.
45
National Business college.
4.String
Note :- single character is written in single inverted comma (‘a’) and string is written in
double inverted comma(“Ram”).
char g[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
‘a’ =Single character.
“Ram” = String.
Note :- %c is used for character inputting and outputting & %s is used for
String inputting and outputting.
Example :-
#include<stdio.h>
void main()
{
char a[30];
gets(a);
printf("%s",a);
}
C supports a wide range of functions that manipulate null-terminated strings:
46
National Business college.
#include<stdio.h>
void main()
{
char a[30];
int i;
48
National Business college.
Do it with yourself.
(i.) input a string and count no. of character , alphabet, vowels, consonant,
digits, spaces & special characters.
(ii.) input string and convert it into upper and and lower case.
(iii.) Input a string & convert it into (i.)Toggle case (ii.)Setence case (iii.) tittle
case.
Group of string:-
In ’C’ we can also implement strings together in a single array for it double
dimension of character’s are used.
Example:-
#include<stdio.h>
void main()
{
int a[5][32];
int i;
printf("Enter 5 names");
for(i=0;i<5;i++)
{
scanf("%s",a[i]);
}
for(i=0;i<5;i++)
{
printf("%s\n",a[i]);
}
}
49
National Business college.
#include<stdio.h>
void main()
{
char a[10][32],b[32];
int i;
printf("Enter 10 names :-");
for(i=0;i<10;i++)
gets(a[i]);
for(i=0;i<10;i++)
{
strcpy(b,"mr.");
strcat(b,a[i]);
strcpy(a[i],b);
}
for(i=0;i<10;i++)
{
printf("%s\n",a[i]);
}
}
Example :- input 10 names and copy all names into another array variable
In reverse order.
#include<stdio.h>
void main()
{
char a[10][32],b[10][32];
int i,j;
printf("Enter 10 names :-");
for(i=0;i<10;i++)
gets(a[i]);
j=0;
for(i=9;i>=0;i--)
{
strcpy(b[j],a[i]);
j++;
}
for(j=0;j<10;j++)
printf("%s\n",b[j]);
50
National Business college.
}
Do it with yourself.
(i.) input 10 names and convert it into uppercase and prefix mr. in every
names.
(ii.) Input a name and count no of character’s in name using string.h, header
file function(strlen).
(iii.) Input 10 names and count no of characters in every names.
51
National Business college.
6.Pointer
Pointers in C is easy to learn. Some C programming tasks are performed more easily
with pointers, and other tasks, such as dynamic memory allocation, cannot be
performed without using pointers. So it becomes necessary to learn pointers to become
a perfect C programmer. Let's start learning them in simple and easy steps.
As you know, every variable has a memory location and every memory location has its
address defined which can be accessed using ampersand (&) operator, which denotes an
address in memory. Consider the following example, which prints the address of the
variables defined:-
#include<stdio.h>
Void main()
{
Int a=5,*p;
P=&a;
Printf(“%u”,p); //%u is used to print address of variable p (62224).
}
NULL Pointers
It is always a good practice to assign a NULL value to a pointer variable in case you do
not have an exact address to be assigned. This is done at the time of variable
declaration. A pointer that is assigned NULL is called a null pointer.
The NULL pointer is a constant with a value of zero defined in several standard
libraries. Consider the following program:
#include <stdio.h>
void main ()
{
Int a=5,*p;
P=&a;
52
National Business college.
Do it with yourself.
(i.) input 2 no. and do multiplication using pointer.
(ii.) Input 4 no. and find average of the no. using pointer.
(iii.) Input three no. and print greatest.
POINTER ARRAY.
We can also implement an array actually array & pointer same but difference is that
array is constant and pointer is variable according to address of locations.
Pointer and single dimension array we can also implement a single dimension array
using pointer for it .
printf("Value");
for(i=0;i<5;i++)
{
printf("%d,",a[i]);
}
printf("\n");
printf("Address:- ");
for(i=0;i<5;i++)
{
printf("%u,",&p[i]);
}
printf("\n");
printf("Value");
for(i=0;i<5;i++)
{
printf("%d,",*(p+i));
}
printf("\n");
printf("Value");
for(i=0;i<5;i++)
{
printf("%d,",*p);
p++;
}
getch();
}
After writing this code we get output is :-
Do it with yourself:-
Note :- All question has to be solved using pointer.
(i.) input 10 no. & find greatest no.
(ii.) input 10 no. & find maximum no.
(iii.) input 10 no. & find average of the no.
54
National Business college.
We can also implement an double dimension array using pointer for it pointer of
double Dimension is used to store the address of double dimension array
Syntax :-
Example :-
#include<stdio.h>
#include<conio.h>
void main()
{
int a[3][3],(*p)[3];
int i,j;
p=a;
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
scanf("%d",*(p+i)+j);
}
}
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("%2d",*(*(p+i)+j));
} printf("\n");
}
getch();
}
Example :- input no. in 5*5 matrix form and multiply 2 to the matrix.
#include<stdio.h>
#include<conio.h>
void main()
{
int a[5][5],(*p)[5];
int i,j,g;
p=a;
printf("Enter no in 5*5 form ");
55
National Business college.
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
{
scanf("%d",*(p+i)+j);
}
}
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
{ g=(*(*(p+i)+j))*2;
printf("%4d",g);
}printf("\n");
}
getch();
}
Pointer to pointer
We can store the address of one pointer variable to another pointer variable is
called pointer variable.
Example :-
#include<stdio.h>
#include<conio.h>
void main()
{
int a=5,*p,**p1,***p2;
p=&a;
p1=&p;
p2=&p1;
printf("%d\n",*p);
printf("%d\n",**p1);
printf("%d\n",***p2);
56
National Business college.
getch();
}
These functions are used to create memory locations dynamically at runtime. These all
functions are found in malloc.h.
i. Malloc () :- This function is used to create memory dynamically. It
initializes its variable with garbage value .
Syntax :-
int *p =(int *)malloc (n*size of (int));
Example :-
#include<stdio.h>
#include<malloc.h>
#include<conio.h>
void main()
{
int *p,n,i;
printf("Enter the no. ");
scanf("%d",&n);
p=(int*)malloc(n*sizeof(int));
printf("Enter the no.");
for(i=0;i<n;i++)
scanf("%d",&p[i]);
for(i=0;i<n;i++)
printf("%d\n",p[i]);
getch();
}
Syntax :-
Int *p= (int *)calloc(n,sizeof(int));
Example :-
#include<stdio.h>
#include<malloc.h>
#include<conio.h>
void main()
{
int *p,n,i;
printf("Enter the no. ");
scanf("%d",&n);
p=(int*)calloc(n,sizeof(int));
printf("Enter the no.");
for(i=0;i<n;i++)
scanf("%d",&p[i]);
for(i=0;i<n;i++)
printf("%d\n",p[i]);
getch();
}
iii. Realloc ():- This function is used to modify the size of memory locations
which are created dynamically .
Syntax:-
Int *p = (int *) realloc(p,(n1+n2)*sizeof(int));
Example :-
#include<stdio.h>
#include<malloc.h>
void main()
{
int *p,n,i,n2;
printf("Enter the no.");
scanf("%d",&n);
p=(int*)calloc(n,sizeof(int));
for(i=0;i<n;i++)
scanf("%d",&p[i]);
printf("Enter no. to store more information");
scanf("%d",&n2);
p=(int*)realloc(p,(n+n2)*sizeof(int));
for(i=n;i<(n+n2);i++)
58
National Business college.
scanf("%d",&p[i]);
for(i=0;i<(n+n2);i++)
printf("%d,",p[i]);
}
iv. Free () :- This function is used to realese memory locations which are
created dynamically .
Syntax :-
Free(p);
Do it with yourself:-
i. input some no. in dynamic memory calculate average. input some more
data into it again calculate average and print separately
ii. input no. in dynamic memory again input some more no. and find sum of
all the no.
Structure.
Structure is user defined data type in it we can store different types of data elements in
single unit.
Structures are used to represent a record. Suppose you want to keep the record of
employee of a college. You might want to track the following attributes about each
employee:
i. Name
ii. mobile no.
iii. Salary
iv Joining date
Defining a Structure
To define a structure, you must use the struct statement. The struct statement defines a
new data type, with more than one member. The format of the struct statement is as
follows:
Example :- This example shows that different types of data is stored in single
structure variable.
#include<stdio.h>
struct name
{
59
National Business college.
int r,m1,m2,m3,t,avg;
char a[30];
};
void main()
{struct name s; printf("Enter Roll
No."); scanf("%d",&s.r);
printf("Enter Your
name"); scanf("%s",s.a);
printf("Enter The marks of :-\nScience\nmaths\nsst");
scanf("%d%d%d",&s.m1,&s.m2,&s.m3);
s.t=s.m1+s.m2+s.m3;
printf("Total:- %d\n",s.t);
s.avg=s.t/3; printf("Average:-
%d\n",s.avg); if(s.avg>=80)
printf("grade A");
if(s.avg>=60 && s.avg<80)
printf("Grade B");
else
printf("Grade C");
}
Structure essentialization:- we can also initialize structure variable with its initial
value.
As shown in example
Example :-
#include<stdio.h>
#include<conio.h>
struct student
{
int roll;
char n[32];
int marks;
};
void main()
{
60
National Business college.
Copy Structure :-we can also copy value of a structure variable into another structure
variable
It is performed in 2 ways
i. Element by element.
ii. Whole structure.
Example :-
#include<stdio.h>
#include<string.h>
struct student
{
int r;
char n[32];
int marks;
};
void main()
{
struct student s={1,"Deepak",30};
struct student t;
t.r=s.r;
strcpy(t.n,s.n);
t.marks=s.marks;
printf(" Roll no.%2d\nName %s\nMarks%3\d",t.r,t.n,t.marks);
61
National Business college.
iii. Whole structure :- In this method all elements are copied together at a time
into structure variable .
#include<stdio.h>
Struct student
{
Int r;
Char n[32];
Int m;
};
Void main()
{
Struct student s={1,”Deepak”,30);
Struct student t;
t=s;
printf(“Roll no.%d\n Name %s \n Marks %d”,t.r,t.n,t.m);
}
Array of structure
Array of structure:- We can can also create an array of structure to store more
than one information of particular thing .it is also group of continuous memory
location of structure type data.
Syntax :-
struct student s[10];
#include<stdio.h>
struct student
{
int r;
char n[32];
int m1,m2,m3;
};
void main()
{
struct student s[3];
int i,c=0,t;
62
National Business college.
clrscr();
printf("Enter the information of stduents");
for(i=0;i<3;i++)
{
printf("\n%d. Enter the name",i+1);
scanf("%s",s[i].n);
printf("\nEnter the roll no.:-");
scanf("%d",&s[i].r);
printf("\nEnter the marks of Physics:-");
scanf("%d",&s[i].m1);
printf("\nEnter the marks of Chemestry:-");
scanf("%d",&s[i].m2);
printf("\nEnter the marks of Maths");
scanf("%d",&s[i].m3);
}
for(i=0;i<3;i++)
{
printf("\nName.%3s",s[i].n);
printf("\nRoll No.%3d\n",s[i].r);
t=s[i].m1+s[i].m2+s[i].m3;
printf("Total marks:-%3d",t);
}
}
63
National Business college.
Do it with yourself
(i.) write a program to input information of 5 employee and find detail of an
employee using id of an employee.
(ii.) Write a program to input information of 5 employee and print them
serially.
(iii.) Input information of some employee and found employee with highest
salary.
(iv.) Input information of 10 students name,roll no.,marks of 3 subject and find
topper of the class.
Nested structure.
Nested structure :-In it one structure variable is defined within another
structure variable.
Syntax :-
Struct student
{
…………………………….
…………………………….
};
Struct school
{
………………
Struct student variable;
};
Example :-
#include<stdio.h>
struct company
{
char name[30],id[30];
};
struct emp
{
int bs;
struct company c;
};
void main()
{
struct emp s[10];
int i;
printf("Enter the information of employe\n");
64
National Business college.
for(i=0;i<5;i++)
{
printf("Enter the name of employe\n");
scanf("%s",s[i].c.name);
printf("Enter the id");
scanf("%s",s[i].c.id);
printf("Enter the salary\n");
scanf("%d",&s[i].bs);
}
for(i=0;i<5;i++)
{
printf("NAME:-%s\n",s[i].c.name);
printf("ID:-%s\n",s[i].c.id);
printf("Basic salary:-%d\n",s[i].bs);
}
}
Union :- It is also a user a user defined data type and works same as structure type but
the difference is that it shares same memory locaton for every data elements.
Syntax :-
Union name
{
Data element
………….
…………………………
};
Syntax :-
Typedef datatype new-name;
Example :-
65
National Business college.
#include<stdio.h>
void main()
{
typedef int salary;
typedef char name;
name n[32];
salary bs;
printf("Enter the name of employee");
scanf("%s",n);
printf("Enter the salary of an emplolyee");
scanf("%d",&bs);
printf("\n%s\n%d",n,bs);
}
Enum(enumerator)
Enum(enumerator):- It is also a user defined data type and used to create symbolic
constant.
Syntax :-
Enum{Enumerator-name,constant-name2…….};
Example :-
#include<stdio.h>
#include<conio.h>
enum day{sun=1,mon,tue,wed,thu,fri,sat};
void main()
{
int day;
scanf("%d",&day);
switch(day)
{
case sun: printf("sunday");
break;
case mon: printf("Monday");
break;
case tue: printf("tuesday");
break;
case wed: printf("Wednesday");
break;
case thu: printf("Friday");
break;
66
National Business college.
FILE :-This file structure is responsible for opening or creating a disk file.
There is a file structure called (FILE) in <stdio.h> header file which is responsible for
connection between HDD and RAM to open a disc file we use pointer of this structure.
Syntax:-
FILE pointer variable;
Fopen(“File-name”,”w”);
Fopen(“student”,w”);
(ii.) ”r” :- It always opens an existing file. It is used to read content of disc file.if
unable to open it returns NULL.
Fopen(“student”,”r”);
(iii.) “a” :- It is used to append data into a disc file. If file does not exist it creates
new if unable to open it returns NULL(‘\0’).
(iv.) “w+” :- In it reading and writing both operations are performed in a new
file if unable to open then it returns NULL (‘\0’).
(v.) (“r+”):- In it an existing file is opened for reading & writing both if unable
to open then it returns NULL (‘\0’)
fopen(“student”,”r+”);
67
National Business college.
(vi.) (“a+”) :- In this a file is open for appending & reading both operations if
unable to open then it returns NULL (‘\0’).
⇒ Getc() or fgetc():- This function is used to read data from a disc file
character by character .
Syntax:-
Getc(file-pointer);
Example:- Getc(fp;)
Example :- This example shows how to access information from
storage devices.
#include<stdio.h>
void main()
{
FILE *fp;
char ch;
fp=fopen("ram","r");
if(fp==NULL)
printf("Unable to open");
else
{
do{
ch=getc(fp);
printf("%c",ch);
}while(ch!=EOF);
fclose(fp);
}
}
Putc() or fputc() :-This function is used to write data into a disc file character by
character.
Syntax:-
fputc(char,file-pointer);
Example :- fputc(ch,fp);
Example :-
#include<stdio.h>
#include<conio.h>
void main()
{
68
National Business college.
FILE *fp;
char ch;
fp=fopen("Gautam","w");
do{
ch=getchar();
putc(ch,fp);
}while(ch!=EOF);
fclose(fp);
}
69
National Business college.
In ‘c’ there is a provision for talking data from command line. These data are called
command line argument for it two argument are created in main function
I. Argc
II. Argv
Example :- This example shows how to make own copy con command with your own
name.
#include<stdio.h>
void main(int argc,char*argv[])
{
char ch;
FILE *fp;
clrscr();
fp=fopen(argv[1],"w");
if(fp==NULL)
printf("Unable to open");
else
{
do{
ch=getchar();
putc(ch,fp);
}while(ch!=EOF);
fclose(fp);
}
}
Fgets():- This function is used to read a group of characters (string from a disc file).
Syntax :-
Fgets(string variable,no of char,file-pointer);
Example :-
70
National Business college.
#include<stdio.h>
void main()
{
FILE *fp;
fp=fopen("ram","r");
char ch[12];
while(fgets(ch,11,fp)!=NULL)
printf("%s",ch);
fclose(fp);
}
fprintf():- This function is used to write different types of data into a disc file into a
formatted way.
Syntax :-
fprintf(fp,”format specifier”,variable);
example :-
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
int a;
float b;
fp=fopen("ram","w");
scanf("%d%f",&a,&b);
fprintf(fp,"%d%f",a,b);
fclose(fp);
}
Fscanf():- This function is used to read different types of data in formatted way.
Syntax:-
Fscanf(fp,”format specifier”,&variable);
Example :-
#include<stdio.h>
void main()
{
FILE *fp;
int a;
float b;
clrscr();
fp=fopen("ram","r");
fscanf(fp,"%d\n%f",&a,&b);
71
National Business college.
printf("%d%f",a,b);
}
Fwrite:- This function is used to write a block of data into a disc file.
Syntax :-
fwrite(&block,size of(block),no of block,file pointer);
Example :-
#include<stdio.h>
struct student
{
int r;
char n[32];
int m;
};
void main()
{
struct student s;
FILE *fp;
fp=fopen("student","w");
printf("ENTER THE ROLL NO.OF
STUDENT"); scanf("%d",&s.r);
printf("ENTER THE NAME OF STUDENT");
scanf("%s",s.n);
printf("ENTER THE MARKS");
scanf("%d",&s.m);
fwrite(&s,sizeof(s),1,fp);
fclose(fp);
}
Fread() :- This function is used to read data from a disc file.
Syntax :-
Fread(&block,sizeof(block),no of block,file-pointer);
Examle :-
#include<stdio.h>
struct student
{
72
National Business college.
int r;
char n[32];
int m;
};
void main()
{
struct student s;
FILE *fp;
fp=fopen("student","r");
fread(&s,sizeof(s),1,fp);
printf("Roll no. %d\n NAME %s\n MARKS
%d",s.r,s.n,s.m); fclose(fp);
}
Random access file:- In ‘c’ there is a provision to access data in 2 ways.
i. Serial access
ii. Random access
(i.) Serial access :- In serial access method data is accessed serially one after
another from a disc file .
(ii.) Random access :- In this method data is accessed directly .
Fseek(fp,10,seek_set);
Fseek(fp,10,seek.cur);
Fseek(fp,-10,seek.cur);
Fseek(fp,-10,seek_End);
Ftell()=This function is used to get current location in a disc file in numbere of bytes.
Ftell(fP);
73
National Business college.
N=ftell(fp);
Rewind() :- This function is used to send the cursor or begning of the file.
Syntax :-
Rewind(file-pointer);
Example :- Rewind(fp);
Syntax :-
While(!feof(fp))
{
…………………..
…………………..
}
Perror() :- This function is used to print error
message Perror(“Error message”);
Pre-processor directives
In it those elements are included which are processed before the main program is
processed it is started with a # symbol.
#include it is used to include an external file into current program it is also used in two
ways :-
(i.) #include<file-name>
(ii.) #include”file-name”
PREDEFINED MACROS
Macro Description
__DATE__ The current date as a
character literal in "MMM DD
YYYY" format.
__TIME__ The current time as a
character literal in
"HH:MM:SS" format.
__FILE__ This contains the current
filename as a string literal.
__LINE__ This contains the current line
number as a decimal
constant.
__STDC__ Defined as 1 when the
compiler complies with the
ANSI standard.
Example :-
#include<stdio.h>
#define output printf
#define input scanf
void main()
{
char ch[32];
output("Enter name");
input("%s",ch);
output("%s",ch);
}
#include<stdio.h>
#define square(x) (x*x)
void main()
{
int a=10,b;
b=square(a);
printf("%d",b);
}
76