C Language Notes
C Language Notes
Of
C
Language
Basics of 'C' language 2
C Language Programs
S.no Name of the Program
Simple programs(1 to 15)
1. WAP print “hello”.
2. Write a program to add two numbers. (without scanf()).
3. Write a program to add, multiply, divide, subtract two numbers. (Without
scanf()).
4. WAP to find out simple interest. (Without scanf()).
5. WAP to enter 5 subjects’ marks and calculate total marks and percentage.
(With scanf()).
6. Write a program to give name of item, cost, qty and calculate total bill.
7. Write a program to input marks and calculate total marks and the
percentage.
8. Write a program to input the length and breadth of rectangle to calculate
its area.
9. Write a program to calculate d=(b*b)-4*a*c/quadratic equation.
10. Write a program to convert centigrade to Fahrenheit.
11. Write a program to input five ages and find the average.
12. Write a program to swap two numbers without third number.
13. Write a program to swap two numbers with third number.
14. Write a program to input radius and find the area of circle.
15. Write a program to print int,float values using format specifiers.
Conditional Statements
Simple If(16-21)
16. Write a program to find the smallest from two numbers.
17. Write a program to input age of a person and find whether he/she is
eligible for voting or not.
18. WAP to Input marks in three subjects calculate total marks and
percentage if per>=50 then print pass else fail.
19. Write a program to input a number and find whether it is –ve or +ve.
20. Write a program to find whether a given number is odd or even.
21. Write a program to find whether the year is leap or not.
Nested If (22-27)
22. Write a program to find greatest from three integers.
23. Input age of a person conditions are
if age<12 then child if age between 12 to 25 then young if age between
25to 50 then adult if age >=50 old.
24. WAP to calculate the division of a student after getting valid marks for
three subjects with the conditions that percentage>60 is First division,
percentage<60&>40 is second division, percentage<40 is third division.
25. Input basic pay and calculate total pay (basicpay+bonus) conditions are
Pay<1000 then bonus 10% if pay between 1000 to 3000 then bonus 9% if
pay between 3000 to 5000 then bonus 8% if pay>=5000 then bonus 7% .
26. Input two nos and a choice if choice is ‘a’ add it if choice is ‘s’ subtract it
Basics of 'C' language 3
and if choice is ‘d’ divide it otherwise give message wrong key pressed.
Looping programs
Strings(52-56 )
52. Write a program to change the string from upper to lower case.
Basics of 'C' language 4
Arrays
Multidimensional arrays(66-72)
66.
Input the value of 3*3 matrices and display it input days of a week and
display it.
67. Write a program to add two matrices.
68. Write a program to subtract two matrices.
69. Write a program for matrix multiplication.
70. Write a program to find the sum of diagonal elements of a matrix.
71. Write a program to find the transpose of a given matrix.
72. WAP to find a specific word from string.
Functions(77-89)
ADD TWO NUMBERS USING FUNCTIONS
77 Without arguments without return
Basics of 'C' language 5
Pointers(90-92)
90.
Write a program to find largest among n numbers using pointers and
arrays.
91.
Write a program to swap two numbers using pointers.
92
Multidimensional arrays and pointers and WAP to add two matrices ,
passed as arguments (as ref) using pointers.
12345
Basics of 'C' language 6
Chapter 1
INTRODUCTION TO PROGRAMING LANGUAGES
Programming Languages
Programming languages are the languages used to make programs that can
be executed by the computer using compiler or interpreter. We can create
programs, application software, web sites etc with the help of these
programming languages. Programming language can be categorized as below.
Low Level Language.
Assembly Language.
High Level Language.
Low Level Language (Machine Language)
Machine Language is a language that a computer can understand, but it is
very difficult for the human beings to understand. Programs written in
machine language consist of machine instructions. Machine language consists
of strings of binary numbers (0, 1). Each microprocessor can have different
machine language.
Advantages:
1. Machine language instructions are directly executed, so there
is no compilation or translation needed, that’s why it is fast in
execution.
2. Machine language uses computer memory very well.
Disadvantages:
1. Machine language is a machine dependent.
2. It is very difficult to remember the codes.
3. Modification is difficult in machine language program.
4. High programming skills are required to develop programs in
machine language.
Assembly Language
In 1950s operation codes [opcodes] were developed. Assembler is used to
convert these codes into to machine language. Like it is difficult to remember
any code like(01010001 for add) instead of this binary code in assembly
language we use ADD to add contents of two registers.
Advantages:
1. Assembly language programs are easier to use than machine
language.
2. Error detection is possible and easy.
3. Modification is simple in assembly language program.
4. Less efforts are required as compared to machine language in
writing the program.
Basics of 'C' language 7
Disadvantages:
1. These languages are fully machine dependent language.
2. Good programming skills are required to develop a program in
assembly language.
HIGH-LEVEL LANGUAGE (HLL)
High level languages are very powerful and these are similar to English
language. C, C++, Java, Visual Basic etc are the examples of HLL.
High level Compiler / Machine
language interpreter language
program program
Advantages:
1. HLL are easy to learn and understand.
2. It is very easy to write the program.
3. Mostly the syntax of all high level languages are similar.
4. Knowledge of hardware is not essential to write program.
5. Program written in HLL are easy to modify.
Disadvantages:
1. Compiler or interpreter is required to convert HLL into low level
language.
2. Due to conversion these are slower in speed.
3. Specific hardware and
software are required for some high level language.
Compiler And Interpreter
Compiler and interpreter both are used to convert the high-level language
program into the object code.
Interpreter:- Interpreter convert the program of High level language into
Low level language line by line.
COMMON LANGUAGES
1) BASIC ( BEGINNERS ALL PURPOSE SYMBOLIC INSTRUCTION
CODE):- All purpose symbolic instruction ) It is designed in 1964 by
John George Kemeny and Thoman kurtic. It is easy for beginners,
provide error messasges, no need to understand hardware. Its based
on fortran-2nd + ALGOL.
2) ALGOL( ALGORITHM C LANGUAGE) :- Developed in 1950. It is
the first language that implement nested functions.
3) FORTRAN(FORMULA TRANSLATOR):- It is developed for numeric
computation and scientific calculation and it is developed by IBM in
1950.
4) COBOL:- Common Business-oriented language design for
business, finance administrative systems. Cobol 2002 also support
object-oriented programming.
5) LISP:- (List processing) It is used to implement lists that is a
major data structure developed in 1958.
7) BCPL:-( Basic combine programming language) It can
perform task of many language ‘C’ is based on this language.
7) LOGO:- It gives graphics. It is develop in 1968. It is used to create
simple programs that can contain simple graphics.
8) SQL (STRUCTURE QUERY LANGUAGE):- It is used in databases to
create database and access information from it.
C/C++ compilers
Turbo C++
Borland C++
Pelles C
Intel C++
VisualAge C++
Tiny 'C' Compiler
Basics of 'C' language 10
Chapter 2
BASIC OF 'C' LANGUAGE
Before Writing 'C' Program
Before starting programming in ‘C’ Language, it is better to learn some basic
concepts like:-
1. Important logics that will be used in common 'C' programs.
2. Character set of 'C' language.
3. Constants
4. Variables
5. Keywords
6. Data types
7. Operands
8. Operators
9. How to open 'C' Compiler.
10. Compile and run 'C' program
11. Open and save 'C' program.
12. Algorithms and Flow Charts.
1. Basic Logics [Formulas]: Some of the basic formulas that we will
use in 'C' are:-
Constant Variable
1) Constant value doesn’t 1) Variable vary during
change during execution of the program.
execution of the program.
2) It is fixed quantity. 2) It’s value can be changed.
3)e.g. z=2x+5y 3)e.g. z=2x+5y
here 2,5,are constants. here x,y are variables.
3. With these commands 'C' editor will open that look like
To run the program select run option from the run menu or Press Ctrl + F9
12. Open and save 'C' program.
To open a file select open from file menu or press F3, and to save
select save form file menu or press F2,the extension of 'C' program is
.c
Steps to take C programs in printed form:
1) Go to c:\tc\bin and press enter.Right click on the file having
extension .c or .cpp and open it with notepad.
2) Now go to file menu of notepad & click on print option.
3) The printed form of required C program will be in your hands.
Algorithms
Algorithms are the English like steps to solve a problem. It is the part of
software designing. Before creating a program or software we develop its
design using some tools like algorithms, DFDs, Flowcharts etc. Mainly we
follow following steps to design an algorithm.
Step 1. START //it represents beginning of the algorithm
Step 2. DECLARE //the variables used in algorithm are declared in this step.
Step 3. INPUT // here we input the values
Step 4. FORMULA// the required result is generated in this step.
Step 5. OUTPUT // display the result.
Step 6. STOP // end of algorithm
**We can use if else, goto ,loops etc according to requirement
Flowchart:-
Basics of 'C' language 19
Step 3: STOP
Flowchart
START
STOP
Basics of 'C' language Page No: 20
PRINT C
START
Q3. Write an algorithm and draw
STOP
flowchart to add, sub, mul, div
2 numbers.
Declare A, B, SUM, SUB, MUL,
DIV
Algorithm
Step 1: START
Step 2: DECLARE A, B, ADD, SUB, INPUT A,B
MUL, DIV
Step 3: INPUT A, B
Step 4: ADD A+B ADD = A+B
Step 5: SUB A-B
Step 6: MUL A*B SUB = A-B
Step 7: DIV A/B
Step 8: PRINT “SUM=”, ADD
Step 9: PRINT “SUB=”, SUB MUL = A*B
Step 10: PRINT “MUL=”, MUL
Step 11: PRINT “DIV=”, DIV DIV = A/B
Step 12: STOP
PRINT “SUM=”, ADD
STOP
Basics of 'C' language Page No: 21
DECLARE A,B
INPUT : A, B
IF
A>B
PRINT: A IS
then
BIG
N
PRINT: A IS
Y
BIG
STOP
Pseudo code:-Pseudo code is like an algorithm but pseudo codes are nearer
to the program. It is the outline of the program and it cannot be compiled nor
executed. It is easy to covert Pseudo code into program as compare to
algorithm.
TOKENS:-The individual words ,special symbols , operators, punctuation
marks are called tokens.These are given below:
C
Tokens
Keywords Strings
Constants Identifiers
Operators Special
Basics of 'C' language Page No: 22
s
y
m
b
o
l
s
Basics of 'C' language Page No: 23
Chapter 3
START PROGRAMING IN 'C' LANGUAGE
As we discuss we can use various approaches to develop software. Today
languages are based on two main concepts Procedural Programming and
Object Oriented Programming. ‘C’ is procedural language and ‘C++, Java’ are
Object Oriented languages. In procedural language functions are created to
perform various tasks. Functions can be inbuilt or user defined and in object
oriented language classes are created. Classes are the combination of
functions and data.
'C' language is a procedural language where every thing is done in the form
of functions. In 'C' language we have two main types of functions
1. Inbuilt
2. User defined functions.
Inbuilt functions are pre defined in the 'C' compiler and we use them according
to the requirement, work of inbuilt functions are fix. With the help of inbuilt
functions and statements we create user define functions. 'C' program can
contain any number of user define functions. But one of them must be main
function. Main function is the entry point of the program, compiler run the
working of program from main function, all the other functions are directly
and indirectly called by the main function.
Step1 Start
Step2 Print “hello world”
Step3 Stop
To write a program from algorithm, we step by step convert the steps into
program.
Algorithm Program
Step1 Start void main()
{
When we use inbuilt function in the program it is better to include header files
of that functions like printf function is define in stdio.h so we include this file
in our program. The program become like this.
We compile the program with alt+F9. It displays errors. After removing the
errors we can run the program using Ctrl+F9.Complier runs the program and
control come back to the editor screen, we can use Alt+F5 to view result.
.Algorithm Program
Step1 Start void main()
{
Step2 declare a,b,c int a,b,c;
Step3 a=10 a=10;
Step4 b=20 b=20;
Step5 c=a+b c=a+b;
Step6 Print c printf(“%d”,c);
Step7 Stop }
In printf we need format specifier to print value of the variable like we use
%d to print value of variable c. Some times we use getch() to avoid pressing
Alt+F5. and clrscr() function if we want to clear the screen. clrscr() function
should be used after the variable declaration.
#include<conio.h>
#include<stdio.h>
void main()
{
int a,b,c;
clrscr();
a=10;
b=20;
c=a+b;
printf("%d",c);
getch();
}
Output:- 30
If we write printf function like :- printf(“sum=%d”,c);
Output:- sum=30
Write algorithm and program to swap two numbers
Step1 Start
Step2 declare a,b,c
Step3 a=10
Step4 b=20
Basics of 'C' language Page No: 28
Step5 c=a
Step5 a=b
Step5 b=c
Step6 Print a
Step6 Print b
Step7 Stop
Algorithm Program
#include<conio.h>
#include<stdio.h>
void main()
{
int a,b,c;
a=10;
b=20;
c=a;
a=b;
b=c;
printf("a=%d ",a);
printf("b=%d ",b);
getch();
}
#include<conio.h>
#include<stdio.h>
void main()
{
char ch;
clrscr();
printf("Enter a character ");
scanf("%c",&ch);
printf("character=%c",ch);
getch();
}
Output:
Enter a character G
character =G
We can also assign a character without scanf function, but character
should be in single quotes like ‘a’ ‘F’ etc
#include<conio.h>
#include<stdio.h>
void main()
{
char ch;
clrscr();
ch='A';
printf("character=%c",ch);
getch();
}
Output:- character=A
Chapter 4
OPERATORS
Operators are the symbols that are used to perform various operations on
data, like arithmetic operations, comparison or logical operations etc.Operator
refers to a symbol that tells the computer to perform certain mathematical or
logical tasks on operands. Operators can be Unary and Binary. Unary
Operators work on one operand like –a, b++ etc and Binary operators
work on two operators like a+b, a*c etc.
C provides different types of operators as follow:-
1) Arithmetic operators
2) Logical operators
3) Assignment operators
4) Relational operators
5) Bit wise operators
6) Unary operators
7) sizeof operator
8) Comma operator
9) Conditional operator
These operators are performed on operands and operands are the variables
on which these operations are performed.
e.g x+y
In this x,y are operands and + is operator and x+y is called expression.
a*b=36
a/b=2 (decimal ignored as it is an integer arithmetic)
a%b=1 (remainder)
b) Real arithmetic:- The Operators which are performed only on real
operands, called real arithmetic. Real operands may include decimal or
exponential notation.
e.g a=9.0 and b=4.0
then a/b=9.0/4.0=2.250000
NOTE:- The operation % cannot be used with real operands.
c) Mixed mode arithmetic:- It is the combination of real operand &
integer operand. In this case if either operand is of real type then result will
always be is a real no. e.g 25/10.0=2.5
whereas 25/10=2
2) Logical operators: - The logical operators && and || are used when we
want to test more than one condition to make decisions. The result of logical
operator AND (&&) will be true only if both the conditions are true, whereas
the result of a logical operator OR (||) will be true if one or more conditions
are true. In other words, the result of a logical OR operation will be false only
if all conditions are false.
logical operators
NAME SYMBOL IN 'C'
D &&
OR ||
NOT !
LOGICAL OR (||)
OR (||) is a logical operator that will give result if minimum one of its
condition is true.
Basics of 'C' language Page No: 35
5) Bit Wise Operators: -These operators are used for testing the
bits, or shifting them right or left. These operators are used for
manipulation of data at bit level.
1. Bit wise logical operators
a. Bit wise and (&)Bit wise or (|)
b. Bit wise xor ( ^ )
2. Bit wise shift operators
a. Bit wise left(<<)
b. Bit wise right(>>)
3. Complement operator(~)
Operator Meaning
& Bit wise Logical AND
| Bit wise OR
^ Bit wise XOR
<< Left shift
>> Right shift
~ Complement
#include<stdio.h>
void main()
int n,m,and,or,com,rs,ls,xor;
n=11;
m=5;
and=n&m;
or=n|m;
xor=n^m;
com=~n;
ls=n<<2;
rs=n>>2;
printf("\n n&m=%d",and);
printf("\n n|m=%d",or);
Basics of 'C' language Page No: 37
printf("\n n^m=%d",xor);
printf(“\n ~n=%d",com);
printf("\n rs>>2=%d",rs);
printf("\n ls<<2=%d",ls);
}
Output:-
n&m=1
n|m=15
n^m=14
~n=-12
rs>>2=2
ls<<2=4
int a=5;
a++:
printf(“%d”,a);
Output is 6 means ++ operator increase the value by 1.
Example
int a=5;
a--:
printf(“%d”,a);
Output is 4 means -- operator decreases the value by 1.
Increment or Decrement operators are further two types: -
1) Pre increment operator/Pre Decrement operator
2) Post increment operator/post Decrement operator.
Both operators increment or decrement the variables but at different times.
The statement ++x increments x before using its value, while x++
increments x after its value has been used.
The x++ or x-- reads the value & store a copy of it at temporary location.
The computer increments or decrements the variables, & the temporary
copy is used in expression.
e.g.
int x,y;
x=5;
y=x++;
printf(“x=%d,y=%d\n”,x,y);
o/p :-
x=6,y=5
Example of pre increment operator
#include<stdio.h>
#include<conio.h>
void main()
{
int a=5,b;
b=++a;
printf(“\na=%d”,a);
printf(“\nb=%d”,b);
getch();
}
output:- a=6
b=6
Example of post increment operator
#include<stdio.h>
#include<conio.h>
void main()
{
int a=5,b;
Basics of 'C' language Page No: 39
b=a++;
printf(“\na=%d”,a);
printf(“\nb=%d”,b);
getch();
}
output:- a=6
b=5
Example of pre decrement operator
#include<stdio.h>
#include<conio.h>
void main()
{
int a=5,b;
b=--a;
printf(“\na=%d”,a);
printf(“\nb=%d”,b);
getch();
}
output:- a=4
b=4
Example of post decrement operator
#include<stdio.h>
#include<conio.h>
void main()
{
int a=5,b;
b=a--;
printf(“\na=%d”,a);
printf(“\nb=%d”,b);
getch();
}
output:- a=4
b=5
7) sizeof operator: - The sizeof operator returns the size , in bytes
, of the given operand. A sizeof operator is a unary operator that returns
the number of bytes required to store a variable or a data type.
Syntax is:-
sizeof(datatype or variable)
Example:-
sizeof (int)
Basics of 'C' language Page No: 40
Output
size of int =2 bytes
size of float=4 bytes
size of char=1 byte
8) Comma operator: - The comma operator (,) is used to declare more
than one variable in single line. It is also known as separater as it separates
one variable name from other.
Example
int a,b,c;
9) Ternary operator: - Ternary operator is also known as conditional
operator or immediate if. These are ? and : ternary operator. An operator that
takes three statements to work. The syntax of this operator is
<Condition>? <Expression1>: <expression2>
The <condition> is evaluated first. If the result is true then expression 1 is
executed, otherwise expression 2 is executed.
If <condition> is false ,expression3 is evaluated & its value becomes the
result of expression.
e.g. if a=15,b=5
x=(a>b)?a:b
The above example means that if a is greater than b then a will be assigned
to x, otherwise b will be assigned to x.
It can be achieved using if-else statements as follows:
if(a>b)
x=a;
else
x=b;
Note:The detail of if-else is discussed in next chapter.
Basics of 'C' language Page No: 41
Operators
Associativity
([-. Left to right
! - ++ -{- + * & (type-cast) sizeof Right to left
* /% Left to right
+ - Left to right
<< >> Left to right
< <= > >= Left to right
== != Left to right
& Left to right
^ Left to right
| Left to right
&& Left to right
|| Left to right
?: Left to right
= += -= *= /= %= Right to left
&= ^= |= <<= >>= Left to right
Important Questions[Short]
1. Define relational operators.
2. Explain Advance assignment operator.
3. Define Ternary operators.
4. Define sizeof operator.
5. Write difference between logical AND and OR operators.
6. Write difference between ++I and I++.
Important Questions[Long]
1. Explain Bitwise operators.
2. Explain increment and decrement operators with example.
3. Write precedence of the operators.
Basics of 'C' language Page No: 42
Chapter 5
CONDITION CONTROL STATEMENTS
Control Statements
Normally program is executed in the sequential order, and when we want to
change the normal execution of the program then we need to use control
statements or we can say control statements are used to change the normal
execution of the program.
Control statements are mainly divided into three types
1. Condition control statements
2. looping or iterative statements
3. branching statements
1. Condition control statements
These are used when we want to execute the statement or block of
statements according to some condition. Conditional execution can be
controlled by :-
a. if
b. if else
c. if else if
d. Nested if
e. switch case
f. Conditional operator or ternary operator
If Statement
It is the basic condition control statement. When we have single
condition then we mostly use it. The if statement allows a programmer
to test the value of a conditional expression and to select or reject the
execution of the statement or block of statements depending on this
value.
Syntax of if:
if (condition)
Expression {
false statement1;
true statement2;
Step7 Stop }
IF ELSE
If is a single selection structure and if else is a double-selection structure
because it selects from two different actions. If else is one of the most
commonly used control statement.
Statement1 Statement2
Syntax
if (Expression)
statement1
else
statement2
If Expression is true then it executes statement1 otherwise it executes
statement2
Write an algorithm and program to Input two number and print
greatest from them.
Algorithm Program
Step1 Start void main()
{
Step2 declare a,b int a,b;
Step3 Print “Enter value of a” printf(“Enter value of a”);
Step4 Input a scanf(“%d”,&a);
Step5 Print “Enter value of b” printf(“Enter value of b”);
Step6 Input b scanf(“%d”,&b);
Step5 if a> b if(a>b)
begin {
Print “a is big” printf(“a is big”);
End }
Else else
Begin {
Print “b is big” printf(“b is big”);
End }
Step7 Stop }
Output:-
Enter value of a 20
Enter value of b 10
a is big
Basics of 'C' language Page No: 45
In this example if a is greater than b then first block is executed and if b>a
then second block will execute else if none of the above conditions are true
then else part will execute. If –else-if is faster than multiple if block because
in this if first block is executed then all the other blocks are ignored by the
compiler.
Nested if
We can write if statement within the scope of another if or else block, it is
known as nested if.
Syntax of nested if:
if (condition)
{
if (condition)
{
do this;
}
else
{
Basics of 'C' language Page No: 47
do this;
Basics of 'C' language Page No: 48
and this;
}
}
else
{
do this;
}
#include<stdio.h>
#include<conio.h>
void main( )
{
int a,b,c;
clrscr();
printf("enter the value of a");
scanf("%d",&a);
printf("enter the value of b");
scanf("%d",&b);
printf("enter the value of c");
scanf("%d",&c);
if(a>b)
{
if(a>c)
{
printf("a is big");
}
else
{
printf(“c is big”);
}
}
else
{
if(b>c)
{
printf("b is big");
}
else
{
printf(“c is big”);
}
}}
#include<stdio.h>
#include<conio.h>
void main( )
{
int a,b;
clrscr();
printf("enter the value of a");
scanf("%d",&a);
printf("enter the value of b");
scanf("%d",&b);
(a>b)?printf("a is big"):printf(" b is big");
getch();
}
Nested ternary operators.
#include<stdio.h>
#include<conio.h>
void main( )
{
int a,b,c;
clrscr();
printf("enter the value of a");
scanf("%d",&a);
printf("enter the value of b");
scanf("%d",&b);
printf("enter the value of c");
scanf("%d",&c);
(a>b&&a>c)?printf("a is big"):(b>c)? printf(" b is big"):printf(“c is big”);
getch();
}
Switch statement
When we have multiple if statements then we can use switch case statement.
The variable used in switch is known as switch variable. The variable in the
switch statement can be of int or char type only. The switch statement can
also contain the default statements that will be executed if none of the case
is executed, default is optional.
syntax of Switch
switch (expression)
{
case 1:
...block of statements1...
break;
case 2:
...block of statements2...
break;
-----------------
Basics of 'C' language Page No: 50
-----------------
-----------------
default:
...block of statements for default..
break;
}
#include<stdio.h>
#include<conio.h>
void main( )
{
char c;
clrscr();
printf("enter the value of c");
scanf("%c",&c);
if(c==’r’)
{
printf("colour is red");
}
else if(c==’b’)
{
printf("colour is blue");
}
else if(c==’g’)
{
printf("colour is green");
}
else
{
printf("colour is white");
}
}
break;
case ‘b’:
printf("colour is blue");
break;
case ‘g’:
printf("colour is green");
break;
default:
printf("colour is red");
}
}
Applications of switch:
1) It makes program easy to read and understand.
2) It is the replacement of multiple if statements.
3) Whole switch block is act like a single block.
Limitations of switch:
1) We can only use int and char type data.
2) We can not write relational operators in case.
Like case > 10 is wrong.
fflush(stdin);
scanf(“%c”,&ch);
switch(ch)
{
case ‘a’:
c=a+b;
printf(“\naddition=%d”,c);
break;
case ‘s’:
c=a-b;
printf(“\nsubtraction=%d”,c);
break;
case ‘d’:
c=a/b;
printf(“\ndivision=%d”,c);
break;
default:
printf(“\nwrong key pressed”);
}
getch();
}
Chapter 6
LOOPING AND BRANCHING STATEMENTS
Loops are used to execute statement or block of statements more than once.
In other words, Loop is defined as continuity. In simple language, it means to
do a particular task again and again till a particular condition is true or
satisfied.
For example
A person is given a task to go upstairs or downstairs for five no. of times
continuously. These processes of going up and down again and again are
known as loop. In a simple way we can say that a particular work or job is
done repeatedly.
Use of loops in programming is to calculate the result or percentage of 100,000
students of Punjab school education board. In this case, we have to calculate
the percentage of each student individually. To do this, we have to apply the
same formula again and again for each student. This process is very time
consuming, so to save memory space as well as time, loop is used in the
database. We can apply formula with the help of loop in one single line
according given condition.
Thus a loop is a part of program through which the control moves several
times during the execution of the program. The part which is executed again
and again is known as body of the loop. During the execution of loop,
whenever control falls to end of the body of the loop, it again jumps to the
starting point of body of the loop. This continues till a condition is satisfied
and control comes out of the loop if the condition is not satisfied.
Increment/decrement;
}
There will be no semicolon at the end of the line containing the keyword
while in while loop.
Loops are also very helpful if we want to multiply , add or count number from
the continue list like 2 4 6 8 10 12 14 16 18 20 to add numbers we use s=s+a
where s is used for sum and a is the variable of the loop at start value of s
should be initilized with 0 as in the following example value of s in the beging
of the loop is 0 after one iteration of the loop value of s=s+1 means s=0+1
this make s=1 and after second itration s=1+2 so s is 3 similar after third
itration s=3+3 (6) after fourth s=6+4 (10) this is executed 10 times. In the
end value of s=1+2+3+4+5+6+7+8+9+10=55. Similarly if we want to
count numbers we use c=c+1 and for multiply m=m*a.
void main()
int n,i,s=0;
clrscr();
printf("enter a no");
scanf("%d",&n); //let n=1234
while(n>0)
i=n%10; //4
s=s+i; //0+4=4 4+3=7 7+2=9 9+1=10
n=n/10; //123 12
#include<stdio.h>
void main()
int n,i,s=0;
clrscr();
printf("enter a no");
scanf("%d",&n); // let n=1234
while(n>0)
i=n%10; //i=4 3
s=s*10+i;//s=0*10+4=44*10+3=4343*10+2=432432*10+1=432
n=n/10;
{
for(j=1;j<=5;j++)
{
printf(“%d”,j);
}
printf(“\n”);
}
getch(); }
In above program we have used nested loop. Ist loop is outer loop and 2 nd
loop is inner loop. If the outer loop is true then control goes to the inner loop
otherwise exit the control in outer loop. In simple meaning outer loop act as
no of rows and inner as no of column.
clrscr();
Basics of 'C' language Page No: 64
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
{
printf(“%d”,i);
}
printf(“\n”);
}
getch();
}
for(j=1;j<=i;j++)
{
printf(“9”);
}
printf(“\n”);
}
getch();
}
#include<stdio.h>
#include<conio.h>
void main()
{
int n,i,s=0,m;
clrscr();
for(m=1;m<=1000;m++)
{
n=m;
s=0;
while(n>0)
{
i=n%10;
Basics of 'C' language Page No: 66
s=s*10+i;
n=n/10;
}
if(s==m)
printf(" %d",s);
}
getch();
}
Branching Statements
There are another kind of control statements that can change the execution
of loop or execution of the program. Branching statements are further divided
into three types.
a. Break
b. Continue
c. goto
Break: - Break statement is used to exit from the loop or switch statement.
Whenever break statement is encountered the rest of the statements inside
the loop are ignored and the control go to the next statements after the loop.
It can also be used with a while , a do while , a for or a switch statement.
#include<stdio.h>
#include<conio.h>
void main()
{
int i;
clrscr();
for(i=1;i<=10;i++)
{
if(i==5)
{
break;
}
printf("\n% d",i);
}
getch();
}
output
Basics of 'C' language Page No: 67
1
2
3
4
#include<stdio.h>
#include<conio.h>
void main()
{
int i;
clrcsr();
for(i=1;i<=10;i++)
{
if(i==5)
{
continue;
}
printf(“ %d ”,i);
}
getch();
}
Output: 1 2 3 4 6 7 8 9 10
Goto: - The goto statement is control statement that causes the control to
jump to a different location in the program with or without checking any
condition . It is always used with the label. It increase the readable
complexity of the program so programmers avoid to use this. The goto
statement can only be used within the body of a function definition.
There are two types of goto:-
1) Unconditional jump
2) Conditional jump
Basics of 'C' language Page No: 68
Output
One
Two
Three
Seven
Eight
2. Conditional Jump: In this control is transferred from one
statement to another according to the condition.
EXAMPLE conditional GOTO STATEMENT
#include<stdio.h>
#include<conio.h>
void main()
{
int a;
Abc:
printf(“Enter no greater than 10”);
scanf(“%d”,&a);
if(a<=10)
goto Abc;
printf(“You enter number greater than 10”);
getch();
}
in this program control goes back to Abc label until user not enter number
greater than 10.
Basics of 'C' language Page No: 69
Important Questions[Short]
1. What do you mean by loop?
2. What are the limitations of goto statement?
3. Write advantages of for loop over while and do-while.
Important Questions[Long]
1. Explain various types of loops in 'C' language .
2. Write difference between break and continue.
3. Write difference between while and do-while.
4. What are various jump statements in 'C' language .
** Perform Programs from 27 to 51 from program list
Basics of 'C' language Page No: 70
Chapter 7
ARRAYS AND STRINGS
Arrays are group of similar data types. It’s used to store a large amount of
data. The array elements are stored in contiguous memory locations. In other
words, if an array is declared to be of an int type, it can’t contain elements
that are not of int type.
How to declare an Array:
DataType variablename[size]
Example:- int ary[5];
10 20 30 40 50
ary[0] ary[1] ary[2] ary[3] ary[4]
In the above program ary is variable name which hold the 5 elements which
have a same name, same data type but with different memory locations. As
the memory is allocated sequentially so that data can be easily accessed by
increment or decrement by single variable. Arrays always start with index
value zero.
Advantages of arrays
1. Array is the simplest data structure.
2. It is easy to create.
3. We can use one name for similar identifier.
4. Arrays use reference type so we need not to use return statement.
Limitations
1. Array may require large amount of contiguous memory, which is not
available sometimes.
2. Bound checking is not done by 'C' compiler. Means in ary[5] the index value
should be between 0 to 4 but if we write ary[7],ary[34] etc compiler does
not show any error and display garbage value.
3. Overflow condition may occur in array if we want to store more values
then its size.
ARRAY TYPES
Array is two types
1) One dimensional array
2) Multidimensional array
1) One dimension array:- A list of items have only one subscript and such
a list is called one dimensional array.
Declaration of an array.
int a[5];
In the above example we defined an array a [5]. Here a is a variable name.
Data type of a is integer and 5 is the size of an array. Size is always written
in subscript []. This means that it can store only five elements. Index of a is
start from 0 to 4.
Initialization of an array:- we can also assign values to an array when we
declare it.
int a[]={1,2,3,4,5};
Basics of 'C' language Page No: 71
compiler automatically sets the size of the array like in this case size of a is
5 and it requires 10bytes of memory[2 for each int]
int a[10]={1,2,3,4,5,6,7,8,9,10};
In this we assign values to the ten elements of a. We can access array
elements with its index, for example, if we want to print 5th element from the
list we use a[4].
Write a program to print five elements of an array.
#include<stdio.h>
#include<conio.h>
void main()
{
int a[]={1,2,3,4,5};
clrscr();
printf(“%d”,a[0]);
printf(“%d”,a[1]);
printf(“%d”,a[2]);
printf(“%d”,a[3]);
printf(“%d”,a[4]);
getch();
}
In this program 1 is store at location 0,2 at location 1 similarly others.
When we print a[0] it will display 1.
Write a program to input and print five elements using array.
**it is always helpful to use loop in array
#include<stdio.h>
void main()
int a[5],i;
clrscr();
for(i=0;i<=4;i++) /*it will execute scanf statement 5 times and
value in array*/
for(i=0;i<=4;i++)
printf(“ %d”,a[i]);
getch();
for(i=0;i<=4;i++)
{
for(j=0;j<=4;j++)
{
c[i][j]=a[i][j]+b[i][j];
printf(“ %d”,c[i][j]);
}
printf(“\n”);
}
getch();
}
a b c
1 2 3 4 5 1 1 1 1 1 2 3 4 5 6
Write a 1 2 3 4 5 1 1 1 1 1 program to 2 3 4 5 6
multiply 1 1 1 1 1 two
1 2 3 4 5 2 3 4 5 6
matrices. 1 2 3 4 5 1 1 1 1 1 2 3 4 5 6
1 2 3 4 5 1 1 1 1 1 2 3 4 5 6
#include<stdio.h>
#include<conio.h>
void main()
{
int a[5][5] , b[5][5],c[5][5],i,j,k;
clrscr();
printf(“enter 1st matrix”);
for(i=0;i<=4;i++)
Basics of 'C' language Page No: 72
{
for(j=0;j<=4;j++)
{
scanf(“%d”,&a[i][j]);
}
}
printf(“enter 2nd matrix”);
for(i=0;i<=4;i++)
{
for(j=0;j<=4;j++)
{
scanf(“%d”,&b[i][j]);
}
}
for(i=0;i<=4;i++)
{
for(j=0;j<=4;j++)
{
c[i][j]=0;
for(k=0;k<=4;k++)
{
c[i][j]=c[i][j]+a[i][k]*b[k][j];
}
}
}
for(i=0;i<=4;i++)
{
for(j=0;j<=4;j++)
{
printf(“%d”,c[i][j]);
}
printf(“\n”);
}
getch(); }
Write a program to print transpose of matrix.
Transpose means converting the rows into column;
#include<stdio.h>
#include<conio.h>
void main()
{
int a[5][5],i,j;
clrscr();
printf(“enter array matrix”);
for(i=0;i<=4;i++)
{
for(j=0;j<=4;j++)
Basics of 'C' language Page No: 73
{
scanf(“%d”,&a[i][j]);
}
}
for(i=0;i<=4;i++)
{
for(j=0;j<=4;j++)
{
printf(“ %d”,a[j][i]);
}
printf(“\n”);
}
getch();
}
A B
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15 1 5 9 13 17
16 17 18 19 20 2 6 10 14 18
3-Dimensonal array:- eg int 3 7 11 15 19 A[4][5][3]. In this
we can store total 4*5*3=60 4 8 12 16 20 elements and size
of A is 120 bytes.
Write a program of 3-D Array.
#include<stdio.h>
#include<conio.h>
void main()
{
int a[3][5][4],i,j,k;
clrscr();
printf(“enter array matrix”);
for(i=0;i<=2;i++)
{
for(j=0;j<=4;j++)
{
for(k=0;k<=3;k++)
{
scanf(“%d”,&a[i][j][k]);
}
}
}
for(i=0;i<=2;i++)
{
for(j=0;j<=4;j++)
{
for(k=0;k<=3;k++)
Basics of 'C' language Page No: 74
{
printf(“%d”,a[j][i][k]);
}
}
}
getch();
}
String
C language does not provide any data type in which we can represent
collection of character. So if we want to do this we use character array that is
called string. As we can store more than one element in integer or float array,
similarly we can store more than one character in character array. Group of
characters is also known as String.
A string is a one dimensional array of characters terminated by a NULL(‘\0’).
For example,
char name[20]={‘P’,’R’,’A’,’T’,’H’,’A’,’M’};
or
char name[20]={“PRATHAM”};
The size of name is 20 bytes(1 byte for 1 char) and we use only first three
bytes to store “PRATHAM” after this we have 13 bytes left that contain garbage
value. But when we print it, it display first three characters only because
compiler place NULL also represented as ‘\0’ at the end of the string, so when
compiler print the string it print up to NULL character. We can input and print
string using %s format specifier in scanf and printf functions. We can also use
gets to input a string and puts to print a string.
Write a program to input and print a string.
#include<stdio.h>
#include<conio.h>
void main()
{
char ch[20];
clrscr();
printf("Enter name ");
scanf("%s",&ch); // or we can use gets(ch);
printf("Name=%s",ch);
getch();
}
String library functions are the functions, which are used regularly and
stored in library file and whenever these functions are needed , you need to
include the required header file in your program like as,
#include<string.h>
There are 7 inbuilt functions to perform different operations on strings.
1.. strlen: This function is used to count the characters in a string.
It calculates the length of the string.
Syntax:
strlen(array variable);
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char s1[20];
int i;
clrscr();
printf(“Enter string “);
scanf(“%s”,&s1);
i=strlen(s1);
printf(“Length=%d”,i);
getch();
}
Basics of 'C' language Page No: 76
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char s1[20],s2[20];
int i;
clrscr();
printf(“Enter string “);
scanf(“%s”,&s1);
printf(“Enter string “);
scanf(“%s”,&s2);
i=strcmp(s2,s1);
if(i==0)
printf(“ Both strings are same”);
else
printf(“ Strings are not same”);
getch();
}
5. strrev() : - String reverse function is used to reverse the
string. This function also contain a single argument
6. strupr() : - String upper case is used to convert the string in to
upper case or in capital letter. This function contains single argument.
7. strlwr() : - String lower case is used to convert the string into
lower case or in small letter. This function contains single argument.
atoi()[define in stdlib header file: This function comes under <stdlib.h>
header file. This function convert numeric string into integer
Syntax
int atoi(string);
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
char s1[20];
int i;
clrscr();
printf(“Enter string “);
scanf(“%s”,&s1);
i=atoi(s1);
printf(“ i=%d”,i);
getch();
}
String can also be accessed as array like we can create programs without
using string functions.
Basics of 'C' language Page No: 78
Chapter 8
FUNCTIONS
Functions are the blocks of C programs which perform the specifc task.
Functions are used to divide the long program into sub program. In general,
a function is a block of code that performs one or more actions. Functions are
called by other functions. A program in the C language consists of several
functions. One such function we use is the main () function. Every function
has a name. The name of the function ends with a pair of parenthesis. This
parenthesis may or may not contain any thing. Whatever is inside the
parenthesis is known as the arguments of the function.
While defining function you must know these things: -
1. Function name.
2. Function return type (if there is no return then use void)
3. Function argument( if there is no argument here also use void).
Syntax to define a function:
<Return type> <function name>(<arguments>);
Example: -
void show();
Why we use function: -
1. Functions are used to find the errors in the program.
2. Functions are used for reusability.
3. It decreases the cost of the software.
4. It increases the efficiency.
5. It makes the programming simple.
6. It reduces the complexity of the program.
Types of Functions
There are two types of functions. First are known as built in functions and
second are the user defined functions.
void show(void);
Note that the keyword ‘void’ is used in the declaration to indicate to the
compiler that no argument is passed to the function. The compiler will produce
an error message if an argument is passed to show () function later in a
program when this function is called.
Example1.WAP to add and subtract two numbers using function with
no return no argument.
As show in the Example: -
#include<stdio.h>
clrscr();
sum(); //Function calling
sub();
getch();
int a,b,c;
printf(“enter first number”);
scanf(“%d”,&a);
printf(“enter second number”);
scanf(“%d”,&b);
c=a+b;
printf(“sum=%d”,c);
int a,b,c;
printf(“enter first number”);
scanf(“%d”,&a);
printf(“enter second number”);
scanf(“%d”,&b);
c=a-b;
int a;
void sqr(int n)
int m;
void cube(int n)
int m;
m=n*n*n;
Basics of 'C' language Page No: 84
Local variables: - Local variables are those variables, which are declared
inside a block or function. These variables are accessible only within the block
and are passed as argument into the function or declared inside the function.
These are also known as function level variable because they are accessible
only within the function.
Global variables: - Global variables are those variables, which are declared
outside the block or function. These are known as global variables. Which is
accessible by each block of the program.
3. With return without Argument: - Return type functions are
those functions, which return a value to the calling function. These
functions start with a specific data type in place of void keyword. These
type of functions use return keyword to send the data back to the calling
function.
As shown in the example:-
Example 3. WAP to find the factorial of a given number using
function with return type.
#include<stdio.h>
int f;
int a,b=1,n;
printf(“enter any number”);
scanf(“%d”,&n);
for(a=1;a<=n;a++)
b=b*a;
return b;
int a,b;
clrscr();
printf(“please enter any number”);
scanf(“%d”,&a);
b=reverse(a); // Function calling
printf(“\n Reverse of a number=%d”,b);
getch();
int r,s=0;
{
r=n%10;
s=s*10+r;
n=n/10;
return s; }
Recursive Functions
Recursive functions are those functions, which call itself again and again.
Normally function is called by the other function, but in recursive function it
call itself repeatedly. This process known as recursion, as shown in the
example below:
Example . WAP to find the factorial of a given number using recursion.
#include<stdio.h>
#include<conio.h>
int fact(int n);
void main()
{
int n,f;
clrscr();
printf(“enter any number”);
scanf(“%d”,&n);
f=fact(n);
printf(“factorial=%d”,f);
getch();
Basics of 'C' language Page No: 86
}
int fact(int n)
{
if(a==1)
{
return 1;
}
else
{
return n*fact(n-1);
}
}
#include<stdio.h>
#include<conio.h>
int fibo(int a,int b);
void main()
{
clrscr();
fibo(0,1);
getch();
}
int fibo(int a,int b)
{
printf(“%d”,a);
if(a>100)
{
return 0;
}
fibo(b,a+b);
}
Call by Value
In C language by default, the arguments are passed to the function by value.
It means the actual arguments copy their value into the formal arguments. In
call by value, we can pass the value. If any change is done into the formal
arguments, it doesn’t affect the actual arguments because both the arguments
use the different memory location.
#include<stdio.h>
#include<conio.h>
void show(int a); //declaring the function (a is our formal
argument)
void main()
{
int x;
clrscr();
printf(“enter any number”);
scanf(“%d”,&x);
show(x); //calling the function ( x is our actual arguments)
printf(“\n now value of x=%d”,x);
getch();
}
void show(int a) // function definition ( a is our formal
argument)
{
a=a+1;
printf(“\n the value of a=%d”,a);
}
Output
Enter any Number = 5
The value of a = 6
Now value of x = 5
Call by reference
In call by reference we can pass the address of a variable in place of value. It
means we can pass the address of actual argument to the formal argument.
If any change is done in to the formal arguments ,it also affects the actual
arguments, because the address of the actual arguments are passed to the
formal arguments .In call by reference, we can pass pointer variable as formal
arguments.
As show in the example:-
#include<stdio.h>
#include<conio.h>
void show(int *a); //declaring the function (a is our
formal argument)
void main()
{
int x;
clrscr();
printf(“enter any number”);
scanf(“%d”,&x);
show(&x); ///calling the function ( x is our actual
arguments)
printf(“\n now value of x=%d”,x);
getch();
Basics of 'C' language Page No: 88
}
void show(int *a)// function definition ( a is our formal
argument)
{
*a=*a+1;
printf(“\n the value of a=%d”,*a);
}
Output
Enter any Number = 5
The value of a = 6
Now value of x = 6
{
char name[20];
int roll,marks;
};
void show(struct student);
void main()
{
struct student s;
clrscr();
printf("enter student name");
scanf("%s",&s.name);
printf("enter student roll number");
scanf("%d",&s.roll);
printf("enter student marks");
scanf("%d",&s.marks);
show(s);
getch();
}
void show(struct student s)
{
printf("\nstudent name=%s",s.name);
printf("\nstudent roll=%d",s.roll);
printf("\nstudent marks=%d",s.marks);
}
Nested Function
Nested function means a function inside a function. But C does not allow
nested functions. But we can call one function into another function. It is also
known as nested function. As shown in the example:
#include<stdio.h>
#include<conio.h>
void sum(int a,int b);
void input(int a,int b);
void input(int a,int b)
{
sum(a,b);
}
void sum(int a,int b)
{
int c;
c=a+b;
printf(“the sum=%d”,c);
}
void main()
{
int x,y;
clrscr();
Basics of 'C' language Page No: 90
Chapter 9
STORAGE CLASSES
Storage classes tell us about three things.
1. Storage classes tell us about the memory. It means a variable
uses which type of memory. It uses RAM or any other memory (CPU
Memory).
2. Storage classes tells us about the scope of variable.The scope of
a variable is defined as the area of program in which it is accessible.
3. Storage classes tells us about the default value of the variable.
There are four types of storage classes.
1. Auto
2. Static
3. External
4. Register
1. Auto: - Auto means automatically. It is the default scope of variables
and they are declared with or without auto keyword, belong to auto storage
class. Auto variable are active in the block in which they are declared. Block
means statements inside the braces ({}).
The scope of auto variable is limited. It means they are local
variable. They can access within the block where they are declared.
The auto storage class variable uses primary memory for storing
data. It means RAM.
The default value of auto storage class is garbage.
For E.g :-
void main( )
{
auto int a,b;
int c;
clrscr( );
printf(“Enter two numbers=”);
scanf(“%d%d”,&a,&b);
c = a + b;
printf(“Sum=%d”,c);
getch( );
}
Note: - As shown above a,b and c all are belong to the auto storage
class .
2) Static variable: - Static variable are those variable, which start
with static keyword. Static variables retain their values through out the
execution of the program. Their initial value is zero. Static variable also
use primary memory for storing data. Static variables are also active in
the block in which they are declared, means the scope of variable is
Basics of 'C' language Page No: 92
local. The declaration part of static variable execute only once even if we
call function more than once. Static variables are mostly used in
functions. As shown in example: -
#include <stdio.h>
#include<conio.h>
void show();
void main( )
{
clrscr( );
show( );
show( );
show( );
getch( );
}
void show( )
{
static int a;
printf(“\n%d”,a);
a=a+1;
}
Output :- 0
1
2
3) Extern variable: - Extern variable are those variables, which are,
declared outside of the block/main. This variable can be accessible by
each block of the program. They are known as global variables. These
variables are declared with extern keyword. Its initial value is zero. They
consider as local variable but work as global variables. They also use a
primary memory (RAM) for storing a data.E.g :-
#include<stdio.h>
#include<conio.h>
void show();
void main( )
{
extern int a;
clrscr( );
printf(“\n the value of a=%d”,a);
show( );
a = a + 10;
printf(“\nNow the value of a=%d”,a);
getch( );
}
void show( )
{
extern int a;
Basics of 'C' language Page No: 93
a=a + 5;
printf(“\nThe value of a=%d”,a);
}
Output :- 0
5
15
4) Register variable: -Register variable are those variable, which
start with register keyword. We can use register keyword to increase the
speed of program. The Resister variable uses the CPU memory. Their
default value is garbage. They are also block level variables, which can
access with in the block where they are declared. In case of non-
availability of CPU memory, these variables use primary memory (RAM).
E.g :-
void main( )
{
register int a;
clrscr( );
printf(“\nThe value of a=%d”,a);
getch( );
}
Chapter 10
STRUCTURE
Structure is a group of similar and dissimilar data types. Structure is user
defined data type. To create a structure, we use struct keyword. Structure
starts with a delimiters ({) and close with a delimiter(}). After closing the
delimiters, we place a semicolon. To access the elements of the structures,
we create a structure variable/ structure field. With the help of structure
variable we use the dot operator and a specific element name, which we want
to access. As shown in the syntax below:
Syntax
struct<structure name>
{
<data type> <variable>;
<data type><variable>;
};
Example
struct student
{
char name[20];
int roll, marks ;
};
In this example student is structure name and in this structure we declare
two different data types , i.e. char & int.
Example of structure
#include<stdio.h>
#include<conio.h>
struct student
{
char name[20];
int roll,marks;
};
void main()
{
struct student s; //s is structure variable
clrscr();
printf(“enter student name”);
scanf(“%s”,&s.name);
printf(“enter student roll no”);
scanf(“%d”,&s.roll);
printf(“enter student marks”);
scanf(“%d”,&s.marks);
printf(“\n your name=%s”,s.name);
printf(“\n your roll=%d”,s.roll);
printf(“\n your marks=%d”,s.marks);
Basics of 'C' language Page No: 95
getch();
}
Initialization of structure
Initialization of structure means to give the initial values to the structure
elements in place of giving the values at run time. As shown in the example
given below:
#include<stdio.h>
#include<conio.h>
struct student
{
char name[20];
int roll,marks;
};
void main()
{
struct student s={“Anju”,1,89}; //initialization of structure
variable s
clrscr();
printf(“\n your name=%s”,s.name);
printf(“\n your roll=%d”,s.roll);
printf(“\n your marks=%d”,s.marks);
getch();
}
name
0 1 2 3 4 ----------------------------------------- 16 17 18 19
roll
0 1
marks
0 1
Basics of 'C' language Page No: 96
Dot Operator:- In structure we can use dot operator to access the elements
of the structure. We can use structure variable with dot operator and then
given the element name, which we want to access. As shown in the example
struct student s;
s.name=”MONCY”
s.marks=89;
Here s is the structure variable and name,marks are the elements of structure
which we are accessing using dot operator.
Structure Array
We can also create an array of the structure for storing the details of more
than one student.
struct student s[5];
Here s is the name of the structure array.The elements of this array are
s[0],s[1],s[2],s[3],s[4].
Write a program to enter the details of five students: their name, roll
no and marks using structure.
# include<stdio.h>
# include<conio.h>
struct student
{
char name [20];
int roll,marks;
};
void main( )
{
int i;
struct student s [5];
clrscr( );
for(i=0;i<5;i++)
{
printf(“\n enter your name”);
scanf(“%s”,& s[i].name);
printf(“please enter roll no”);
Basics of 'C' language Page No: 97
scanf(“%d”,& s[i].roll);
printf(“please enter your marks”);
scanf(“%d”,& s[i].marks);
}
for(i=0;i<5;i++)
{
printf(“\n your name=%s”,s[i].name);
printf(“\n your roll no=%d”,s[i].roll);
printf(“\nyour marks=%d”,s[i].marks);
}
getch( );
}
Nested structure
Nested structure means a structure inside a structure.It is possible to
have one structure as a member of another structure.In nested structure the
first structure is called the outer structure and second structure which inside
the structure is known as inner structure.E.g :-
struct emp
{
char name[20];
struct dep
{
int salary ;
}d;
};
void main( )
{
struct emp e;
clrscr( );
printf(“Enter Employ name=”);
sacnf(“%s”,& e.name);
printf(“Enter your salary=”);
sacnf(“%d”,& e.d.salary);
printf(“\n Your name=%s”,e.name);
printf(“\n Your salary=%d”.e.d.salary);
getch();
}
As shown in the above example the emp is our outer structure and dep is
inner structure.
Passing structure as argument into function: - We can also pass
structure as argument into the function. Same as variable and array. As
shown in the example.In this program,we write a function show().It accepts
a structure as its argument.
Basics of 'C' language Page No: 98
struct student
{
char name[30];
int roll, marks;
};
void show(struct student s);
void show(struct student s);
{
print(“\n Student name=%s”,s.name);
print(“\n Student roll=%d”,s.roll);
print(“\n Student marks=%d”,s.marks);
}
void main()
{
struct student s={“Harparteek”,1,89};
clrscr();
show(s);
getch();
}
In the above example first we declare the structure and then declare the
function with structure argument. Then we define th body of the function and
in last call the function with main function.
Structure Array
Structure starts with struct It does not start with any keyword but
keyword. is uses subscript for creating an array.
We can use dot operator to We can use index of the arrayto access
accesses the elements of the the element of the space array.
structure.
Chapter 11
UNION
Union is a group of similar and dissimilar data types or elements. It is a user
defined data type. Union starts with ‘union’ keyword and terminate with
semicolon same as structure. Union allocates a single memory to its elements.
All the elements of the union share the single memory. To access the elements
of union we can create a union variable. It is same as structure.
The major difference between the union and structure is that in
structure different members use different memory locations whereas in union
all members of union share the same memory location.
Syntax: -
union < union name >
{
<data type> <variable name> ;
<data type> <variable name> ;
};
E. g: -
union student
{
char name [20];
int rollno, marks;
};
0 1 2 3 4 5 6 ------------------------- 17 18 19
roll
marks
As shown in the example and figure the union allocate 20 bytes memory for
name, roll and marks, which is the largest or higher memory in the union.
WAP to create union, which can store student detail like students
name, rollno, and marks.
Basics of 'C' language Page No: 101
union student
{
char name[20];
int rollno,marks ;
};
void main( )
{
union student s;
clrscr( );
printf(“Enter Employ name=”);
sacnf(“%s”,& s.name);
printf(“\n Your name=%s”,s.name);
printf(“Enter your Rollno.=”);
sacnf(“%d”,& s.rollno);
printf(“\n Your Rollno.is=%d”,s.rollno);
printf(“Enter your Marks=”);
sacnf(“%d”,& s.marks);
printf(“\n Your Marks is=%d”,s.marks);
getch();
}
Initialization of union
We cannot initialize the union same as structure because it uses the
single memory location and all the elements use the same memory.
As shown in the example below:
#include<stdio.h>
union student
char name;
int roll,marks;
};
void main()
union student s;
clrscr();
s.name='h'; //initialization of union variable s
printf("\n your name=%c",s.name);
s.roll=1;
printf("\n your roll=%d",s.roll);
s.marks=99;
printf("\n your marks=%d",s.marks);
getch();
Basics of 'C' language Page No: 102
Union Array
We can also create the array of the union same as structure for storing
the details of more than one student.
Write a program to enter the detail of five students: their name,
rollno and marks using union.
# include<stdio.h>
# include<conio.h>
union student
{
char name [20];
int roll,marks;
};
void main( )
{
int i;
union student s[5];
clrscr( );
for(i=0;i<5;i++)
printf(“\n enter your name”);
scanf(“%s”,& s[i].name);
printf(“\n your name=%s”,s[i].name);
printf(“please enter roll no”);
scanf(“%d”,& s[i].roll);
printf(“\n your roll no=%d”,s[i].roll);
printf(“please enter your marks”);
scanf(“%d”,& s[i].marks);
printf(“\n your marks=%d”,s[i].marks);
}
getch( );
}
union emp e;
clrscr();
printf(“the size of the union=%d”,sizeof(e));
getch();
}
Difference between structure and union
Structure Union
Structure start with ‘struct’ Union start with ‘union’ keyword
keyword
All the elements of the structure All the elements use the single
use different memory locations memory location for storing the
for storing the data. data.
It allocates different memory to It allocates single memory. All the
each element. elements share the same memory.
Chapter 12
ENUMERATION
The enumerated data type is used when we know in advance about a finite
list of values as a particular data type. The declaration of enumerated data
type start with ‘enum’ keyword.. ‘enum’ keyword is followed by an enum
name, an open brace, each of the values separated by a comma, and finally a
closing brace and a semicolon. The list of values is known as the enumerated
list of items.
Syntax: -
enum <enum name>{value1,value2,value3……….value n};
example:
enum color { red, blue, green, white, black };
Note:- Here color is the name of the enum, and red, green, blue are the
symbolic constants. Each enum constant has an integer value. If we have not
given any value, then the initial value of the red is 0, blue is 1 and so on and
incremented by one.
As shown in the example below:
#include<stdio.h>
#include<conio.h>
enum col{red, green, blue, yellow, black, white };
void main()
clrscr();
printf(“\n the value of red=%d”,red);
printf(“\n the value of green=%d”,green);
printf(“\n the value of white=%d”,white);
getch();
output:-
the value of red=0
the value of green=1
the value of white=5
void main()
{
clrscr();
printf(“\n the value of red=%d”,red);
printf(“\n the value of green=%d”,green);
printf(“\n the value of white=%d”,white);
getch();
}
Output: -
the value of red=0
the value of green=5
the value of white=9
Important Short Answer Type Questions
1. Give an example of enumerated data type in C.
Important Long Answer Type Questions
1. Explain enum declaration in C with suitable example.
2. How can you differentiate enum from an array?
Chapter 13
POINTER
Pointer is a special type of variable, which is used to store the address of
another variable. This variable starts with asterisk symbol (*). The pointer can
use two special operators.
1. The first one is *(asterisk), it is called indirection operator or
value of operator.
2. The second is &(ampersand), it is called address of operator.
Pointer declaration
A pointer is declared same as a variable with a specific data type. But
declared with an asterisk sign. As show in the example below:
Example
int *ip; //ip is our integer pointer
float *fp; //fp is our Float pointer
char *cp; //cp is our character pointer
65524
Address of
pointer
variable
of the
variable
a 65526
Arithmetic pointers
We can also use pointers for arithmetic purposes same as variables. When
we write a++ it increase the value of the variable but when we write p++,
Basics of 'C' language Page No: 108
b=*p;
}
p++;
}
printf(“the maximum number=%d”,b);
getch();
}
for(j=0;j<3;j++)
{
printf("enter any number");
scanf("%d",&a[i][j]);
}
}
p=&a[0][0];
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("%d",*p);
p++;
}
printf("\n");
}
getch();
}
Pointer with structure
We can also access the elements of the structure with help of pointer. We can
assign the address of the structure variable to the pointer variable. For
accessing the elements we can use arrow (->) operator in place of dot(.)
operator.
Write a program to access the elements of the structure-using
pointer.
#include<stdio.h>
#include<conio.h>
struct stu
{
char name[20];
int roll;
};
void main()
{
struct stu s={"Pratham",1};
struct stu *p;
clrscr();
p=&s;
printf("\n your name=%s",p->name);
printf("\n your roll=%d",p->roll);
getch();
}
Pointer to pointer
Pointer to pointer means which can store the address of another pointer
variable. A pointer-to-pointer variable start with double asterisk (**) sign. A
Basics of 'C' language Page No: 111
simple pointer can store the address of a variable but a pointer to pointer
can store the address of another pointer. As shown in the example below:
Example :-
int a, *p,**pp;
a=5;
p=&a;
pp=&p;
Example program
#include<stdio.h>
#include<conio.h>
void main()
{
int a,*p,**pp;
clrscr();
a=5;
p=&a;
pp=&p;
printf("\nthe value of a=%d",a);
printf("\nthe value of pointer =%d",*p);
printf("\n the value of pointer to pointer=%d",**pp);
getch();
}
Pointer passing as argument to the Function
We can also pass pointer variable as an argument into the function. This is
also known as reference variables.
As shown in the example below:
#include<stdio.h>
#include<conio.h>
void swap(int *a , int *b);
void swap(int *a, int *b)
{
*a=*a + *b;
*b=*a - *b;
*a=*a - *b;
}
void main()
{
int x,y;
clrscr();
printf(“enter the value of x”);
scanf(“%d”,&x);
printf(“enter the value of y”);
printf (“Before Swapping”);
printf(“\n %d/n%d”,x.y);
scanf(“%d”,&y);
Basics of 'C' language Page No: 112
swap(&x ,&y);
printf(“\n after swapping “);
printf(“\n the value of x=%d”,x);
printf(“\n the value of y=%d”,y);
getch(); }
int *show();
int *show()
int a;
printf("enter any number");
scanf("%d", &a);
a=a*a;
return &a;
void main()
int *p;
p=show();
printf("\n The value of a=%d",*p);
getch();
Advantages of Pointers
1. Pointers increase the speed of the program.
2. It is used to read the address of the variable.
3. It is used to the manage memory efficiently.
4. For Dynamic memory allocation we can use pointers.
5. With the help of pointers we can create efficient programs.
6. Pointers can be used to access elements of the structure.
7. It can pass as arguments into the function.
sign.
It can store the value. It can store the address of another
variable
It can not use any special It uses two special operators first is
operator. address operator and second is
indirection operator(value of operator).
When we perform any arithmetic when we perform any arithmetic
operation on variable it increases operation on pointer variable it moves to
the value of the variable. Like the next memory address. It increments
in their address. Like int a=5,*p;
int a=5;
p=&a;
a++;
p++;
Now value of a=6.
Now it increment in their address.
A float variable can store the value A float pointer can store the address of a
of an integer variable. float variable it cannot store the address
of integer variable.
Example Example
int a; int *p,b=5;
a=5; p=&b;
#include<alloc.h>
void main()
{
int i, n,*p;
clrscr();
printf("enter the size of the values");
scanf("%d",&n);
p=(int*) malloc(n);
for(i=0;i<n;i++)
{
printf("enter any number");
scanf("%d",(p+i));
}
for(i=0;i<n;i++)
{
printf("%d\n",(*p));
p++;
}
getch();
}
#include <stdio.h>
#include <alloc.h>
#include <string.h>
#include<conio.h>
void main()
{
char *p;
clrscr();
p = (char *) malloc(10);
strcpy (p, "CJSOFTECH");
printf("String is %s”,p);
printf(“\n Address is %u”, p);
p = (char *) realloc(p, 20);
strcpy(p,"CJSOFTECH Patiala");
printf(“String is %s”,p);
printf(“\n New address is %u",p);
getch();
}
4. Free function:- This function is used to release the memory which is
occupied by the variable. That memory, which is allocated by the above
discussed functions like malloc(), calloc(), realloc(), so this function is used
to free the memory. This function contains a single argument, whose
memory we want to release. As shown in the syntax and example below:
Chapter 14
FILE HANDLING IN C
To understand the concept of File handling, we must understand the
following things;
D Person name
Student name Address
Address A Ph No
Father’s Name Meter No
Ph No T Old Reading
Roll No New
School Name A Reading
Suppose these two different records are of yours. Name, Ph.no, Address
is common. But Roll no, meter no is different that’s why we create
different records.
3. File : File is a collection of similar same type of records. For
example student’s records will be placed in a one file. (Student name,
Address, father’s name, phno, rollno, school name)
Electricity dept will hold records of bill in different file(Person Name,
Address , Ph No, Meter No, Old Reading, New Reading)
Note
Basics of 'C' language Page No: 118
Diagram of file
Data Name
Data Father’s Name (N records mark 1 file)
Data Address
Data Ph No
Data DOB
Data City
Data School
Data Marks
N records
1 record
3rd record
2nd record
In earlier days, the amount of information is stored in manual form. The major
drawbacks of manual system are Required more space to store the data in file
Updating of data was very difficult.
Searching is quite difficult.
No security in manual Files Manual file were not reliable means if file was
lost all the data would also lost.
Now modern files are made on computers. The data is stored in
computerized files.
It has following advantages;
1. Data can be easily stored in compact space updating of data is
very easy. Using the pointers concept when we perform any changes in
a file, all the files which related with that file are automatically updated.
2. Searching is very easy.
3. The data in modern file are very secure. Only the authorized
persons can view data.
4. Files are very reliable because adequate backup checks are there.
The main motive of file handling is to transfer the data from primary
memory to secondary memory.
Types of Files
There are three types of files, which are;
Basics of 'C' language Page No: 119
1. Text Files
2. Data Files
3. Binary Files
1. Text Files: - Text files are those files, which store the information in
the text format. It stores the data into character or strings. The extension
of text file is .txt.
2. Data Files: - Data files are known as database files, which store the
data in different formats. The extension of data file is .dat.
3. Binary Files: - These files store data in binary form. These files store
data in sequence of bytes. It is an Encrypted file so we cannot read it.
FILE Structure
FILE is our inbuilt structure, which is used to create a file. We can create a
pointer of the FILE structure. It is known as file declaration. As shown in the
example and syntax.
Syntax:-
FILE filepointer;
Example:-
FILE *fp;
Note: The type name FILE is always written in capital letters
File handling Functions
1. fopen() functon:- Before using data file it is necessary to open
that file. It can be opened by using fopen() function. The function has
two arguments, first is name of the file to be opened , and second is
string representing mode in which the file is to be opened. As shown in
the syntax and example given below:
Syntax:-
fp=fopen(“filename”,”mode”);
e.g.
fp=fopen(“CJSOFTECH.txt”,”w”);
File name: - It specifies the file name where we want to store the data.
Like “CJSOFTECH.txt”, here CJSOFTECH is the file name and .txt its
extension. It means it is a text file.
Modes: -File can be opened in following modes:
1. Read: - In this mode we can read the data from the file. When
a file is opened in this mode, it is not possible to write the data into the
file. We can use ”r” as a parameter in fopen function.
2. Write: - If a file in this mode is opened we can write the data into
the file but it is not possible to read the data from file. A file already
exists is opened in the write mode, the old contents of the file will be
deleted and new data can be written in the file. We can use ”w” as a
parameter in fopen function.
Basics of 'C' language Page No: 120
Example: -
fgets(str,40,fp);
5. getc() Function:- This function is used to read a character from a file.
This function contains a single argument of file pointer. As shown in the
syntax and example-
Syntax: -
variable=getc(file pointer);
Example:
char a;
a=getc(fp);
Note:
The character read from the file is assigned to a char variable a.
6. putc() Function:-This function is used to write a character to a
file. It has two arguments, first is the character variable and second is
the file pointer. As shown in the example:-
Example:char a;
putc(a,fp);
Note:
Basics of 'C' language Page No: 121
include<conio.h>
void main()
{
char str[32],*p;
FILE *fp,*fp1;
clrscr();
fp=fopen(“CJSOFTECH.txt”,”r”);
fp1=fopen(“CJSOFTECH.txt”,”w”);
while((p=fgets(str,40,fp))!=’\0’)
{
fputs(str,fp1);
}
fclose(fp);
printf(“data is copied”);
fclose(fp1);
getch();
}
FILE *fp;
int i;
for(i=1;i<=10;i++)
putw(i,fp);
printf("data is written");
fclose(fp);
getch();
printf("%d",n);
}
fclose(fp);
getch();
}
Chapter 15
MACRO
Macro is also called a substitution string. A macro always start with # define.
After the # define, we can give the name to the macro and after that we can
give replacement text/value. Wherever the preprocessor encounters that
name, it will replace it with the replacement text. Macro is always declared in
capital letters, which differentiate the macro from variable. If we want to
change the value of the macro variable we can do it at only at place where it
is defined. Macro never ends with semicolon.
The value of the macro body specified by a #define directive can be any
character string or number. For example, the following definition is NAME with
the string "CJSOFTECH".
SYNTAX:
#define <identifier><value>
Example:-
#define A 50
WAP to use macro in the program.
#include<stdio.h>
#include<conio.h>
#define a 10
void main()
{
int b;
clrscr();
b=a*a;
printf(“square=%d”,b);
getch();
}
In macro we can also pass arguments inside the macro. It works as function,
which are defined before using it.
Write a program to swap two numbers without using third variable
and by using macro.
#include<stdio.h>
#include<conio.h>
#define swap(x,y)x=x+y;y=x-y;x=x-y
void main()
{
int a,b;
clrscr();
printf(“enter two no”);
scanf(“%d%d”, &a,&b);
swap(a,b);
printf(“\n now value of a=%d” ,a);
printf(“\n now value of b=%d”,b);
Basics of 'C' language Page No: 126
getch();
}
Typedef
Definition: - Typedef means to rename the existing data type. With the
help of ‘typedef’ we can give the new name to the inbuilt data type
/structure typedef declaration does not declare any new data type which does
not exist in the C language. Typedef means to create new definition name of
an existing data type.
SYNTAX: -
typedef<data type><new data type>;
Example: -
typ edef int cj ;
Example:-
#include<stdio.h>
#include<conio.h>
void main()
{
typedef int cj;
clrscr();
cj a,b,c;
printf(“enter two numbers”)
scanf(“%d%d”,&a,&b);
c=a+b;
printf(“sum=%d”,c);
getch();
}