Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

National Business College: A Study Material For C' Programming According To Syllabus

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

NATIONAL BUSINESS COLLEGE

A STUDY MATERIAL FOR


‘C’ PROGRAMMING

According to syllabus
of

(MAULLANA MAZHARUL HAQUE ARABIC AND PERSIAN


UNIVERSITY PATNA)

Developed for
IT Department (B.C.A)

NATIONAL BUSINESS COLLEGE


R.K.Plaza Nala Road(Near petrol pump),patna-16
PH :-0612-2660815,7250131311
National Business college.

From Director’s desk

It gives me a great pleasure welcome to N.B College, a Career planning


institute for IT and Management. I welcome the successful students who have
chosen to study IT and Management course in this college and wish them a
bright and successful professional career N.B College is sincerely committed to
the promotion of excellence in computer applications has made professional
impact in almost all sectors of human activity such as education, healthcare,
communication, entertainment, business, industry, media, transport and
scientific research. This has resulted in great demand for computer
professionals all over the globe. Indians have excelled in this field. They are in
great demand even in developed countries like U.S.A, U.K.
National Business College constantly tries to climb the ladder of success
by organizing various seminars and cultural events. We have a wi-fi campus
and internet enabled computers.
The Top IT and management college always puts their best Endeavour for
overall growth of the college in terms of infrastructure and quality of IT and
Management education.
Your success is our motto, your motto is to shape your own future and
fulfill your own dreams

With Best wishes

Pankaj kumar
(Director)

College seal (Mohar)

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

I thank my family, teachers, friends and to National


Business college who always motivated me to do best in my
life.
This book is dedicated to all of them who contributed in my
success directly or indirectly.
All the information contained in this book is taken from some
reliable sources, I am thankful to all of them. Finally my
heartful thank to candidates who will use this book to achieve
success in their life.

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.

⇒ The language was formalized in 1988 by the American National Standard


Institute (ANSI).
⇒ The UNIX OS was totally written in C.
⇒ Today C is the most widely used and popular System Programming Language.
⇒ Most of the state-of-the-art software have been implemented using C.
⇒ Today's most popular Linux OS and RDBMS MySQL have been written in C.

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.

Characters sets of ‘c’

Characters of c are classified into two categories.

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.

Example:-\a =Audible beep.


\b =back space.
\t =vertical tab.
\r =carriage return.

Note :- The character’s which are represented with \ are called escape sequences

Example :- \a.\b,\t,\f etc.

TOKENS :- Small individual unit of a program or statement.

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:

Ex:- /*write a program to print hello.

Types of tokens :- It is classified into 5 categories


(1.)Keywords
(2.)variable
(3.)operators
(4.)punctuator

1.Keywords:- keywords are special predefined words whose meaning or operations


are predefined with compiler we cannot use them for another purpose
There are 32 keywords.
Example :- for, while, int, auto, else , enum, goto, struct, break, union, switch, float, etc.

2.Variable :- It represents memory location in which value is stored .it can vary its
value therefore it s called variable.

Rules for variable’s name :-


1.Keywords are not allowed.
2.Only alphabets digits are allowed.
3.Blank space are not allowed.
4. 1st character must me alphabet.
5.Maximum length may 35 character t can vary with compiler

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.

CONSTANT are classified into 2 categories


1.Numeric constant
2.Non Numeric Constant

Numeric constant:- The data or constant which is used in arithmetical operation is


called numeric data
Ex. :- ‘2’,’5’,6’ etc.

Numeric constant is classified into 2 categories.


1.Real Constant:-The Numeric constant in which decimal point is available called real
constant
Ex.:- 7.5,9.8,7.4 etc.

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.

Non numeric constant is also classified is also classified into 2 catogeries.


(1.) character constant
(2.) string constant

Character constant:- Single character with in single inverted comma is called


character constant.
ex. :- ‘A’,’r’,’c’,’e’ etc

String constant :-String is a group of charcter’s represented with in double inverted


comma (“ “) called string constant.
Ex. :- “Ram”,”1234”,”gautam” etc.

10
National Business college.

4.Operator :- Operator perform specified operation on its operants.


Operator is classified into 2 ways
(1.) According to operation.
(2.) According to operants.

1.According to operaton:- It is classified into four catogeries.

(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(++,--):-

Increment operator :- It increases one value to its


operants Ex. a=10,++a=11
Decrement operator :-It decreases one value to its operants
Ex.:- s=12
--s=11.
Note :- it is used in 2 ways.
(i) prefix (a=10,++a)
(ii) imprefix(post fix)

i. Prefix :- In it operator is written before operants &


operation is performed at first in expression .these are
called pre-increment or prefix ex. ++a

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++

5.Punctuator :- In C; means &; means terminator are used as


punctuator #include<stdio.h>
Void main()
{
Printf(“welcome to c”);
}

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.

!(not) = If condition is true then resultant will be 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

Note:- The syntax of an ‘if’ statement in C programming language is:


if(boolean_expression)

{
/* 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 :-

if...else if...else Statement (ladder of if else) :-


An if statement can be followed by an optional else if...else statement, which is very
useful to test various conditions using single if...else if statement.
When using if…else if…else statements, there are few points to keep in mind:
⇒ An if can have zero or one else's and it must come after any else if's.

⇒ 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 :- Print 1,4,7,10……..n.


#include<stdio.h>
void main()
{
int n,i;
printf("Enter the no.");
scanf("%d",&n);
for(i=1;i<=n;i=i+3)
{
printf("%d,",i);
}
}

Note :-for single statement curlie bracket is not important.

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]);
}

Do it with your self

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.

Example :- input no. and count its digit.


#include<stdio.h>
#include<conio.h>
void main()
{
int n,c=0;
scanf("%d",&n);
while(n>0)
{
n=n/10;
c++;
}
printf("%d",c);
getch();
}

Example :- to print Fibonacci series.


#include<stdio.h>
void main()
{
int a=0,b=1,c=0,n;
printf("Enter the No.");
scanf("%d",&n);
while(c<=n)
{
printf("%d",c);
a=b;
b=c;
c=a+b;
}
}

Do it with your self.


(i.) Write a program to check weather input no. is palindrome or
not.
(ii.) Input no. and print sum of its first & last digit.
(iii.) Input no and print sum of its digit.
(iv.) Input no. and print all its factors.
(v.) Write a program to check given no. is Armstrong or not.

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 :- Function is a slef content block of statements to perform a specific task


it performs its task when it is called by its name.
A function definition in C programming consists of a function header and a
function body. Here are all the parts of a function:
Return Type: A function may return a value. The return_type is the data type of
the value the function returns. Some functions perform the desired operations without
returning a value. In this case, the return_type is the keyword void.

 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.

Reduces creation time :-


When an application is divided into a smaller module we can use many programmers to
create those module at the same time this reduces the creation time of an application.

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.

As shown in the solved example:-

#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.

As shown in the solved example:-

#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);
}

(iv.) Function that doesn’t accepts parameter but return a vale.


As shown in the solved example:-
#include<stdio.h>
#include<conio.h>
void main()
{
int s;
int sum();
s=sum();
printf("%d",s);
getch();
}
int sum()
{
int b=0,i;
for(i=1;i<10;i++)
b=b+i;
return(b);
}
Do it with yourself.
Note:- All questions has to be solved using function.
(i.) input a no. and print sum of even no.
(ii.) Write a program to print even no. less than the input no.
(iii.) Write a program to print odd no. from 1 to 50.
(iv.) Input two no. and calculate sum of two no.
(v.) Input a no. and check input no. is prime or not.
(vi.) Input no. and print its all factor.
(vii.) Write a program to print factorial of the given.

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.

i. Formal parameter :-Parameters which are used at the time of function


definition are called formal parameter.
ii. Actual Parameter :-Parameters which are used at the time of function
calling are called actual parameter.

Advance features of function :-


(i.) Recursion.
(ii.) Call by reference.

Recursion:-Something which indicate itself is called recursive and this incident is


called recursion. The function which calls itself is called recursive function and
this incident is also called recursion.
Example. :- To find factorial of a no. using Recursion:-
#include<stdio.h>
void main()
{
int n,s;
int fact(int n);
printf("Enter the no.");
scanf("%d",&n);
s=fact(n);
printf("%d",s);
}
int fact(int n)
{
if(n==0)
return(1);
else
return(n*fact(n-1));
}
i. Call by Reference.:-Function is called by passing the address of a
Variable as parameter at the time of function calling in it if formal parameter
are changed then actual parameter are also changed.

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);
}
}

ii. Continue:- This statement is used to continue a loop control statement


After ignoring all statement after continue statement.
Syntax :- continue;
Example :-

#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();
}

iii. goto:- This statement is also used as jump statement it sends


program execution at specified position in a program.
Syntax :-
goto label
name; Example:-

#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.

Storage class are classified into 4 categories :-


A storage class defines the scope (visibility) and life-time of variables and/or functions
within a C Program. They precede the type that they modify. We have four different
storage classes in a C program:
⇒ Auto.
⇒ Register.
⇒ Static.
⇒ Extern.

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.

that variable's scope to be restricted to the file in which it is declared.


1. Storage :- Ram
2. default initial value :- Zero.
3. Scope :- within the block.
4. life :- Persist in different function cell.

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.

Array is classified into 2 categories.


(i.) Single dimension array
(ii.) Double dimension array
(iii.) Multi dimension array

i. Single dimension array :- It is Continuous memory location of group of element


of same type it is represented in one dimension way;
syntax :- int a[10];
int b[15];
int c[30];
Example :-

#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.

iii. Double dimension array :- It is represented in 2 dimensional form . It is also


a group of continuous memory location of same data type. Elements are
arranged in rows and column as matrix.
Syntax :- int a[3][4];

Example :- Multiplication of matrix.

#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();
}

Iv. Multi dimension array :- It is also a group of continuous memory location of


same data type. It is represented in more than one dimension form.
Syntax :- Int a[2][3][4];
Example :-
#include<stdio.h>
void main()
{
int a[2][3][3],i,j,k,s=0;
clrscr();
printf("Enter no. in 2*3*3");
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
{
for(k=0;k<3;k++)
{
scanf("%d",&a[i][j][k]);
}
}
}
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
{
for(k=0;k<3;k++)
{
s=s+a[i][j][k];
44
National Business college.

}
}
}
printf("Sum :-%d",s);
getch();
}

Example :- to arrange no. in ascending order using bubble sort.


#include<stdio.h>
void main()
{
int no[5],i,j,t;
clrscr();
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;
}
}
for(j=0;j<5;j++)
printf("%d,",no[j]);
}

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

Strings are actually one-dimensional array of characters terminated by a null character


'\0'. Thus a null-terminated string contains the characters that comprise the string
followed by a null.
The following declaration and initialization create a string consisting of the word
"Hello". To hold the null character at the end of the array, the size of the character array
containing the string is one more than the number of characters in the word "Hello."

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.

Syntax :- char a[30];

Note :- %c is used for character inputting and outputting & %s is used for
String inputting and outputting.

Gets() :- This function is found in stdio.h used to input goup of character’s


or string from keyboard.

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.

S.N. Function & Purpose

1 strcpy(s1, s2); Copies string s2 into string s1.

2 strcat(s1, s2); Concatenates string s2 onto the end


of string s1.
3 strlen(s1);
Returns the length of string s1.
4 strcmp(s1, s2);
Returns 0 if s1 and s2 are the same;
less than 0 if s1<s2; greater than 0 if
s1>s2. (used to compare )
5 strchr(s1, ch);
Returns a pointer to the first
occurrence of character ch in string
s1.
6 strstr(s1, s2);
Returns a pointer to the first
occurrence of string s2 in string s1.

7. strrev(s1,s2); Used to reverse a string.

Note :- These all mentioned functions are found in string.h

Example :- To count no. of character’s in a string.


#include<stdio.h>
#include<conio.h>
void main()
{
char a[30];
int i=0,c=0;
clrscr();
gets(a);
for(i=0;a[i]!='\0';i++)
{
c++;
}
printf("%d",c);
getch();
}
47
National Business college.

Example :- count no. of vowel’s from string.


#include<stdio.h>
#include<conio.h>
void main()
{
char a[30];
int i=0,c=0;
clrscr();
gets(a);
for(i=0;a[i]!='\0';i++)
{
if(a[i]=='a' || a[i]=='e' || a[i]=='i' || a[i]=='o' || a[i]=='u')
c++;
}
printf("%d",c);
getch();
}

Example :- To reverse a string.


#include<stdio.h>
#include<conio.h>
void main()
{
char a[30];
int i;
printf("Enter the string");
gets(a);
for(i=0;a[i]!='\0';i++);
{
for(--i;i>=0;i--)
printf("%c",a[i]);
}
getch();
}

Example :- To convert string in upper case.

#include<stdio.h>
void main()
{
char a[30];
int i;
48
National Business college.

printf("Enter the string");


gets(a);
for(i=0;a[i]!='\0';i++)
{
if(a[i]>='a' && a[i]<='z')
a[i]=a[i]-32;
}
printf("Upper case:- %s",a);
}

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.

Example :- input 10 names and prefix mr. in every name.

#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).
}

What are Pointers?


A pointer is a variable whose value is the address of other variable, i.e., direct address
of the memory location. Like any variable or constant, you must declare a pointer
before using it to store any variable address. The general form of a pointer variable
declaration.

How to Use Pointers?


There are a few important operations, which we will do with the help of pointers very
frequently. (d) We define a pointer variable, (e) assign the address of a variable to a
pointer, and (f) finally access the value at the address available in the pointer variable.
This is done by using unary operator * that returns the value of the variable located at
the address specified by its operand.

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.

Printf(“%u”,p); //Address =62224


Printf(“%d”,*p); // value = 5
Printf(“%d”,*(&a);} //value =5

Pointer Arithmetic :-A pointer is a address, it is a numeric value. where we can


perform arithmetic operations on a pointer just as we can on a numeric value.
⇒ We have four arithmetic operator that we can use on pointer are :-
++ ,–,+,-
⇒ Only integer value is added or subtracted with pointer.
#include<stdio.h>
void main()
{
int a=6,*p,b;
p=&a;
b=*p+10;
printf("%d",b);
}

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 .

Following syntax is used.


Datatype *pontername;
Example:-
#include<stdio.h>
#include<conio.h>
void main()
{
int a[5]={1,2,3,4,5};
int *p,i;
clrscr();
p=a;
53
National Business college.

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.

Double dimension array & pointer

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 :-

Data-type (*pointer name)[size];


Int (*p)[10];

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();
}

Dynamic memory allocation

Dynamic memory location :- in c there is a facility to create memory location at


runtime (dynamically ) so that we can modify the size of location also release it after
use.

⇒ For it following ready made functions are used


(i.)Malloc ()
(ii.)Calloc ()
(iii.)Realloc ()
(iv.)Free ()

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();
}

ii. calloc () :- This function is used to create memory dynamically like


malloc function but the difference is that malloc initializes its variable
with garbage value and calloc initializes its variable with zero.
57
National Business college.

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

For maintaining these kinds of record structures are used.

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");
}

Note :- (.) Operator is used to access the element of a structure.


(.) this operator is called member access operator.

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.

struct student s={1,"Deepak",67};


printf("%d %s %d",s.roll,s.n,s.marks);
getch();
}

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.

i. Element by element :- In this method every element of structure variable is


copied into another structure variable separately.

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];

Examle :- This example shows how to collect information in structure

#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
………….
…………………………
};

Typedef:- it is also a user defined data type. It is used to rename a datatype.

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.

case fri: printf("Friday");


break;
case sat: printf("Saturday");
break;
}
getch();
}
FILE HANDLING.
In file handling there is a program for storing data permanently into HDD or external
storage devices so that we can modify delete or print data anytime as required. For it
there is a ready made file structure called file.

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:- This function is used to open a disc file in different modes.

Fopen(“File-name”,”w”);

Different Modes of writing and reading a disc file are as fallows:-


(i.) “w” :- It is used for writing file into a disc file it creates a new file if unable
to open then it returns ‘\0’ (NULL).

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.

Command line argument

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

(i.) Argc :- It is called argument counter and it stores number of argument on


command line it is of integer type.
(ii.) Argv :-It is called argument vector & used to store argument of command
line it is of array of character pointer.

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);
}
}

Puts():-This function is used to write a string into a disc file.


Syntax :-
Puts(string,file-pointer);

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);
}

BLOCK INPUT OUTPUT


In it a group of different types of data is written or read into a disc file.

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 .

Following functions are used :-


Fseek():- This function is used to keep the file cursor on specified file location in
a disc file .
Syntax :-
fseek(file-pointer,no.of bytes, file-position);
i. file-pointer :- Currently opend disk file .
ii. no.of bytes :- The specified location in the no of bytes from begining.
iii. File position :-
(a.) Seek-set:- It represents beginning of file.

(b.) Seek_cur:- Current Location of disc file.

(c.) Seek_end:-End location of this file.

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);

Error function :- There are some error function.

Feof() :- This function is used to check the end of file.

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 :-

The Defined() Operator

The preprocessor defined operator is used in constant expressions to determine if an


identifier is defined using #define. If the specified identifier is defined, the value is
true (non-zero). If the symbol is not defined, the value is false (zero).

(i.) #include<file-name>
(ii.) #include”file-name”

i. #include<file-name> :- In it the specified file is searched in default include


directory.
Example:- #include<stdio.h>

ii. #include”file-name”:- In it the specified file name is searched with in default


74
National Business college.

include directory also in current directory.

Macro :- #define It is used to create micro definition .micro represents group of


tokens which is replaced with its name when program execute.

PREDEFINED MACROS

ANSI C defines a number of macros. Although each one is available


for use in programming, the predefined macros should not be directly
modified. C Programming
149

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);
}

Note :- Macro can also be used as a function.


75
National Business college.

#include<stdio.h>
#define square(x) (x*x)
void main()
{
int a=10,b;
b=square(a);
printf("%d",b);
}

76

You might also like