The document provides an overview of control structures in programming, including sequential programs, conditional statements, loops, and jump statements. It also covers operators in C, such as arithmetic, relational, logical, and bitwise operators, along with their precedence and associativity. Additionally, it discusses writing simple sequential programs and includes examples of basic C programs for arithmetic operations.
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0 ratings0% found this document useful (0 votes)
38 views42 pages
Unit 2
The document provides an overview of control structures in programming, including sequential programs, conditional statements, loops, and jump statements. It also covers operators in C, such as arithmetic, relational, logical, and bitwise operators, along with their precedence and associativity. Additionally, it discusses writing simple sequential programs and includes examples of basic C programs for arithmetic operations.
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 42
Control Structures
2.1. Simple sequential programs
2.2. Conditional Statements
e if
if else
nested if
if else if ladder
switch
2.3. Loops
« for
while
« do while
2.4, Jump in statements
* break and continue
+ goto2. Control Structures:
Generally programs are executing statements in a sequence.
When you want to skip normal flow we have to use conditional statements
In order to execute a code finite number of times we use loops to break and
continue loops we use jump in statements
ee
re eared Ragauenaneras
sete RS cacy,
sere mother
ae
‘to break and
skip
repetition
‘Statement “Statement
ee t sthement2
,
atements Bearers
Statement Statement
Before writing sequential programs we must have knowledge on the
following areas. i.e., tokens in C
separators Comments - Operator
cath «10420 Sa.
LJ L_j| co
Operands OperandsDR ee UR Ree)
Unary operators:
Unary operator is an
operator which works on
single operand only
Ex: it+, i-- ete.,
Binary Operator
Binary operator is
an operator which works
on 2 operands
Ex: a+b, ab, a&b etc.,
Ternary >
Ternary or
conditional (2 :)
Types of operators w.r.to it's Operator
Arithmetic Operators (+, -,*,/, %)
Relational Operators (>, <,»
Logical Operators (&&, ||, !)
Increment (++), decrement (--)
Arithmetic Assignment Operators (+=
Bitwise Operators (&, |, *, «,?)1. Arithmetic Operators: used for arithmetic operations
Operator =21,b=4; Program
Addition a+b=25 #include
Subtraction 17 #include
Multiplication | * a*b=84 ae
Division / a/b=5.25. int a=21,b=4;
= clrscr();
voc % oe printf{‘a+b=%d \n",a+b);
printf{‘a-b:
printf{‘a*b=
printf(‘a/b=%d\n",a/b);
printf{‘a%b-%d",a%b);
getch();
return 0;
2. Relational Operators: Used to check relationship between two
operands.
Operator Symbol
Program
greater than #include-stdio.h>
noteless than | < #include
greater than | >= main()
or equal to i oe
Tess than = ne
equal to peria .
printf{‘a>b=%d\n",a>b);
not equal to printf(“a=b=%d \n",a>=b);
printf(“a<=b=%d\n",a<=b);
printi(‘a!
3. Logical Operators:
‘The logical && operator doesn't check second condition if first condition is
false. It checks second condition only if first one is true.
The logical | | operator doesn't check second condition if first condition is
true. It checks second condition only if first one is false‘Operator Symbol | Ex : a=21,b=4; Program output
Logical AND | && 18:81 = #include 1
#include oO
main() 0
oO
- 088050) clrscr(); 1
Logical OR I 1ffl=1 printi(®%d\n", 18801); 1
1| 10=: printf(“%d\n", 1880); 1
Olt printf(“%d \n” 08861); °
: oll printf{“%d \n” 0880); 1
Logical NOT! N=0 printi(‘%d\n",1 | | 1);
10=1
printf(“%d\n",1 | |);
printf(“%d\n”,0| | 1);
printf(*%d\n",0| |);
printf(“%d\n",!1);
printf(*%d\n”,10);
getch();
return 0;
i
4. Increment (++) Decrement (--) Operators:
The increment ( ++ ) and decrement (— ) operators in C are unary operators
for incrementing and decrementing the numeric values by 1 respectively
// AS PREFIX
+m
// 8S POSTFIX
mt+
Operator | Symbol | Ex Program Output
Increment | ++ iF; (post #include 1
increment) #include 3
++i; (pre main() 3
increment) { 1
Decrement | —- i; (post int i=1;
decrement) clrser();
--i; (pre printf{"%d\n",i++);
decrement) printf{’"%d\n",++i);
printf("%d\n
printf{"%d"
getch();
return 0;
yi5. Arithmetic Assignment Operators:
= is simple Assignment where as
Arithmetic Assignment operators
Operato
r
‘Example Program Output
5 #include a=30
a=a+b can be | #include
written as a+=b | main()
= a-a-bcanbe |!
written as a-=b | int a=10;
int b=20;
azarb canbe | ser
written as at=b | OFS!
a=a/b can be printi(“ =%d",a);
written as a/=b | Punter “eahalk
%e aza%b canbe | 1h":
2 pare a return 0;
nas
a%e=b ;
Note: Similarly we can use for Bit wise operators also called
bitwise Assignment
6. Bitwise Operators:
In G, the following 6 operators are bitwise operators (also known as bit
operators as they work at the bit-level). They are used to perform bitwise
operations in C.
Operator | Sym | ex: a=12,b=10 | Program Output
bol
Bitwise AND | & a&b=8 #include
BitwiseOR | | alb=14 #include 14
main()
Bit wise XOR | anb=6 { By
Left Shift << accel int a=12,b=10; a
Right Shift |>> | a>>1 clrscr();
printi(*%d\n",a&b);
Note: Unlike Logical AND, printf(“%d\n",a |b);
Logical OR here Bitwise AND printf(“%d\n",a%b);
and Bitwise OR checks printi(“%d\n",a<<1);
second condition when 1** printf(“%d\n",a>>1);
condition is TRUE or FALSE getch();
return 0;
4weead So
[2] °]1 | o}ew Tel] ew
2 eto 10) seas O70] 1] |) ‘pots
Feral Ferme
dasa ie, 2120 ‘ae, 3070'S
7. Ternary or Conditional Operator: ( ?: )
We use the ternary operator in C to run one code when the condition
is true and another code when the condition is false. For example,
(age >= 18) ? printf("Can Vote")
printf{"Cannot Vote"
Here, when the age is greater than or equal to 18, Can Vote is printed.
Otherwise, Cannot Vote is printed.
Syntax is given by,
ee oC BERS Crit2.1.2. Operators’ precedence & Associativity:
(Similar to BODMAS rule in mathematics)
‘To understand this concept let us consider a simple Expression
2+8*2 Here * have highest Precedence,
So, it got evaluated first 3
ie., 2416 then 18
So, operators’ precedence tells us which operator must evaluated 1*
Let’s see table from highest to lowest precedence.
High ‘OPERATOR TYPE ASSOCIAVITY
Ou. > left-to-right
71s oaisy Openia right-to-left
71% Arithmetic Operator | RAtto-isht
. ——— | ——
< > shift Operator Tefi-to-right
<= >> Relational Operator eerie
Relational Operator —
& Bitwise AND Operator ee
“ Bitwise EX-OR Operator | ftto-right
1 Biowise OR Operator — | ftt0-right
ae Logical AND Operator | ft-to-ight
1 Topical OR Operator | Flog
“Ternary Conditional Operator | _rightiolef
zs Assignment Operator | Tihe-tteft
Low é Comma Tef-to-right
Operator associativity is used when two operators of the same
precedence appear in an expression. Associativity can be either from Left
to Right or Right to Left.Example of Operator Associativity
Let's evaluate the following expression, 100 / 5 % 2
Both / (division) and % (Modulus) operators have the same precedence, so
the order of evaluation will be decided by associativity.
According to the given table, the associativity of the multiplicative
operators is from Left to Right. So,
(100 / 5) %2
After evaluation, the expression will be
20 % 2 Now, the % operator will be evaluated. 0.
2.1.3, Separators
A separator is a symbol that is used to separate a group of code from one
another
Name Symbol purpose
Used to enclose an argument in the function , Also used for
pees 0 defining the expression in control statement etc.,
ae 0 Used to oes ne pies oo Also used
Brackets 0 Used to declare an array type.
Semi colon : Used to separate or terminate the statement.
comma Used to separate identifiers (or) Variable declarations.
Period or dot : Used in structure and union variables
NOTE: semi colon; comma, and dot. are also called Punctuators2.1.4. Comment lines in C:
In programming, comments are hints
that a programmer can add to make their code comment
easier to read and understand
J [svat tine comment
1. A person reading a large code will be
bemused if comments are not provided .
BST acteais ar te oreo [7 watisine comment J | Cs
2. C Comments are a way to make a code
more readable by providing more
descriptions.
Types of Comments
// - Single Line Comment
In C, a single line comment starts with //. It starts and ends in the same
line
/*...*/ - Multi-line Comment
allows us to comment on multiple lines at once, they are multi-line
comments.
2.1.5. Keywords:
Y Keywords also known as reserved words or pre defined words that
have special meaning to compiler.
Ex: int a;
compiler allocates memory for variable a
¥ all keywords must be used in lower case only And white space not
allowed
auto break case char
const continue | default do
double else enum extern
float for goto if
int long register return
short signed sizeof static
struct switch typedef union
unsigned void volatile while2.1.5. Math Functions
There is also a list of math functions available, that allows you to perform
mathematical tasks on numbers. To use them, you must include
the math.h header file in your program: #inelude
Square Root .
To find the square root of a number, use the sqrt() function:
Example: printf ("%", sqrt(16)); // outputs 4.00
Round a Number
The ceill) function rounds a number upwards to its nearest integer, and
the floor() method rounds a number downwards to its nearest integer, and
returns the result:
Example
printf{"%6t", ceil(1.4));// outputs 2.00
printf{"%t", floor(1.4)}; // outputs 1.00
Power
‘The pow() function returns the value of x to the power of y (xy):
Example : printf("9%f", pow(4, 3)); // outputs 4°4*4= 64.00
Other functions under math.h are :
Function Description
abs(x) Returns the absolute value of x
acos(x) Returns the arccosine of x
asin(x) Returns the arcsine of x
atan(x) Returns the arctangent of x
cbrt(x) Returns the cube root of x
cos(x) Returns the cosine of x
exp(x) Returns the value of Ex2.1.6. Writing Simple sequential programs:
Every C program start executing from main() function then it will be
executed one line after another in a sequence , let us see some examples
Program 1:
Write a C program on Addition of 2 numbers?
rr (a
]/ Addition of 2 numbers
#include
#include
int main()
t
int n1,n2,sum;
clrscr();
printf(‘Enter 1st n
scanf{*%d”,&n1);
print{(‘Enter 2nd no:
scanf{*%d”,&n2);
sum=nl+n2;
print{(“Total = %d”,sum);
getch();
return 0;
}
Enter 1st no: 10
Enter 2nd no: 20
Total = 30
Program 2:
Bred
7/ Addition of 2 numbers
#include
#include
int main()
{
int n1,n2;
clrser();
printf(‘Enter Ist no:");
scanf(“%ed”,&n1);
printi(‘Enter 2nd no:”);
scanf("%d”,8n2);
printf(“Total = %d”,n1+n2);
getch();
return 0;
i
Write a C program on Addition of 2 numbers ( without using 3" variable)?
Enter 2nd no: 20
Total = 30Program 3:
Write a C program on Addition of 2 numbers (without using 3" variable &
cascading)?
Program
7/ Addition of 2 numbers
#include
#include
int main()
i ni,n2;
clrscr();
printf(“Enter 1st , 2nd nos;
scanf("%d%d",8sn 1 ,&n2);
printf(“Total = %d”,n1+n2);
getch();
return 0;
Cra
Enter Ist,2nd nos: 10 20
Total = 30
Program 4:
Write a C program on Ad
// Addition of 2 numbers
#include
#include
int main()
{
int nl=
clrscr();
printf(“Total = %d”,n1+n2);
getch();
return 0;
0,n!
ion of 2 numbers (using initialization)?
et Croats
‘Total = 30
Program 5:
ree
7/ Area of rectangle
#include
#include
int main()
x
int 1,b,a;
clrscr();
printf(‘Enter length:”);
scanf{“%d” &l);
print{(‘Enter breadth:”);
Write a C program on Area of rectangle (area= 1*b)?
rm
Enter length: 10
Enter breadth: 20scanil"%d",&b);
a=I*b;
printf(‘Area = %d”,a);
getch();
return 0;
Program 6:
// Area of circle
#include
#inchade
int main()
{
float r,a;
elrscr();
printf(‘Enter radius:”);
scant"! r);
printf(“Area = %f”,a);
getch();
return 0;
Write a C program for Area of circle (without using #define)
oe Cross
Enter radius: 5.0
Area= 78.500000
Program 7:
7/ Area of circle
#include
#include
#define PI 3.14
int main()
{
float r,a;
clrscr();
printi(“Enter radiu:
scant“ &r);
a=PI*r*r;
printf(“Area = %f",a);
getch();
return 0;
1
Write a C program for Area of circle (using #define}
re Output
0
Enter length: 5.
Area= 78.500000re
7/ simple interest
#include
#include
int main()
{
float p,t.r,sis
clrscr();
print{(“Enter principle amount:”);
scant“%t”,&p);
printf(‘Enter time period:”
scant("%r",&t);
print{(‘Enter rate of interest:”);
scant(‘%",&t);
*tr/ 100;
printi(‘Simple interest = %.2P',si);
getch();
return 0;
4
Program 9:
// Swapping of two number using third
/ [variable
#include
#include
int main()
‘Before swapping\n");
:%d\nB::%d",a,b);
printi("\nAfter swapping\n’);
printf("A::%d \nB::%d",a,b);
getch();
return 0;
Cia
Enter principle amount: 1
Enter time period: 1
Enter rate of interest: 1
Simple interest=0.01
Write aC un for sway f 2 numbers
eee Output
Before swapping
Az10
B::20
After swappingProgram 10:
Write a C program for swapping of 2 numbers (without using
Err
7* Swapping of two number without using Bebe swapping
third variable */ B20
‘ter awaping
#include Bao
#include
int main()
int a=10,b=20;
clrscr();
print{("Before swapping\n’);
printf("A::%d \nB::%d",a,b);
a=atb;
aza-b;
print{("\nAfter swapping\n’);
printi("A::%d \nB::%d",a,b);
getch();
return 0;
i
Example : ASCII values:(American Standard Code for Information
Interchange)
In C programming, a character variable holds ASCII value (an integer
number between 0 and 127) rather than that character itself. This integer
value is the ASCII code of the character.
For example, the ASCII value of ‘A’ is 65.
Program 11:
C program to print ASCII value of a given character
Program
Enter a character: A
#include ascii value for A is 65
#include
int main()
t
char ch;
clrscr();
printf(“Enter a character:
ch=getchar();
print{(“ascii value for %c is %d”,ch,ch);
getch();Program 12:
C program to calculate square root of a given number
Program
#include Enter a number: 9
#include Square root of 9 is 3
#include
ts main() &)
int n;
clrscr();
printf(‘Enter a number:”);
scanf("%d”,8n);
printf(‘Square root of %d is %d”,n,sqrt(n));
getch();
1‘These are also called selection statements or decision making statements
All of us has to take decisions every day based upon conditions
If condition is satisfied we call it as true statement
Else we call it as false statement
As we discussed earlier C program executes in a sequence but,
Some situations where programmers have to change the order of execution
of statements based on certain conditions which involve kind of decision
making statement
Here the list of Conditional statements in C language:
if
if else
if else if ladder
nested if
switch
oo
Simple if or if:
If test condition is true then statements inside block will be executed
i.e., it tells compiler to execute certain part of code only if particular test
condition is true
Syntax:
if(test condition)
d Cede after if
Bede
Example 1: C program to check positive
Era
#include Enter a number: 9
#include Positive number
int main()
t
int n;
clrscr();
print{(*Enter a number:
scanf(“%d”,8n);
if(n>0)
print{(‘Positive number”,n);
}
getch(); return 0; }if else: ( 2 way selection )
Here when test condition is true then true
executed otherwise false block statements.
Syntax:
i
c
// false statements
)
ree
7/ Entered number is positive or negative
#include
#inchade
int main()
{
int n;
clrser();
print{(‘Enter a number:”);
scanf(*%d”,&n);
ifjn>0)
printf(“Positive number’);
}
else
printf(“Negative number”);
}
getch();
return 0;
1
if(test condition) <> true
C
// true statements ‘
block statements will be
will be executed
false
Fala
Codeafrer |
‘fee block
eres
Enter a number: 9
Positive number
Output 2
Enter a number: -9
Negative number
// Voter is cligible for vote or not
#include
#include
int main()
a
int age;
clrscr();
printi(‘Enter your age:’);
scanf{"%d”,&age);
ifjage>=18)
Exat =
Program ras
Enter your age: 19
Eligible for vote
Output 2
at
printi(“Eligible for vote”);
1
else
nt
printf(“Not eligible”);
1
getch();
return 0;
Enter a number: 9
Not eligible
7/ biggest among 2 numbers
#include
#include
int main()
n
int a,b;
clrscr();
print{(‘Enter 2 numbers:”);
scanf{"%d%d" 8a, 8b);
iffa>b)
{
printi(‘%d is big’,a);
1
else
t
printf(“%d is big’,b);
1
getch();
return 0;
1
Example 3:
Be Output 1
Enter 2 numbers:19 5
19 is big
Output 2
Enter a number: 9 85,
85 is big
Example 4:
eit
7/ Given character is vowel or consonant,
#include
#include
int main()
t
char chy;
clrscr();
printf(“Enter a character:
ch = getchar();
if(ch=='a’| |
ch="A’| [cl
“uy
printi(‘vowel”);
}
rae
Enter a character:i
vowel
Output 2
Enter a character: Z
consonantelse
printf(“consonant”);
1
getch();
return 0;
1
Example 5:
Program
7/ Entered number is EVEN OR ODD
#include
#include
int main()
{
int n;
clrscr();
printf(“Enter a number:”);
scanf“%d”,8n);
if(n%2==0)
t
printi(“EVEN number’);
}
else
{
print{(“ODD number”);
1
getch();
return 0;
1
es
Enter a number: 9
ODD number
Output 2
Enter a number: 20
EVEN numberif else if ladder: ( multi way selection }
Here it will check one condition after another in a sequence
In that way if condition is true then corresponding statements will be
executed. and control goes to statements
At last if no condition is true then else block placed will be executed. and
after if else ladder block
control goes to statements after if else ladder block.
Syntax:
if(condition1)
€
// statementst
3
else if(condition2)
€
//statements2
3
else if(condition n)
{
//statements n
}
Statements 1
Sora
false
true
#include
int main()
t
int num;
clrscr();
print{("Enter a number:
scanf("%d" &num);
if(num>0)
{
print{('Positive number.");
1
else if(num<0)
printf("Negative number");
}
else
i
print{('ZERO");
}
true
<= Stotenertsn
false
Godeinside ele block
Cader False
ladder back
Cres
Enter a number: 9
Positive number
Output
Enter a number: -9
Negative number
Output 3:
Enter a number: 0
ZERO.getch();
return 0;
1
// Entered number to word
#include
#include
int main()
{
int num;
clrser();
printi("Enter single digit number:");
scanf("%d",&num);
if(rum==0)
printf("zero.");
else if(num==1)
printi(“one.")
}
else if(num==2)
printi("two.");
1
else if(num==3)
t
printf('three.");
}
else if{num
==4)
{
printi("fou:
+
else if{num==5)
{
printt"five.");
1
else if{(num==6)
printi("six.");
}
else if{num==7)
{
printf('seven.");
1
else if(num==8)
{
printf{"eight.");
Exai 2
rae erase
Enter single digit
number:5
five
Output 2:
Enter single digit
number:55
please enter single digit.
6else if{(num==9)
printf("nine.");
}
else
printi("please enter single digit."); :
}
getcht);
return 0;
}
Example: Electricity bill
Write aC program to input electricity unit charge and calculate the total
electricity bill according to the given condition:
Units Cost
0-50 0.50 per ui
‘50-100 0.75 per unit
100-250 1.20 per unit
‘Above 250 1.50 per unit
An additional surcharge of 20% is added to the bill.
ra Cres
#include Enter no.of units:100
#include Electricity bill =140.00
int main()
{
int units;
float amt, total;
clrscr();
printi(‘Enter no.of units:”);
scanf{*%d”,8units);
if(units>0&&units<50)
{
amt = units*0.50;
1
else if{units>=508éunits<100)
t
amt = units*0.75I
else if{units>=100&8éunits<250)
t
amt = units" 1.2(
1
else
at
amt = units*1.50; 7
}
total = amt + amt*0.20;
printi(“Electricity Bill
getch();
return 0;
}
%.2£" total);
nested if else:.
If one if condition is placed inside another if condition we call it as nested
if condition
‘The contained if statement is known as inner if statement and another is
known as outer if statement. The inner block of if statement will be
executed only if the outer block condition is true.
Stor
eahig, ~--n-yitatrnbin
fovea) vet Le ioe
“ee mr cin 1
inte) Ta aia true
— false
{
Ist
)
: ales etn
‘ioateuconated
Code after nested if block
re res
7/ biggest among 3 numbers
#include
#includeint main() 30 is big
{
int a,b,c;
clrscr();
printi(“Enter 3 numbers:”);
scanf("%d%d%d" a, 8b, 8c);
iffa>b)
ifla>o)
{
printf(*%d is big”,a);
1
else
t
printf(‘%d is big”,c);
3
}
else
{
if(b>c)
{
printf(“%d is big’,b);
1
else
t
printf(“%d is big’,c);
}
}
getch();
return 0;
1
switch:
switch case control statement is used to execute specific blocks of
statements in given number of blocks
it will compare the value of expression against list of integers or characters
the list of constants are listed using case along with break at the end of
execution
If no condition is satisfied then default statements will be executed
because user may enter unconditional data
Here the syntax for switch is given belowSyntax:
switch(expression) soem la
C
case constant:
statementsl; ‘Statenents 2
break: I fs
case constant2: \ '
statements2: !
break: 1
true
Stotenen
case constant:
statements n: alse
break: statenerts
default
default statements: Code after sitch block
break:
d
ia Cres
// Entered number to word
#include Enter single digit
#include number:5
int main() five.
{
int num;
clrscr(); . Output 2:
print{("Enter single digit number:"); Enter single digit
scanf{"%d" &num); number:55
switch(num) please enter single digit.
t
case
{
print{("zero.");
break;
}
case 1:
printf("one.");
break;
1
case 2:
printi("two.");
break;
hcase 3:
t
printi("three.");
break;
}
case 4:
print{("four.");
break;
1
case 5:
{
printf("five.");
break;
}
case 6:
{
printi("six.");
break;
1
case 7:
{
printf(’seven.”);
break;
1
case 8:
{
printi{"eight.”);
break;
}
case 9:
{
printf("nine.");
break;
1
default:
printi("please enter single digit.");
break;
1
getch();
return 0;
1Example 2: Simple calculator usi switch case
et aes
#include
int main()
{
int a,b,ch;
clrscr();
printi("
‘SIMPLE CALCULATOR---\n");
printi("Enter 2 numbers :");
scanf{"%d%d" , 8a, &b);
printf("Press\n1 for Addition \n2 for
Subtraction\n3 for Multiplication \n4 for
Divison \n’);
print{("Enter ur choic:
scanf"%d" ch);
switch(ch)
t
case 1:
printf("%d+%d=%d",a,b,a+b);
break;
case 2:
printi("%d-%d=%d" ,a,b,a-b);
break;
case 3:
print{("%d*%d=%d",a,b,a*b);
break;
case 4:
printf("%d /%d=%d",a,b,a/b);
break;
default:
printf("Wrong choice’);
1
getchi);
return 0;
SIMPLE CALCULATOR-
Enter 2 numbers: 10 5.
Press
1 for Addition
2 for Subtraction
3 for Multiplication
4 for Divison
Enter ur choice: 1
10+5=15
7This is also called iteration programming or repetition programming.
In C, when you want to execute a specific statement or statements block
number of times until given condition is true we need to use the following
v for fr
Y while 7
¥ do while or do loop
for loop:
for loop is used to execute when we know Number of repetitions before
starting Body of the loop
Syntax:
for(initialization:condition:updation)
{ Fale 4
// body of the loop Statements
} Statements
after for loop ie
tncrement/
Initialization: it holds starting value
of loop
Ex: i=l
Condition: checks up to which point
looping will be continued
Ex: i<=100
Decrement
Updation: updates value of initialized value either increment (++) or
decrement (--)
Ex: i++
ren Ces
// to print 1 to 100 using for
#include
#include
int main()
ft
int i
cirscr();
for(i=1;i<=100;i++)
BONE
{
printi{“%d\n”,i);
}
getch();
return 0; 100
1Example 2:
et eas
// to print 100 to 1 using for 100
#include 99
#include oe
int main()
fk
int i;
clrscr();
for(i= 100;i>=1;i--) oS
ft 4
printf(“%d\n",i); 3
1
getch(); 2
return 0; 1
I
Example 3:
// to print 5 table using for Sts
#include 5*2=10
#include 5*3=15
ia main() 5*4-20
int is 2
clrser();
for(i=1;i<=10;i++)
t :
Prine SYedctod\n" 8); 5*10=50
getch();
return 0;
}
Example 4: Prime number or not
What is a prime number?
The number which is divisible by itself and 1 with remainder 0 is called
prime number Example: 7
Let us see the implementation in C program
re Cre
7/ C program to check whether given no. is | Enter a number: 10
//prime or not 10 is not a prime
#include#include Output 2:
= main() Enter a number: 7
int inum,count=0; eae
clrscr();
printf(“Enter a number:
scanf(“%d”,8num);
for(i=1;i<-num;i+#)
{
if(num%i=-0)
{
count++;
1
1
if{count
2)
printi(“%d is prime”,num);
}
else
printf(“%d id not a prime *,num);
}
getch();
return 0;
4
while loop:
While loop is used when we don’t know number of repetitions before
starting body of the loop.
Looping will not be continued even at once when 1* condition is failed.
Syntax: False
while(condition)
{ Statements after
//body of the loop“
}
// to print 1 to 100 using whileBr res
#include
#include
int main()
{a
int i=1;
clrser(); *
while(i<=100) 75)
BONS
{
printf(“%d\n”,i);
its;
4
getch();
return 0; 100
h
Example 2: Palindrome what is a palindrome number?
Palindrome: ex: 121
If you consider above number from left side It result 1 next 2 next 1 from
right side also same called palindrome property of numbers
Ee Cres
#include
#include
e main() Not a palindrome
int num,temp,rev=0;
Enter a number: 123
clrscr(); Output 2:
printf("Enter a number:")};
sca te enc Enter a number: 121
temp=num; t
while(temp!=0) Palindrome
{
rev=rev*10;
rev=rev+temp%10;
temp=temp/ 10;
1
if{num==rev)
print{("Palindrome');
}
else
t
printi("Not a Palindrome");
1
getch();
return 0;
}do while or do loop:
Do while loop in C programming is used to execute body of the loop at
least once irrespective of given condition
Here it will execute body once and then checks the Condition
Body of the
loo,
Syntax:
ae True
{
Fal:
//body of the loop =
a Statements after
while(condition); do loop
Semi colon (;) after while condition in do loop is mandatory
re ees
7/ program to print 1 to 100 using do
#include
#include
int main()
1
2
3
4
printf(“%d\n",i);
its;
jwhile(i<=100);
getch(); 100
return 0;
1
Example 2: factorial of a given number
5! = 5*4*3*2*1 =120Program
ey
// program to find factorial of a given number
#include
#include
main()
d
int fact=1,counter;
clrscr();
printi("Enter a number:
scanf"%d" &counter);
do
{
fact*=counter--;
1
while(counter:
printi(“%d" fact);
getch();
return 0;
1
Enter a number: 5
120
Vs
While Loop
Do-While Loop
This is entry controlled loop. It
checks condition before entering into
loop
This is exit control loop. Checks
condition when coming out from
loop
‘The while loop may run zero or more
times
Do-While may run more than one
times but at least once.
‘The variable of test condition must
be initialized prior to entering into
the loop
The variable for loop condition
may also be initialized in the loop
also.
while(condition){
//statement
i
dof
//statement
}while(condition);There are 3 jump In loops supported by C language
Y break
Y continue
¥ goto
break:
when break statement encountered inside a loop the loop is immediately
terminated and program control goes to next statement.
Syntax:
break;
rary Cres
7/ use of break in C
#include
#include
int main()
ce
int i;
clrscr();
for(i=1;1<=10;i++)
{
ifli==5)
{
break;
BONE
4
printf(“%d\n”,i);
}
getch();
return
}
continue:
continue statement in c programming works some what like break
statement. Instead of forcing termination it forces the next iteration for the
loop skipping any code in between.
Syntax:
continue;re es
7/ use of continue in C
#include
#include
int main()
Ce
int is
clrscr();
for(i=1;i<=10;i++)
{
iffi==5)
79
OMNIA AWNHE
continue;
}
printf“%d\n”,i);
}
getch();
return 0;
}
goto:
goto statement in C programming takes control of program from one statement to other goto
labeled statement un conditionally
itis proposed that always not use goto statement because it increases readability of the program
Syntax: goto label1;
label2:
statements;
label1:
statements;
goto label2;
re Cres
7/ use of goto in C Welcome to c language
#include tutorials in ECT
#inchade
int main()
{
clrser();
print{("welcome ");
goto x;
y:
printf(" tutorials”);goto z;
x:
printf(" to c language ");
goto ys
z
printf(* in ECT”);
getch();
return 0;Assignment 5
Q: Write a C program on following?
— Biggest among 2 numbers using if else
— Biggest among 2 numbers using ternary operator (?:)
Signature of the FacultyAssignment 6
Q: Write a C program on following?
— Given character is vowel or consonant ( using if else)
> Given character is vowel or consonant ( using switch)
Signature of the Faculty
MBM MC UdeyAssignment 7
Q: What is nested for loop?
> Any 2 C programs to print any patterns using nested for
Signature of the Faculty
“SaaM/ Mc UdayAssignment 8
Q: write any 4 differences between break and continue?
> Program to print even numbers between 1 to 100 using continue
Signature of the Faculty
MBM MC Udey