C- Programming Full Notes
C- Programming Full Notes
Chapter-1
Introduction to Programming
Problem
Definition
Problem Analysis
Design
Coding
Testing
Maintenance
6
Problem Definition : This is the first step in problem solving. In this identify and define the problem.
It means what are the requirements we need to solve a problem.
Problem Analysis : The given problem must be analyze before it is solved. It means what are the
operations to be performed on the problem.
Design : After defining and analyzing a problem the programmer must design a solution of that
problem. For this purpose the programmer can use two programming tools.
Algorithm
Flowchart
Characteristics of an Algorithm:
It may accept one or more input.
It should produce at least one output.
No instruction can be repeated.
Algorithm must have finite number of steps.
Hexagon Looping
Advantages of Flowchart:
It is convenient method of understanding program.
It acts as an important tool for planning and designing a new system.
Disadvantages:
It is difficult to remember the symbols.
Example of Flowchart:
Coding:
Once we complete algorithm and flowchart we proceed the next step of coding.
“coding is nothing but writing an instructions in a particular language to solve the problem.”
Testing:
After writing a program , programmer needs to test the program for completeness and correctness.
Maintenance:
Maintaining a program is review of the program means any improvements or modifications
Are required for the proper documentation of a program.
Basic Control Structures
Control structure: “The ability to control the flow of execution of a program is known as control
structure”. They are :
Sequence
Selection
Iteration
Jumping
Sequence : it just executes statements one by one in an order. Most of the code in any problem
belongs to this category only.
Syntax:
Statement 1
Statement 2
….…..
Statement n
Selection: it executes statements based on the condition only. Whether that condition is true then first
statement will be executed otherwise second statement will be executed.
Syntax: if (condition)
Statement 1
else
Statement 2
Flowchart:
Iteration: “It is also known as repetition. It executes statements repeatedly as long as condition is
true.” Syntax: while(condition)
{
Statement 1;
Statement 2;
.
.
Jumping: It is also known as branching. This type of control structure allows the flow of execution
jump to a different part of the program.
Structured Programming
It is also known as modular programming.
Definition: “Designing and solving a program using sequence, selection and iteration control
structures are called as structured programming”.
Advantages:
Easy to write, debug, understand and modify programs.
Questions:
1. What is a program? 1M
2. Explain the steps to solve a problem. 5M
3. Write any two characteristics of an Algorithm? 1M
4. Define an algorithm and flowchart. 1M
5. Write an algorithm for Simple interest. 3M
6. What are the advantages of an algorithm? 1M
7. What is Structured programming? 1M
8. What are the advantages and disadvantages of flowchart? 1M
Chapter-2
Overview of C
Computers can be utilized efficiently only when the communication between human beings
through the languages. We cannot think of English for communicating with computer. But it is
possible to use English like language to work with the computer.
“C is English like language. When we want to learn one English language we are following
these steps.” As similar in C also
As similar English language we are learn one programming language must and should we follow
above steps. Means first we learn alphabets and then next we learn keywords etc and then using those
words we frame instructions. Finally we are using these instructions we will frame a program.
Types of Languages:
C is oftenly known as” Middle level language.” Because C has combining features of both high level
and low level languages.
Before we are answering this question first we must know what are the features of high level and
low level languages.
But in C writing program is easy and debugging is easy and also execution speed will be faster.
So this is the reason “C is a Middle level language.” And also C has the combining features of
both BCPL and B languages.
Document Section:
Header File Section: This Section helps to include the external file functions such as headerfiles
from the system. This is also known as link section.
Linking: linking puts all other program files and functions together that are required by the program.
o #include<stdio.h>
o #include<conio.h>
o #include<math.h> etc.
Each and every header file must be begin with the # symbol. This # symbol is known as
“preprocessor”. Before processing the program this # symbol instructs the compiler to include all
statements corresponding herder file. For that purpose we used include keyword.
Along with preprocessor directive include header file. Each and every header file must be enclosed
within the angle brackets (< >).
#include<stdio.h>: in this stdio.h refers to standard input and output statement header file.
#include<conio.h> : in this conio.h refers to console input and output header file.
#include<math.h>: any type of mathematical operations included in our program that time we used
this header file.
main() function:
It is the compulsory part in our program. C program.C program contains one or more
functions, but one which must be main() function. Every program execution in C must be begins with
main().
Here we are representing before main() void keyword. Why means void is a keyword which
should not return a value.
Decleration:
This section contains representing variables in our program.
This decleration can be two types. They are
o Global decleration
o Local decleration
Global decleration: variables are declared before the main() function. These variables are related to
all functions.
Ex: main()
{
int a,b; here a and b are local variables.
Statements;
}
Statement is a single line of instruction (or) information. Each and every statement must be
terminated by semicolon.
Function is a set of statements.
Sample program
void main()
{
clrscr();
printf(“\n welcome to C program”);
getch();
}
After writing the program save that program with .c extension.(using f2)
After save then we are compiling our program. Compiling means debugging means error
rectification.(using f9).
Creation of a program.
Compilation and linking of a program.
Executing the program.
Creation of program:
Programs should be written by using editor. After typing the program, save that program
along with .c extention.
After writing source program we need the help of compiler to change the source to object
program (or) machine program.
After compiling, the executable code will be loaded in computer main memory.
Programming Style:
Source Program: It is a program which was created by user in any high level language. It is known
as high level language.
Object Program: C Compiler converts source program in to its machine equivalent code that is
known as object program. It is generated by the compiler.
C is a portable language: The C program written in one computer system can be compiled and run
on other systems with little or no modifications. Hence C language is a portable language.
Questions:
Chapter – 3
It can be represented as
C character set
Collection of statements
called as “program”.
C - Character set
C is a general purpose language. It contains 2 parts. They are
Syntax
Semantics
Syntax of a C language specify character set, words, operators etc. according to the syntax rule
valid C-program can be formulated.
Alphabets
Digits
Special symbols
White spaces
Alphabets: C language allows both lower case and upper case letters. But both are having
different significances. [A-Z] , [a-z]
C-Tokens
“The smallest individual elements in programming are known as tokens”.
C-Tokens
Keywords:
Keywords are the reserve words for specific meaning in C language. All keywords have
predefined meaning. Keywords are in lowercase letters only.
Identifiers:
“A identifier is a name given to a variable, function and array etc programming
elements”.
Constants:
“ It is a physical quantity which does not change its value during executing of a
program is known as constant”.
Integer :
Integer constant is a whole number. It has a sequence of digits with out having a decimal
point. It is prefixed with a positive(+) or negative(-) sign.
Syntax:
Sign digit
Floating:
This type of constant has a seequence of digits having decimal point. It is also prefixed
with positive or negative sign.
Syntax:
Character constant:
A character constant is a single charcter which is enclosed with in a pair of single quote.
String constant:
Variables:
“The quantity that has changes value during executing of a program is known as
variable.”
The variables are the names given to identify the specific elements. These are also known as
identifiers. Variables are represent a perticular memory location where the data can be stored.
Ex: a,b,c ;
Methods of variable:
Declaration of variable:
All variables must be declared before they are used in program. “the purpose of
declaring variables is to reserve amount of memory required for those variables”.
We can declare one or more variables on single line by using comma operator.
Data type:
The data types are used to inform the type of value that can be stored in a variable. The
data may be numeric or non-numeric. In C data types are classified into 2 ways. They are
C has 4 basic data types. These are also known as primitive (these operates by machine)
data types. They are
integer
floating point number
double precession number
character
integer : (int)
All integer numbers are whole numbers without a decimal point. All these numbers can
be preceeded either + or –ve sign.
It is represented by int. the size of this data type will be 2 bytes. For this we are used the format
specifier like %d. the range of this data type will be -32768 to +32767.
2 bytes = 16 bits
2 16 – 1 = 65535
Float is a key word used to indicate floating point numbers. These are numbers with
decimal point. Float data type occupies 4 bytes of memory. The range of this data type is 3.4 *10
-38
to 3.4 * 10 +38.
After decimal point this data type will takes only 6 digits of precession. For this data type we
will use %f format specifier.
This data type is used to declare the variables to hold the large floating point numbers.
When higher precession numbers are required, instead of using float double data type is used.
After decimal digit it will take 14 digits of precession. For this %lf format specifier will be used.
It occupies 8 bytes of memory.
The range of this data type will be 1.7 * 10 -308 to 1.7 * 10 +308.
Character: (char)
This means that a variable is a character. A char is a single ASCII character. Any symbol
enclosed with in a pair of single quote is a charater.
It occupies 1 byte (8bits) of memory. For this we are used %c format specifier. The range of this
data type will be -128 to +127.
1 byte= 8 bits
2 8 – 1 = 255
Once we have declared a variable, the next step is to assign a value to that variable. “The
process of assigning values to variables is known as initialization.”
We can assign a value to a variable in 2 ways. They are
using assignment operator
reading data from keyboard (or) scanf()
using assignment operator:
in this we are used to assignment operator (=).
Syntax: int a=10;
one or more variables can be initialized with one value at the time multiple assignment
operator will used.
Syntax: int x= y= z= 10;
In the above example we are assigned x, y and z those variables have the same value that is 10.
reading data from keyboard (or) scanf():
one more way of assigning values to variables is to input data from heyboard by using
scanf() function.
Symbolic Constant
A symbolic constant is a name that substitutes a numeric constant in our program.
Ex: area = 3.142 * r* r;
In the above example numeric constant will be 3.142 this can be replaced by symbolic constant
“pi”.
Then we are using one preprocessor directive that is “# define”.
“#define is a preprocessor directive and is used to declare a symbolic constants in C
program”.
The above example can be rewrite as
# define pi 3.142
Ex:
#define x 100 #define x 100
main() main()
{ {
int a,b,c; int a, b, c;
a=10, b=20; a=10, b=20;
c = x; c = 100;
a = a + x; a = 10 + 100; 110
b = x + b; b = 100 + 20; 120
} }
Operator:
An operator indicates an operation to be performed on the data.
Operand:
An operand is an entity on which operators perform the operations.
C – Operators
C language provides different types of operators. They are
Unary Operators
An operator that acts upon only one operand is known as unary operator. The unary operators are
Unary minus:
Any positive operand can be associated with unary minus operand then its value gets
changed to negative. It is indicates with – operator along with operand.
Syntax: - (operand)
b = -3
in the above example initially the value of a is 3 but when this a has associated with unary minus
its value gets changed to negative.
Increment Operator:
This is represented by “++” (double plus) symbol. This symbol can be placed either before or
after an integer variable.
This increment is two types. They are pre increment and post increment.
Pre increment:
When the increment operator can be placed before the integer variable that is known as
pre increment operation.
In this the first the value of operand or integer variable must be incremented.
Ex: a= ++b
b = b + 1;
a = b;
Post increment:
When the increment operator can be placed after the integer variable that is known as
post increment operation.
In this the first the value of operand or integer variable must be stored or used.
Ex: a= b + +
a = b;
b = b + 1;
void main()
{
int m = 6 , n = 8;
printf(“ m is %d\n”, + + m);
printf(“n is %d\n” , n + + );
}
Decrement Operator:
This is represented by “- -” (double minus) symbol. This symbol can be placed either before or
after an integer variable.
This decrement is two types. They are pre decrement and post decrement.
Pre decrement:
When the decrement operator can be placed before the integer variable that is known as pre
decrement operation.
In this the first the value of operand or integer variable must be decremented.
Ex: a= - - b
b = b - 1;
a = b;
ex: a= 6 then - - a is 5
Post decrement:
When the decrement operator can be placed after the integer variable that is known as
post decrement operation.
In this the first the value of operand or integer variable must be stored or used.
Ex: a= b - -
a = b;
b = b - 1;
void main()
{
int m = 6 , n = 8;
printf(“ m is %d\n”, - - m);
printf(“n is %d\n” , n - - );
}
Binary Operators
An operator that acts upon minimum two operands is known as binary operator. The binary
operators are
Arithmetic Operators:
These rea the operators used to perform the basic arithmetic operations such as addition ,
subtraction, multiplication and division.
The modulus operator is added to the list of C arithmetic operators. It is used to find the
remainder value.
void main()
{
int a , b ,sum sub, mul, div ;
printf(“\n enter 2 numbers”);
scanf(“%d%d”, &a, &b);
sum = a + b ;
sub = a – b;
mul = a * b;
div = a / b;
printf(“\n sum is %d\n”, sum);
printf(“\n sub is %d\n”, sub);
Relational operators:
They define the relationship that exists between 2 constants or variables. They result in either a
true or false value. The value of true is nonzero that is 1 and that of false is zero.
void main()
{
int a=10, b=5;
printf (“ a==b %d\n”, a==b);
printf ( “a!=b %d\n”, a!=b);
}
Logical operators:
These are used to combine two or more expressions. A logical relationship between the
two expressions. A logical relationship between the expressions is checked with logical
operators.
T T T
T F F
F T F
F F F
T T T
T F T
F T T
F F F
T F
F T
void main()
Bitwise Operators:
All data items are stored in the computer memory as a sequence of bits (0’s and 1’s).
The bitwise AND operator is represented by a single &. This operator operates on two
integer operands. When two operands are one (1) then the result of this operation will be 1.
Otherwise zero (0).
0 0 0
0 1 0
1 0 0
1 1 1
Ex: X = 5 : 00000101
Y = 3 : 00000011
X&Y= 00000001
Bitwise OR ( | ):
If any one of the operands will be one then the result of this operation will be one
otherwise zero.
0 0 0
0 1 1
1 0 1
1 1 1
Ex: X = 5 : 00000101
Y = 3 : 00000011
X | Y= 00000111
The bitwise XOR operator is represented by a ^ (carot) symbol. This operator operates on
two integer operands. When two operands are zero (0) and one then the result of this operation
will be 0. otherwise one (1).
0 0 0
0 1 1
1 0 1
1 1 0
Ex: X = 5 : 00000101
Y = 3 : 00000011
X ^ Y= 00000110
This operator is also called as 1’s compliment operator. This operator changes 1 to 0 and
0 to 1. This is represented by ~ (tilde character).
X = 5 00000101
11111010
Left shift operator is used to move bits from left side to right side. It is represented by << (double
less than).
Ex: a << 5
X = 10 00001010
Right shift operator is used to move bits from right side to left side. It is represented by >>
(double greater than).
Ex: a >> 5
X = 10 00001010
void main()
printf(“12|8 is %d\n”,12|8);
Ternary Operator
This is known as conditional operator. This is used to test the relationship between two variables.
This operator contains a condition followed by two statements or two values.
If the condition is true then the first statement 1 is executed otherwise second statement
will be executed. The condition operator is represented by “ ?: “. It requires two or more
arguments.
z(x>y) ? x : y
the condition x>y is true then x value is printed otherwise y will be printed.
Special Operators
Assignment Operator:
Ex: a = 5;
= = is the relational operator, which is used to compare two quantities means constants, variables
etc.
Comma Operator:
The comma operator can be used to link the related expressions. It is also known as
delimiter or separator. Using comma operator two or more expressions may be combined into a
single expression.
Ex: temp = a;
a= b;
temp = a; a = b; b = temp ;
Size of ( ) Operator:
Size of ( ) operator returns the number of bytes used for the operands, constants, data
types etc.
Where the operand can be data type, constants or variables using this operator we can get
the size of any data type.
int i;
Arithmetic Expressions
A group of constants, variables and operators arranged as per the syntax is known as arthemetic
expression.
Integer Arthemetic:
Ex: 2 + 3 = 5
Floating Arithmetic:
In this some values are integers and some values are real values.
In mixed mode arthemetic expression contains operands of different data types certain
type of conversions are automatically done by the computer itself this is known as implicit type
conversion.
double
float
lowest int
Promotion:
When the variable or constant of lower data type is converted into higher data type is
known as promotion.
Ex: int i = 5;
float f;
f = i;
in the above example I is lowest data type that is integer and f is the highest data type that is
float.
Demotion:
When the variable or constant of highest data type is converted into lowest data type is
known as demotion.
int i;
i = f;
in the above example f is highest data type that is float and i is the lowest data type that is
integer.
Ex: x = (float) 6 + 5 ;
Here 5 and 6 both are integer numbers but the answer will be converted to float data type by
using float casting operator.
void main( )
getch();
Then d = a + b * c
In the above example there are 2 operators. They are + and *. In those * has highest precedence
than + operator. For that
d = 20 + 10 * 5
= 20 + 50
d = 70
if same precedence operators are appeared on a single expression in such situations associatively
from left to right the left most operator will be first executed.
CHAPTER - 4
Managing Input/Output Operations
Reading the data from the input devices and displaying the output on the screen using output
devices. These are two main tasks of computer.
The scanf() function is the formatted input function.the scanf() is used to accept the
values of any data type. This function scans (or) accepts the values from the standerd input
device.
Where
Var1, var2,var3 ----- var n are the arguments passed to the function scanf. They are
address variables.
The second argument in scanf() is the list of variables whose values are to be input. Memory
address of a variable may be obtained by using an ampersand (&) before the variable name.
“ the role of & operator is to indicate the memory location of the variable, so that the value
read at that location.”
/* program to accepts an integer and floating value and print those values */
void main()
{
int a ; float f ;
printf ( “ \n enter integer and float value “);
scanf ( “ %d %f “ , &a, &f );
printf ( “\n integer value is %d float value is %f “ , a, f);
getch();
}
The printf() function is the formatted output function. This function prints all types of
values to the console.
Where
Formatted string is the format specifiers like %d, %f etc and also escape sequences.
List of varibles are the variables whose values are formatted and printed according to the
specifications of the formatted string.
void main()
{
clrscr();
printf ( “ welcome to programming “);
getch();
Escape sequence:
It causes escape from the normal interpretation of a string. The escape sequence begins
with back slash (\) and is followed by one or more special characters.
\b back space
\t horizontal tab
\a bell / alert
\v vertical tab
Format specifies:
Format specifies specify the type of data that can be displayed from the variables
corresponding to the list of variables with the required format.
%c character
%f float
%lf double
%s string
Syntax1:
Here compiler wills creates some amount of space that the number required.
Syntax 2:
here 5 locations will be created ,but positive format specifier, so that the alignment will be right
to left. So that left side one allocation remaining empty.
Syntax 3:
here also 8 locations will be created , but positive format specifier, so that the alignment will be
right to left. So that left side four allocations remaining empty.
Syntax 5:
here 5 locations will be created ,but negetive format specifier is used, so that the alignment will
be left to right. So that right side one allocation remaining empty.
Ex: if a= 5432.123
getchar ()
gets()
The getchar() function reads one character at a time till the user press the entire key. The
getchar() function does not require any argument. Getchar() function requires enter key to be
pressed after the input of character.
Syntax:
The difference between getch() and getche() is that getch() does not display the input
character while entering and getche() display or echos the input character while entering the
character.
Syntax:
Entered caharacter is W
In the above example the character is ‘W’ is entered by the user but getch() does not display the
character typed. If we use getche( ) in place of getch( ) , then we get the result as below
Entered caharacter is W
3. gets ( ):
gets( ) is the unformatted input function. This function accept one string at a time.
Syntax:
gets( string)
ex:
gets ( “vvfgc”)
Output: XY
AdYX
2. putch ( ) function:
putch ( ) is the unformatted output function. putch ( ) is used to display a character and
the argument to this function is the character to be output.
Syntax:
3. puts( ) function:
puts( ) is the unformatted output function. This function print one string at a time.
Syntax:
puts( string)
ex:
puts ( “vvfgc”)
scanf ( ) getchar ( )
it is formatted input function. It is unformatted input function.
It accepts any type of data like integer, it accept only chracter datatype.
It allows format specifiers like %d, %f etc. it can not allow any type of format specifiers.
It can read more than one variable at a time. It can read only one variable at a time.
Syntax: Syntax:
printf ( ) putchar ( )
It is formatted output function. It is unformatted output function.
It printsts any type of data like integer, It prints only chracter datatype.
It allows format specifiers like %d, %f etc it can not allow any type of format specifiers
and also escape sequences like \n, \b etc. and also escape sequences.
It can print more than one variable at a time. It can print only one variable at a time.
Syntax: Syntax:
CHAPTER - 5
Decision making, Branching and Looping
C has mainly 4 types of instructions. They are
Arithmetic instructions
Control instructions
Arithmetic instructions:
These are the instructions used to perform arithmetic operations between variables and
constants.
Control instructions:
It is the ability to control the flow of execution of a program.
C has mainly 3 types of control structures. They are
Sequence
If Statement
It is one way branching statement. This is depends on the condition.
Whether that condition was true then execute the statements in that if block other wise we come
out from that condition.
Syntax:
if (condition)
{
statement;
Ex:
#include <stdio.h>
main()
{
int i = 3,j = 5;
if(i < j)
printf("value of I is %d”, i);
}
If - else Statement
It is two way branching statement. This is also depends on the condition.
Whether that condition was true then execute the statements in that if block other wise else block
statements are executed.
Ex: #include<stdio.h>
void main()
{
int a=10, b=20;
clrscr();
if(a>b)
printf(“a is large %d”, a);
else
printf(“ b is large %d”,b);
getch();
Nested If statement
The if statement may itself contain another if statement is known as nested if statement.
Syntax:
if(condition1)
{
If(condition2)
statement1;
else
statement2;
}
else
{
If(condition3)
Statement3;
}
EX:
main()
{
int a,b,c;
printf(“\n enter 3 numbers”);
scanf(“%d%d%d”,&a,&b,&c);
if(a>b)
{
if(a>c)
printf(“ a is large %d”,a);
else
printf(“ c is large %d”,c);
}
else
{
if (c>b)
printf(“ a is large %d”,c);
else
printf(“ c is large %d”,b);
}
}
Syntax:
if (condition 1)
simple or group of statement
else if (condition 2)
simple or group of statement
else if ( condition 3)
simple or group of statement
.....
else if ( condition n )
simple or group of statement
else
statement n;
Ex:
#include <stdio.h>
main()
{
int i = 2;
if(i == 0)
{
printf(" i == 0");
}
else if(i == 1)
{
printf(" i == 1. \n");
}
else if(i == 2)
{
printf(" i == 2. \n");
}
}
Switch Statement
Switch statement provides multi-way branching. It is an extension of if-else statement. Using if-
else a maximum 2 branches are allowed. If there is need for multiple branches then we use
switch is the best option.
To take one of a number of possible actions.
switch is preferred over multiple if...else statements.
Syntax:
switch (expression)
{
case label 1 : statements;
break;
case label 2 : statements;
break;
:
:
case label n : statements;
break;
default : default statements;
} statements;
}
The expression present within the parenthesis of switch statement must be of type int or
char.
Based on the expression. The control is transferred to a particular case label are executed.
The case label must be of type int or char.
The case default is executed only when none of the cases are true.
The default block is optional.
Break is a keyword is used to terminate the switch construct. The control is transferred to
the first statement after the switch construct.
The labels with several cases need not be in order.
More than one statement with a case need not be enclosed in braces.
It is not compulsory to have the statements for a particular case.
There should not be a semicolon at the end of the closing braces after expression.
Nested switch construct will be allowed.
Ex:
main()
{
int a=2;
switch (a)
{
case 1 : printf(“number is 1”);
break;
case 2: printf(“ number is 2”);
break;
case 3 : printf(“number is 3”);
break;
default: printf(“invalid number”);
}
}
Looping Statement
Using decision making control structures statements are executed only once during execution of
the program. In some situations, it may be necessary to execute a list of statements more than
once. In such cases, the looping constructs are used.
“ looping construct is a construct that executes the statements repeatedly for a certain number
of times as long as the condition is true.
C has provided three types of iteration statements:
1. While loop.
2. do...while loop
3. For loop
Silpa K C[M.Sc] 37 Lecturer, Dept of BCA
C -Programming VVFGC, Tumkur
While Loop
While loop is also known as “pre tested loop” or “entry controlled loop”.
Why means in this we are first check out the condition. Whether that condition was true then the
control transferred to the inside the loop. Otherwise exit from the loop.
In While looping statement allows a number of lines represent until the condition is satisfied
Ex:
Syntax: #include<stdio.h>
while (condition) main()
{
{
int i = 0;
simple or group of statement while (i<=5)
(body of the loop); {
} printf(" the value of i is %d\n", i);
i = i + 1;
Flowchart: }
}
Do While Loop
In while loop, the condition is tested in the beginning. If the condition becomes false for first
time, then the body of while loop will not executed even once. In some programming situations,
we may require to execute the body of a loop at least once even though condition is false for first
time. In such situations do-while loop is used.
Do-while loop is also known as “post tested loop” or “exit controlled loop”.
Because here we are checked the condition after one iteration. Whether that condition was true
then control transferred to next iteration otherwise comes out from the loop.
Syntax: do
{ #include <stdio.h>
statements; main()
} while (expr); {
int i,n = 5;
i = 1;
do
{
Flowchart: printf("the numbers are %d \n",i);
i = i +1;
}while( i<=n) ;
}
For Loop
For loop is also known as “pre tested loop” or “fixed execution loop”. Thie loop is the
modified form of a while loop.
The for loop is especially used to execute the statements for a certain number of times.
This loop simplifies the program as well as can reduce the number of statements.
Syntax: ex: #include<stdio.h>
for( expression1 ; expression2 ; expression3) main()
{ {
Statement1 int i;
: for ( i=1;i<=5;i++)
: {
Statement printf(“%d”,i);
} }
getch();
break statement
goto statement
Syntax:
while(condition)
{
if(condition)
{
statement 1;
:
statement n
break;
}
}
statement n+1;
Ex: main()
{
int i=1;
while(i<=5)
{
if(i==3)
break;
printf(“%d”,i)
i++;
}
}
In the above program output will be 1 and 2.
When I becomes 3 then break statement will be executed then the control transferred to the out of the
loop.
The continue: when this keyword is encountered, it transfers the control back to the loop condition
by skipping the rest of statements of the body of the loop.
This keyword works only with loops. This cannot be used in switch construct.
The transfer of control of continue statement is as shown below.
{
if(condition)
{
statement 1;
:
statement n
continue;
}
}
Ex: main()
{
For (int i=1;i<=5;i++)
{
if(i==2)
continue;
printf(“%d”,i);
}
}
Because when the value of I becomes 2, the condition (i==2) is satisfied and continue statement will
be executed. At the situation 2 will not be printed it will move to the next iteration.
goto statement:
goto even;
void main()
{
int i=1, sum=0;
while(i<=10)
{
printf(“%d”,i);
Output:
1 2 3 4 5 6 7 8 9 10
Sum of 10 natural numbers is 55.
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
void main()
{
int i, j, n;
printf(“\n enter the number of lines:”);
scanf(“%d”, &n);
for(i=1; i<=n; i++)
{
for(j=1; j<=i; j++)
{
printf(“%d”, j);
}
printf (“\n”);
}
}
void main()
{
int num, fact = 1, i;
printf (“\n enter a number”);
scanf(“%d”,&num);
for ( i=1 ; i<= num; i++)
{
fact = fact * I;
}
Output:
Enter a number 5
Factorial of 5 is 120.
void main()
{
int i,j,n;
clrscr();
printf("\n enter the number of lines");
scanf("%d",&n);
for( i=n; i>=1; i-- )
{
for( j=1; j<=i; j++)
{
printf("*");
}
printf("\n");
}
getch();
}
void main()
{
int i,j,n;
clrscr();
printf("\n enter the number of lines");
scanf("%d",&n);
exit() statement:
exit() function is a standerd library function that comes ready made with the C compiler. Its
purpose is to terminate the execution of the program.
Break statement terminates the execution of loop in which it is written, where as exit() function
terminates the xecution of the program itself.
CHAPTER - 6
Arrays
A normal variable can hold only one value. Suppose we may need to process a group of data items
that are having the same data ty2pe such as integer, float etc. in such situations we need one special
data structure that is “arrays”.
Definition:
An array can be defined as an ordered collection of homogeneous data elements of same data
type.
Each element in an array is declared by a subscript or index. It is represented by pair of square braces
[ ].
Arrays are mainly classified into 2 types. They are
Array Initialisation:
Where
ele1, ele2….ele n are the initial values enclosed with in a pair of braces { }.
10 20 30 40 50
Example programs
/* program to accept n integers and store them in an array and also print them */
void main()
{
int a[10], i ,n ;
printf(“\n enter the size of an array”);
scanf(“%d”,&n);
printf ( “ \n enter elements to an array”);
for ( i=0; i<n ; i++)
scanf ( “%d” , &a[i]);
printf ( “ \n elements of an array are”);
for ( i=0; i<n ; i++)
printf ( “%d” , a[i]);
}
/* program to accept 2 integer arrays and find sum of the corresponding elements in the array
*/
void main()
{
int a[10],b[10,c[10, i ,n,sum[10] ;
printf(“\n enter the size of an array”);
scanf(“%d”,&n);
printf ( “ \n enter elements to the first array”);
for ( i=0; i<n ; i++)
scanf ( “%d” , &a[i]);
printf ( “ \n enter elements to the second array”);
for ( i=0; i<n ; i++)
scanf ( “%d” , &b[i]);
This array can be consisting of 2 subscripts.The simplest and most commonly used arrays are
2 dimensional arrays.
This array required row size and column size. The declaration of 2D array will be
Syntax:
Syntax:
Initialization of 2D array
The list of values assigned to array elements in order.
void main()
{
int a[10][10], b[10][10],sum[10][10],sub[10][10],i, j ,n;
clrscr();
printf(“\n enter the order of matrix”);
scanf(“%d”,&n);
printf ( “ \n enter elements to the first array”);
for ( i=0; i<n ; i++)
for (j=0; j<n ; j++)
scanf ( “%d” , &a[i][j]);
printf ( “ \n enter elements to the second array”);
for ( i=0; i<n ; i++)
for (j=0; j<n ; j++)
scanf ( “%d” , &b[i][j]);
The matrix multiplication is possible only, when the columns of 1 st matrix must be equals to the rows
of 2nd matrix.
m x n = p x q
equal
void main()
{
int a[10][10], b[10][10], mul[10][10], i, j ,k,n;
clrscr();
printf(“\n enter the order of matrix”);
scanf(“%d”,&n);
printf ( “ \n enter elements to the first array”);
for ( i=0; i<n ; i++)
for (j=0; j<n ; j++)
scanf ( “%d” , &a[i][j]);
printf ( “ \n enter elements to the second array”);
for ( i=0; i<n ; i++)
}
getch();
}
Sorting
Definition:
Arranging the elements in any one of the order either ascending or descending order.
Bubble Sort:
Bubble sort is the most popular sorting technique. Because it is very simple to understand and
implement.
Condition:
If the 1st element is greater > second element then those two are swapped (interchanged).
Procedure:
First compare 1st element with the 2nd element of an array. If 1 st element > 2nd element then
those two elements are swapped.
Now compare 2nd element with 3rd element of an array. If 2nd element > 3rd element then
those two elements are swapped.
Pass 1: here 1st element is greater than 2 nd element then exchange of those 2 elements.
28 20 30 15 5
20 28 30 15 5
20 28 15 30 5
20 28 15 5 30
Pass 2:
20 28 15 5 30
20 15 28 5 30
20 15 5 28 30
Pass 3:
20 15 5 28 30
15 20 5 28 30
15 5 20 28 30
Pass 4:
15 5 20 28 30
5 15 20 28 30
CHAPTER - 7
Strings
Definition:
String is a one dimensional array of characters. (or)
String is a collection of characters or sequence of characters to be enclosed into double quotes.
Example= “computer”
This string is stored in memory as shown below
c o m p u T e r \0
The very first character occupies 0th subscript place, the second character is stored at the 1st subscript
place and so on, the last character occupies the (n-1) th subscript. However an n-character array
contains (n+1) array elements.
The compiler automatically adds the terminating NULL character that is ‘\0’ at the end of the string.
This character is used to indicate end of the string. C language provides many string handling
functions which are defined in the header file <string.h>.
Operations on strings
There are so many operations are in strings. They are
Concatenating strings
scanf ( ) function
gets ( ) function
getchar ( ) function
scanf ( ) function:
The function scanf with %s format specifier is needed to read the string from the terminal.
B A N G A L O R E \0
Ex: suppose if we input “NEW DELHI”, then storage looks like
N E W \0 ? ? ? ? ? ?
The function scanf ( ) has a drawback it just terminates as soon as it finds blank space.
In the above example scanf reads only new but not delhi because after the word new one blank space
is appeared. Then scanf understand the string will be ended.
getch();
}
gets ( ) function:
gets (str);
printf(“\n given string is %s”, str );
getch();
}
getchar ( ) function:
This function is unformatted input function. It read only one character at a time.
Ex:
void main()
{
char str[40], ch;
int i=0;
printf(“\n enter a string “);
do
{
ch=getchar( );
str[i]=ch;
i++;
printf ( ) function
puts ( ) function
putchar ( ) function
printf ( ) function:
The function printf with %s format specifier is needed to print the string on the terminal.
puts ( ) function:
this unformatted output function. Using this we can print one string at a time.
This is the most convenient method of writing a string . this is a library function and it is available in
the <stdio.h> header file.
putchar ( ) function:
This function is unformatted output function. It print only one character at a time. We can use
this function repeatedly to output a string of characters stored in an array using a loop.
Ex:
void main( )
{
char str[8]= {“skyward”};
int i=0;
for(i=0;i<7;i++)
putchar( str[i]);
putchar(“\n”);
}
{
char ch;
}
Ex3: void main()
{
int i=20;
i = i+’A’;
printf(“%d”, i); it prints 65
}
{
char str[5] = “12345”;
int num;
num = atoi (str);
printf(“number is %d\n”, num);
}
In the above, string is a character array which is assigned the string constant “12345”. The function
atoi converts the string “12345” to its numeric equivalent 12345 and assignes it to the integer
variable num.
Output: programming
It will append the string “ming” to the end of the string “program”. By default the total string was
stored in first string.
Procedure:
1. read two strings as string1, string2.
char str1[40],str2[40];
printf(“\n enter first string”);
gets(str1);
printf(“\n enter second string”);
gets(str2);
strcat(str1,str2);
char str1[40],str2[40];
int i=j=0;
gets(str2);
while( str[i] != ‘\0’)
i++;
while (str2[j] != ‘\0’)
{
str1[i]=str2[j];
i++;
j++;
}
str[i]=0;
printf(“ concatenating of 2 strings is %s\n”,str1);
}
{
puts(“enter the string”);
gets(str);
len=strlen(str);
if(len!=0)
printf(“length of the string is %s\n”, len);
else
break;
}
return(0);
}
{
char str[40];
int i=0;
printf(“enter the string\n”);
gets(str);
while(str[i]!=’\0’)
i++;
printf(“length of given string is %s\n”,i);
}
This function returns -1 , if the ASCII value of first string is less than that of second string.
This function returns 0 (zero), if both strings are equal.
This function returns 1, if the first string is greater than second string.
Procedure:
Start comparing the first character of both strings and if they are equal then increment the
counter and continue for the next characters until corresponding characters till the end of the 2
strings.
char str1[40],str2[40];
int i=j=0;
printf(“\n enter first string”);
gets(str1);
printf(“\n enter second string”);
gets(str2);
int i, j;
printf(“\n enter first string”);
gets(str1);
printf(“\n enter second string”);
gets(str2);
i= strcmp(str1,str2);
if (i = = 0)
printf(“strings are equal”);
else
printf(“\n not equl”);
getch();
}
target[i] = ‘\0’ ;
printf(“ destination string is %s\n”,target);
}
1. /* program to find length of the given string without using library function */
void main()
{
char str[40];
int i=0;
clrscr();
printf("\n enter the string");
gets(str);
while(str[i]!='\0')
i++;
printf("\n the length of the string is %d",i);
getch();
}
Output:
Enter the string vision
Output 2:
Enter the word skyward
The word is not palindrome.
Chapter – 8
If the length of a program is too large, it is very difficult for the programmers to handle it.
Generally larger programs increases errors and it would be a complex job to locate and correct the
errors. Therefore, such programs should be broken down into a number of smaller logical
components.
The process of splitting the lenghy and complex programs into a number of smaller
units(components) is called modularization. Programming with such is called modular
programming.
Debugging is easier, since each module is smaller and easier, the user can easily locate the
errors and correct them.
Build library, it allows the programmer to build a library of most commonly used
subprograms. This reduce the time and space complexity.
Definition:
Library functions:
Those are the functions which are already exist in the computer is known as library functions.
For example printf() and scanf() these are the functions available in <stdio.h> header file.
Sin(), cos() etc mathematical functions are available in <math.h> header file.
Function call:
Function call is to be present inside the main function. This is also known as calling function.
This function call consists of name along with the arguments. Those arguments are called as “actual
arguments”.
Ex: main( )
sum(x,y);
Function Prototype:
To avoid confusion and complexity in data transfer between called function and calling
function, we use this prototype. Always this can be placed before main() function.
In some situations definition is placed before main function, then no need to write prototype.
Function name of the function call and prototype are the same and arguments must match.
Prototype consisting of datatypes corresponding function call arguments.
Function Definition:
The actual code of the function written in this function definition. This is the header of the
function.
There should be match with name of the function, list of formal parameters in prtotype and definition.
Syntax: return type function name ( type1 data1, type2 data2 …. type n data n)
Ex:
clrscr();
c=Sum (a, b); Function call (calling function)
printf (“sum of 2 numbers is %d\n”,c); a,b are actual arguments
getch();
}
int sum (int x, int y) Function definition (called function)
Categories of Functions
Based on the arguments and return values functions are classified 4 types. They are
Function with arguments and with return value.: In this case function call send arguments to
called function and called function sends return value to calling function. Hence there is data transfer
between the calling function and the called function.
Syntax: function prototype(arguments as datatypes );
void main()
{
function call ( actual arguments);
}
function definition( formal arguments )
{
statements;
return;
}
Ex: int sum( int, int );
void main()
{
Actual arguments:
The arguments associated with a function call is referred as actual arguments. These
arguments are sent from calling function to called function.
Ex: void main()
{
int x=10,y=20;
sum (x,y); here x and y are actual arguments.
Formal arguments:
The arguments associated with a function definition are referred as formal arguments. These
arguments are receiving arguments from calling function.
Ex: void sum(int x, int y) these are formal arguments.
{
int z;
z=x+y;
return(z);
}
Call by value
Call by reference
Call by value:
When the values of the arguments are passed from a calling function to a called function, the
values are copied into the called function. If any changes are made to the values in the called
function, those changes are not effect to the calling function.
void swap(int,int);
void main()
Int a=10,b=20;
Swap(a,b);
Printf(“after swap”);
int temp;
temp=x;
x=y;
y=temp;
Call by reference:
In this method, the actual values are not passed, instead of their addresses are passed to a
calling function. Here no values are copied as the memory locations themselves are refernced. If any
modification is made to the values in the called function, those changes will effect to the calling
function.(original values)
void main()
int a=10,b=20;
Swap(&a, &b);
Printf(“after swap”);
int temp;
temp=*x;
*y=temp;
Output:
The value of a is 20
Value of b is 10
Recursion
“It is a process of calling a function repeatedly by itself is known as recursion.”
Advantages:
long factorial(long);
void main()
{
long num;
clrscr();
printf("\n enter the number");
scanf("%ld",&num);
ans=fact(num);
printf("\n factorial of %ld is %ld",ans);
getch();
}
long factorial(long n)
{
if(n==0)
return (1);
else
return (n*fact(n-1));
}
Recursion iteration
Storage Classes
We define one variable needs to mention its data type. But mentioning data type is not sufficient it
also requires storage class.
All variables not only have the data types but also having storage class.
Advantages:
The storage classes are can be classified into 4 types. They are
Auto
Static
Extern
Register
Auto:
It is the default storage class for all local variables. The keyword auto is derived from
automatic.
Static:
The variables which are declared as static are referred to the static variables. Unlike the auto,
the memory allocated for static variables will not be destroyed when the control goes out of the
function. So that the current value of the variable is available for the next time.
If the static variables are not initialized that time the default value will be zero.
static double f;
The variables are called external variables because they are declared or defined outside of the
function like after the main( ). So that these variables are also called as global variables.
void decrement( )
{
i=i-2;
printf(“\n I is %d”,i);
}
Register:
The variables which are declared as register are referred as register variables. These are as
same as the automatic variables.
Chapter- 9
An array is stored a group of homogeneous elements. This is not suitable to store different or
dissimilar data elements, but most of the real world applications need a group of heterogeneous
elements. In such situations we need one special data structure that is “structures”.
Definition:
“it is a meaning full collection of data items of different data types, but it collects all elements
under an unique name”.
Declaration:
Each and every structure must be defined an declared before it appears in a C-program.
Syntax:
struct structurename
{
type1 data1;
type2 data2;
:
type n data n
};
In the above syntax struct is a key word.
Structurename is a name of the structure. It is also known as tagname.
Type1, type2 …. Type n are the basic data types.
Data1, data2 ----data n are the members or fields of the structures.
{ it indicates sarting of the structure.
} it indicates end of the structure.
char sname[20];
};
Declaration of variables:
Like ordinary variables, we can also define and declare structure variables.
Syntax:
Structurestype varlist;
Where structuretype is type of a structure it takes the keyword struct followed by the name of the
structure.
Variable list is the one or more variables seperated by comma (,).
Syntax: ex:
struct structurename struct employee
{ {
type1 data1; int eid;
type2 data2; char ename[20];
: int sal;
Syntax: ex:
struct structurename struct employee
: int sal;
type n data n };
}; struct employee e1, e2 ;
Struct structurename varlist;
Syntax:
Structurevariable . structuremember
Dot operator
Ex:
struct student
{
int rollno;
float fee;
char sname[20];
}s1,s2 ;
We are accessing rollno through first student.
s1. rollno
/*program to define and assign and access the members of the structure */
void main()
{
struct emp
{
char ename[20];
int eno;
float sal;
};
struct emp e1, e2;
Initialization of a structure
Assigning members to a structure at the time of declaration itself. “but C does not permit initalization
of individual structure members with in the templet [with in the braces ]”.
Syntax:
Ex:
Void main()
{
Struct student
{
Int age;
Float weight;
Char name[20];
};
static struct student stu1= { 20,55.4, “ramu”};
static struct student stu2= { 30,55.4, “raju”};
}
{
int age;
float weight;
char name[20];
};
struct student stu1= { 20,55.4, “ramu”};
struct student stu2= { 30,55.4, “raju”};
Void main()
{
Statements;
}
Nested structures
This is also known as structure with in the structure or embedded structure.
“ A structure that contain other structure as a member or as a structure itself is known as embedded
structure”.
2. There may be separate structures. The embedded structure is declared first and the outer
structure declared next.
}e1,e2;
Syntax of second way: ex:
{ {
{ {
}; char name[20];
}e1,e2;
struct item
{
int itemno;
char iname[30];
struct pdate
{
int dd;
int mm;
int yyyy;
}date;
};
struct item items[20];
void main()
{
int i,n;
clrscr();
printf("\n enter the number of goods:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\n enter item %d details",i+1);
printf("\n enter item number");
scanf("%d",&items[i].itemno);
printf("\n enter item name:");
scanf("%s",&items[i].iname);
printf("\n enter purchase date:");
scanf("%d%d%d",&items[i].date.dd,&items[i].date.mm,&items[i].date.yyyy);
}
printf("\n details of the items are:");
printf("\n*****************************");
printf("\nitemno\t\tiname\t\tpdate");
for(i=0;i<n;i++)
printf("\n%d\t\t%s\t\t%d-%d-
%d",items[i].itemno,items[i].iname,items[i].date.dd,items[i].date.mm,items[i].date.yyyy);
getch();
Union
“It is a collection of heterogenoeus elements of different data types. This is similar to the
structures”.
The main difference between the structures and union is in structure each member is assigned its own
memory location due to this some times memory will be wasted. But in union all members are share
common memory location due to this saves memory.
Declaration:
Like structure Each and every union must be defined an declared before it appears in a C-
program.
Syntax:
union unionname
{
type1 data1;
type2 data2;
:
type n data n
};
In the above syntax union is a key word.
{
int rollno;
Declaration of variables:
Like ordinary variables, we can also define and declare union variables.
Syntax:
uniontype varlist;
Where uniontype is type of a union it takes the keyword union followed by the name of the union.
Variable list is the one or more variables seperated by comma (,).
: int sal;
type n data n }e1,e2 ;
}var1,var2….var n ;
Syntax: ex:
union unionname union employee
{ {
type1 data1; int eid;
unionvariable . unionmember
Dot operator
Ex:
union student
{
int rollno;
float fee;
char sname[20];
}s1,s2 ;
We are accessing rollno through first student.
s1. rollno or s1->rollno
/*program to define and assign and access the members of the union */
void main()
{
union emp
{
char ename[20];
int eno;
float sal;
};
union emp e1, e2;
e1.ename= “vvfgc”;
Syntax:
ex:
in the above declaration, slary is an identifier, which is another name for int. what ever the values we
are representing int datatype those are used salary type.
enum
The keyword enum allows the user to define new enumerated user defined type. This user defined
data type is an identifier which can be used to declare variables that can have one of the values
enclosed with in the curly braces.
The compiler assigns integer values beginning with 0 to all the enumeration constants. That is jan is
assigned as 0
Ex:
enum month{jan,feb,mar=6,apr,may=9,jun,jul---dec};
Here by default jan is assigned with 0, feb is assigned with 1 but april is assigned with 7 because
march is assigned with 6 after 6 came ita s 7 like so on.
Chapter- 10
Pointers
A pointer is a powerful construct of the C programming language.
Definition:
“A pointer is a variable which holds the address of other variables such as arrays, structures
and functions that are used in program.”
Advantages:
The indirection operator (*) : it gives the value of the variable that the pointer is pointing to.
Pointer declaration:
Like ordinary variables, pointer variables that appear in a C program must be declared.
address data
dereferencing
1000 100
1001
1002
Referencing
1003 640
…
…
2000
There are 2 integer quantities, 100 and 640 which are stored at the memory locations 1000 and 1003
respectively. Let us assign 100 to x and 640 to y.
y = 200
in order to access the value of a variable x via a pointer, we must need a pointer variable. Assume that
the variable be px. Also, consider another variable py, which points to the address of y.
px= &x
= 1000
Similarly, py=&y
= 1003
here x and y are 2 integer variables. We are declaring one pointer variable by using this syntax
datatype *pointervariable ;
void main()
{
int *iptr;
char *cpter;
int s1,s2;
s1 = sizeof (iptr);
s2 = sizeof (cptr);
printf(“size of iptr is %d\n”, s1);
Pointer Dereferencing
This is a process of referencing the contents of the variables using pointers, indirectly.
1000
ptr to int 1004
1001
1002
1003
num 1004 400
"
"
2000
in the above figure, the variable num designates the memory location 1004 and the pointer variable
ptr-to-int designates the memory location 1000.
Operations on pointers
A pointer variable holds the address of the other variable. This address can be incremented or
decremented. But the multiplication and division operations cannot be performed on the addresses.
This means that the pointer variables cannot be multiplied or divided. Operations that can be
performed on pointers as given below.
Assignment:
A pointer variable can be assigned the address of the other variable.
ptr = &var;
if 2 pointer variables are pointing to the object of the same data type, then they can be
assigned.
ptr1 = ptr2;
ptr = NULL;
Ptrx = ptrx + 2;
Ptrx = ptrx – 1;
One pointer variable can be subtracted from another pointer variable, if both are pointing to
the elements of the same array.
ptr1 = &x[1];
ptr2 = &x[3];
Comparison:
If two pointer variables are pointing to the objects of same datatype, then they can be
compared with one another.
void main()
{
int *ptr;
int x[4] = {10,20,30,40 };
ptr= &x[0];