0% found this document useful (0 votes)
30 views95 pages

CSF101 Unit-02-2

Uploaded by

PIYUSH GUPTA
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views95 pages

CSF101 Unit-02-2

Uploaded by

PIYUSH GUPTA
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 95

CSF101: Programming for Problem

Solving

Session: 2023-24

B. Tech 1st Semester

Unit-2: Arithmetic Expression, and


Conditional statements, Loops,
Expression
Course Instructor
Prabhjot Kaur
Assistant Professor, School of Computing
Operators
• Arithmetic operators (+, - , *, /, %)
• Relational operators (<, <=, >, >=, ==, !=)
• Logical operators (&&, ||, !)
• Assignment operators (+=, -=, *=, /=)
• Increment and decrement operators (++, --)
• Conditional operators (?:)
• Bitwise operators (&, |, ^, <<, >>)
• Special operators ()
Arithmetic Operators
• Arithmetic operators are used for mathematical calculation.
Operat Meaning Examp Description
or le
+ Addition a+b Addition of a and b
- Subtraction a–b Subtraction of b from a
* Multiplication a*b Multiplication of a and b
/ Division a/b Division of a by b
% Modulo division- a%b Modulo of a by b
remainder
Relational Operators
• Relational operators are used to compare two numbers and
taking decisions based on their relation.
• Relational expressions are used in decision statements such as
if, for, while etc…
Operator Meaning Example Description
< Is less than a<b a is less than b
<= Is less than or equal to a <= b a is less than or equal to b
> Is greater than a>b a is greater than b
>= Is greater than or equal a >= b a is greater than or equal to b
to
== Is equal to a=b a is equal to b
!= Is not equal to a != b a is not equal to b
Logical Operators
• Logical operators are used to test more than one condition and
make decisions.

Operat Meaning
or
&& logical AND (Both nonzero then true, either is zero
then false)
|| logical OR (Both zero then false, either is nonzero then
true)
a&&! a|| Logical NOT (Is greater than) Examples:
a\ b !a !b
b b 1. (a==b) && (b==c) will be true if a=b=c.
0 0 0 0 1 1 2. (a==b) && (b==c) will be false if the value
of even a single variable is different
0 1 0 1 1 0
1 0 0 1 0 1
1 1 1 1 0 0
1. Logical AND Operator ( && )
• If both operands are non zero then the condition becomes true. Otherwise, the result has a
value of 0.
• The return type of the result is int.
• Syntax: (operand_1 && operand_2)

// C program for Logical


// AND Operator
#include <stdio.h>

// Driver code
int main()
{
int a = 10, b = 20;
Output:
Both values are greater than 0
if (a > 0 && b > 0) {
printf("Both values are greater than 0\n");
}
else {
printf("Both values are less than 0\n");
}
return 0;
}
2. Logical OR Operator ( || )
• The condition becomes true if any one of them is non-zero. Otherwise, it returns false i.e., 0
as the value.
• Syntax: (operand_1 || operand_2)

// C program for Logical


// OR Operator
#include <stdio.h>

// Driver code Output:


int main() Any one of the given value
{ is greater than 0
int a = -1, b = 20;

if (a > 0 || b > 0) {
printf("Any one of the given value is "
"greater than 0\n");
}
else {
printf("Both values are less than 0\n");
}
return 0;
}
3. Logical NOT Operator ( ! )
• If the condition is true then the logical NOT operator will make it false and vice-versa.
• Syntax: !(operand_1 && operand_2) or !(Operand)
• Below is the truth table for the logical NOT operator.

// C program for Logical


// NOT Operator
#include <stdio.h>

// Driver code
int main()
{
int a = 10, b = 20;

if (!(a > 0 && b > 0)) {


// condition returned true but
// logical NOT operator changed
// it to false
printf("Both values are greater than 0\n");
}
else {
printf("Both values are less than 0\n");
}
return 0;
}
Assignment Operators
• Assignment operators (=) is used to assign the result of an
expression to a variable.
• Assignment operator stores a value in memory.
• C also supports shorthand assignment operators which
simplify operation with assignment.
Operat Meaning
or
= Assigns value of right side to left
side
+= a += 1 is same as a = a + 1
-= a -= 1 is same as a = a - 1
*= a *= 1 is same as a = a * 1
/= a /= 1 is same as a = a / 1
%= a %= 1 is same as a = a % 1
Increment and Decrement Operators
• Increment (++) operator used to increase the value of the variable by
one.
• Decrement (--) operator used to decrease the value of the variable by
Exampl Explanati
one. e on
x=100; After the execution,
x++; the value of x will be
101.
Exampl Explanati
e on
x=100; After the execution the
x--; value of x will be 99.
Increment and Decrement Operators (cont…)
Operator Description
Pre increment operator (++x) value of x is incremented before assigning it to the
variable on the left
Exampl Explanati Output
e on
Int x,p; First increment value x will be 11
x=10; of x by one then p will be 11
p=++x; assign.
Operator Description
Post increment operator (x++) value of x is incremented after assigning it to the
variable on the left
Exampl Explanati Output
e on
x=10; First assign value of x x will be 11
p=x++; then increment value. p will be 10
Conditional Operators
• A ternary operator is known as conditional operator.
• Syntax: exp1 ? exp2 : exp3
Working of the ? :
Operator
exp1 is evaluated first
if exp1 is true(nonzero) then
- exp2 is evaluated and its value becomes the value of the
expression
If exp1 is false(zero) then
- exp3 is evaluated and its value becomes the value of the
expression
Exampl Exampl
e e
m=2, n=3; m=2, n=3;
r=(m>n) ? m : r=(m<n) ? m :
n;
Explanati n;
Explanati
on on
Value of r will be Value of r will be
3 2
Bitwise Operators
• Bitwise operators are used to perform operation bit by bit.
• Bitwise operators may not be applied to float or double.

Operat Meaning
or
& bitwise AND
| bitwise OR
^ bitwise exclusive OR
<< shift left (shift left means multiply
by 2)
>> shift right (shift right means divide
by 2)
Bitwise Operators
8 = 1000 (In Binary) and 6 = 0110 (In
Binary)
Example: Bitwise & Example: Bitwise |
(AND) (OR)
int a=8, b=6, c; int a=8, b=6, c;
c = a & b; c = a | b;
printf("Output = %d", c); printf("Output = %d", c);
Output Output
0 14

Example: Bitwise << (Shift Example: Bitwise >> (Shift


Left) Right)
int a=8, b; int a=8, b;
b = a << 1; b = a >> 1;
printf("Output = %d", b); printf("Output = %d", b);
Output Output
16 (multiplying a by a power of 4 (dividing a by a power of two)
two)
Special Operators
Operat Meaning
or
& Address operator, it is used to determine address of the variable.
* Pointer operator, it is used to declare pointer variable and to get
value from it.
, Comma operator. It is used to link the related expressions together.
sizeof It returns the number of bytes the operand occupies.
. member selection operator, used in structure.
-> member selection operator, used in pointer to structure.
Expressions
• An expression is a combination of operators, constants and
variables.
• An expression may consist of one or more operands, and zero
or more operators to produce a value.
Operand Operand Operand
1 2 3

answer = a + b
* c;

Variable to store Operator Operand


the expression 1 2
value
Operator precedence
• Precedence of an operator is its priority in an expression for
evaluation.
• The operator with higher precedence is evaluated first and the
operator with the least precedence is evaluated last.
• Operator precedence is why the expression 5 + 3 * 2 is
calculated as 5 + (3 * 2), giving 11, and not as (5 + 3) * 2,
giving 16.
• We say that the multiplication operator (*) has higher
"precedence" or "priority" than the addition operator (+), so
the multiplication must be performed first.
Operator associativity
• Associativity is the left-to-right or right-to-left order for
grouping operands to operators that have the same
precedence.
• Operator associativity is why the expression 8 - 3 - 2 is
calculated as (8 - 3) - 2, giving 3, and not as 8 - (3 - 2), giving
7.
• We say that the subtraction operator (-) is "left associative", so
the left subtraction must be performed first.
• When we can't decide by operator precedence alone in which
order to calculate an expression, we must use associativity.
printf()
• printf() is a function defined in stdio.h file
• It displays output on standard output, mostly monitor
• Message and value of variable can be printed
• Let’s see few examples of printf
• printf(“ ”);
• printf(“Hello World”); // Hello World
• printf(“%d”, c); // 15
• printf(“Sum = %d”, c); // Sum = 15
• printf(“%d+%d=%d”, a, b, c); // 10+5=15
scanf()
• scanf() is a function defined in stdio.h file
• scanf() function is used to read character, string, numeric data
from keyboard
• Syntax of scanf
• scanf("%X", &variable);
• where %X is the format specifier which tells the compiler what type of data is in
a variable.
• & refers to address of “variable” which is directing the input value to a address
returned by &variable.
Format Supporte Example Description
specifier d
data
types
%d Integer scanf(“%d”, Accept integer value such as 1, 5, 25,
&a) 105 etc
%f Float scanf(“%f”, Accept floating value such as 1.5, 15.20

Decision Making or Conditional


Statement
Decision Making or Conditional Statement
• C program statements are executed sequentially.
• Decision Making statements are used to control the flow of
program.
• It allows us to control whether a program segment is executed
or not.
• It evaluates condition or logical expression first and based on
its result (either true or false), the control is transferred to
particular statement.
• If result is true then it takes one path else it takes another
path.
Relational Operators
• Relational Operator is used to compare two expressions.
• It gives result either true or false based on relationship of two
expressions.

Math C Meaning Example Result


> > is greater than 5 > 4 true
≥ >= is greater than or equal 5 >= 4 true
to
< < is less than 5 < 4 false
≤ <= is less than or equal to 5 <= 4 false
≠ != is not equal to 5 != 4 true
= == is equal to 5 == 4 false
Need of decision making

if number is odd
{
/* code */
}

else number is ev
en
{
/* code */
}
Decision Making Statements in C
Decision Making Statements
are
One way Decision: if (Also known as simple if)
Two-way Decision: if…else
Multi way Decision: if…else if…else if…else
Two-way Decision: ?: (Conditional Operator)
n-way Decision: switch…case

If statement
if
• if is single branch decision making statement.
• If condition is true, then only body will be executed.
Flowchart of if
• if is a keyword.
Syntax
if(condition)
{ False
// Body of the if
conditio
// true part n
}
True


WAP to print Zero if given number is 0
Outpu
Program
t
1 #include<stdio.h> Enter Number:0
2 void main() Zero
3 {
4 int a;
5 printf("Enter Number:");
6 scanf("%d",&a);
7 if(a == 0)
8 {
9 printf("Zero");
10 }
11 }
WAP to print Positive or Negative Number
Outpu
Program
t
1 #include<stdio.h> Enter Number:5
2 void main() Positive Number
3 {
Outpu
4 int a; t
5 printf("Enter Number:"); Enter Number:-5
6 scanf("%d",&a); Negative Number
7 if(a >= 0)
8 {
9 printf("Positive Number")
10 ;
11 }
12 if(a < 0)
13 {
14 printf("Negative Number")
15 ;
}
}
Modulus Operator
• % is modulus operator in C
• It divides the value of one expression (number) by the value of another expression
(number), and returns the remainder.
• Syntax: express1 % express2
• E.g.
• 7%2 Answer: 1
• 6%2 Answer: 0
• 25%10 Answer: 5
• 37%28 Answer: 9
WAP to print Odd or Even Number
Outpu
Program
t
1 #include<stdio.h> Enter Number:12
2 void main() Even Number
3 {
Outpu
4 int a; t
5 printf("Enter Number:"); Enter Number:11
6 scanf("%d",&a); Odd Number
7 if(a%2 == 0)
8 {
9 printf("Even Number");
10 }
11 if(a%2 != 0)
12 {
13 printf("Odd Number");
14 }
15 }

If..else statement
if...else
• if…else is two branch decision making statement
• If condition is true, then true part will be executed else false
part will be executed Flowchart of if…
• else is keyword else

True conditio False


Syntax n
if(condition)
{
// true part … …
}
else
{ …
// false part
}
WAP to print Positive or Negative Number using if…else

Outpu
Program
t
1 #include<stdio.h> Enter Number:5
2 void main() Positive Number
3 {
Outpu
4 int a; t
5 printf("Enter Number:"); Enter Number:-5
6 scanf("%d",&a); Negative Number
7 if(a >= 0)
8 {
9 printf("Positive Number")
10 ;
11 }
12 else
13 {
14 printf("Negative Number")
15 ;
}
}
WAP to print Odd or Even Number using if…else

Outpu
Program
t
1 #include<stdio.h> Enter Number:12
2 void main() Even Number
3 {
Outpu
4 int a; t
5 printf("Enter Number:"); Enter Number:11
6 scanf("%d",&a); Odd Number
7 if(a%2 == 0)
8 {
9 printf("Even Number");
10 }
11 else
12 {
13 printf("Odd Number");
14 }
15 }
WAP to find largest number from given 2 numbers
using if
Outpu
Program
t
1 #include<stdio.h> Enter Two Numbers:4
2 void main() 5
3 { 5 is largest
4 int a, b;
5 printf("Enter Two Numbers:");
6 scanf("%d%d",&a,&b);
7 if(a > b)
8 {
9 printf("%d is largest", a
10 );
11 }
12 if(a < b)
13 {
14 printf("%d is largest",
15 b);
}
}
WAP to find largest number from given 2 numbers
using if…else

Outpu
Program
t
1 #include<stdio.h> Enter Two Numbers:4
2 void main() 5
3 { 5 is largest
4 int a, b;
5 printf("Enter Two Numbers:");
6 scanf("%d%d",&a,&b);
7 if(a > b)
8 {
9 printf("%d is largest", a
10 );
11 }
12 else
13 {
14 printf("%d is largest",
15 b);
}
}
{ }
• If body of if contains only one statement then { } are not
compulsory
• But if body of if contains more than one statements then { }
are compulsory
if(a >= b) Both if(a >= b)
{ printf("%d is largest",
are
printf("%d is largest", a a);
); same
}

If…else if…else if…else


Ladder if
If…else if…else if…else
• if…else if…else if…else is multi branch decision making
statement.
• If first if condition is true then remaining if conditions will
not be evaluated.
• If first if condition is false then second if condition will be
evaluated and if it is true then remaining if conditions will not
be evaluated.
• if…else if…else if…else is also known as if…else if ladder
Syntax
if(condition-1)
statement-1;
else if(condition-2)
statement-2;
else
statement-3;
if…else if…else ladder flowchart

conditio False
n1

True conditio False


n2
… True Conditio False
n3
… True

… …
WAP to print Zero, Positive or Negative Number

Outpu
Program
t
1 #include<stdio.h> Enter Number:5
2 void main() Positive Number
3 {
Outpu
4 int a; t
5 printf("Enter Number:"); Enter Number:-5
6 scanf("%d",&a); Negative Number
7 if(a > 0)
8 printf("Positive Number")
9 ;
10 else if(a==0)
11 printf("Zero");
12 else
13 printf("Negative Number")
;
}

Nested if
Nested if
• If condition-1 is true, then condition-2 is evaluated. If it is true,
then statement-1 will be executed.
• If condition-1 is false, then statement-3 will be executed.
Syntax
if(condition-1)
{
if(condition-2)
{
statement-1;
}
else
{
statement-2;
}
}
else
{
statement-3;
}
Nested if flowchart

False conditio True


n1

Statemen conditio False


t3 n2

True
Statemen Statemen
t1 t2

Next
Statemen
t
WAP to print maximum from given three numbers
Program
1 void main(){ Outpu
2 int a, b, c; t
3 printf("Enter Three Numbers:" Enter Three Numbers:7
4 ); 5
5 scanf("%d%d%d",&a,&b,&c); 9
6 if(a>b) 9 is max
7 {
8 if(a>c)
9 printf("%d is max",a);
10 else
11 printf("%d is max",c);
12 }
13 else
14 {
15 if(b>c)
16 printf("%d is max",b);
17 else
18 printf("%d is max",c);
19 }
}

Conditional Operator
? : (Conditional Operator)
• The conditional works operator is similar to the if-else.
• It is also known as a ternary operator.
• It returns first value of expression (before colon(:)) if
expression is true and second value of expression if expression
is false.
Fals
Tru e
e
variable = Expression1 ? Expression2 : Express
ion3 Result
value Result
value
Conditional operator flowchart
• Here, Expression1 is the
True Expressio False condition to be evaluated.
n1 • If the condition(Expression1) is
True then Expression2 will be
Expressio Expressio executed and the result will be
n2 n3 returned.
Variable • Otherwise, if
condition(Expression1) is false
then Expression3 will be
executed and the result will be
returned.
WAP to find largest number from given 2 numbers
using ? :
Outpu
Program
t
1 #include<stdio.h> Enter Two Numbers:4
2 void main() 5
3 { 5 is largest
4 int a, b, max;
5 printf("Enter Two Numbers:");
6 scanf("%d%d",&a,&b);
7 max = a>b?a:b;
8 printf("%d is largest",max);
9 }

switch…case
switch...case
• The switch statement allows to execute one code block among many alternatives.
• It works similar to if...else..if ladder.

Syntax  The expression is evaluated once


switch (expression) and compared with the values of
{
​ each case.
case constant1:
// statements  If there is a match, the
break; corresponding statements after the
case constant2: matching case are executed.
// statements
break;  If there is no match, the default
. statements are executed.
.
.  If we do not use break, all
default: statements after the matching label
// default statements are executed.
}
 The default clause inside the
WAP that asks day number and prints day name
using switch…case
void main(){ case 7:
int day; printf("Saturday");
printf("Enter day number(1-7):"); break;
scanf("%d",&day); default:
switch(day) printf("Wrong input");
{ break;
case 1: }
printf("Sunday"); }
break;
case 2:
printf("Monday");
break;
case 3: Outpu
printf("Tuesday"); t
break; Enter day number(1-7):5
case 4: Thursday
printf("Wednesday");
break;
case 5:
printf("Thursday");
break;
case 6:
printf("Friday");
break;

Iteration and loops


What is loop?
• Loop is used to execute the block of code several times
according to the condition given in the loop. It means it
executes the same code multiple times.
“Hello” 5

Outpu
t
printf("Hello\n"); Hello
printf("Hello\n"); Hello loop(condition)
{
printf("Hello\n"); Hello //
printf("Hello\n"); Hello statements
}
printf("Hello\n"); Hello
Syntax and Logic
Swimming To
Rules Swim
1. Breath control
2. Kicking legs
3. Back stroke with arms
4. Front stroke with arms
5. Crawling in water

Syntax Logic
while(condition) int i = 1;
{ while (i <= 5)
// Body of the while {
// true part printf("%d\n", i);
} i=i+1;
}
if v/s while
v/
Flowchart of if s Flowchart of while

conditio False conditio False


n n
True True

… …
Looping or Iterative Statements in C
Looping Statements are
Entry Controlled Loop: while, for
Exit Controlled Loop: do…while
Virtual Loop: goto

While loop
While Loop
• while is an entry-controlled loop
• Statements inside the body of while are repeatedly executed
till the condition is true
• while is keyword
Synta
x
while(condition)
{
// Body of the while
// true part
}
WAP to print 1 to n(while loop)
Outpu
Program
t
1 #include <stdio.h> Enter n:10
2 void main() 1
3 { 2
4 int i,n; 3
5 i=1; 4
6 printf("Enter n:"); 5
7 scanf("%d",&n); 6
8 while(i<=n) 7
9 { 8
10 printf("%d\n",i); 9
11 i=i+1; 10
12 }
13 }
WAP to print multiplication table(while
loop)
Outpu
Program
t
1 #include<stdio.h> Enter n for multiplication
2 void main() table:5
3 { 5 * 1 = 5
5 * 2 = 10
4 int i=1,n;
5 * 3 = 15
5 printf("Enter n for multiplication table:") 5 * 4 = 20
6 ; 5 * 5 = 25
7 scanf("%d",&n); 5 * 6 = 30
8 while(i<=10) 5 * 7 = 35
9 { 5 * 8 = 40
10 printf("%d * %d = %d\n",n,i,n*i); 5 * 9 = 45
11 i=i+1; 5 * 10 = 50
12 }
}
WAP to Sum of 5 numbers entered by user(while
loop)
Outpu
Program
t
1 #include<stdio.h> Enter a number=10
2 void main() Enter a number=20
3 { Enter a number=30
Enter a number=40
4 int sum=0, i=1,n;
Enter a number=50
5 while(i<=5) Sum is=150
6 {
7 printf("Enter a number=");
8 scanf("%d",&n);
9 sum=sum+n;
10 i=i+1;
11 }
12 printf("Sum is=%d",sum);
13 }
WAP to find factors of a number(while
loop)
Outpu
Program
t
1 #include <stdio.h> Enter n to find factors=12
2 void main() 1,2,3,4,6,12,
3 {
4 int i=1,n;
5 printf("Enter n to find factors=");
6 scanf("%d",&n);
7 while(i<=n)
8 {
9 if(n%i==0)
10 printf("%d,",i);
11 i=i+1;
12 }
13 }
WAP to print reverse a number(while loop)
Outpu
Program
t
1 #include <stdio.h> Enter a number=1234
2 void main() 4321
3 {
4 int n;
5 printf("Enter a number=");
6 scanf("%d",&n);
7 while(n!=0)
8 {
9 printf("%d",n%10);
10 n=n/10;
11 }
12 }
WAP to check given number is perfect or not(while
loop)
1 void main(){
2 int i=1,n,sum=0; Outpu
3 printf("Enter a number:"); t
4 scanf("%d",&n); Enter a number:6
5 while(i<n) 1+2+3=6
6 is a perfect number
6 {
7 if(n%i==0) Outpu
8 { t
9 printf("%d+",i); Enter a number:8
1+2+4+=7
10 sum=sum+i;
8 is not a perfect number
11 }
12 i=i+1; Outpu
13 } t
Enter a number:496
14 printf("=%d",sum);
1+2+4+8+16+31+62+124+248+=496
15 if(sum==n) 496 is a perfect number
16 printf("\n%d is a perfect number",n);
17 else
18 printf("\n
19 %d is not a perfect number",n);
}
WAP to check given number is prime or not(while
loop)
1 void main()
2 { Outpu
3 int n, i=2,flag=0; t
4 printf("Enter a number:"); Enter a number:7
5 scanf("%d",&n); 7 is a prime number
6 while(i<=n/2)
7 { Outpu
8 if(n%i==0) t
9 { Enter a number:9
9 is not a prime number
10 flag=1;
11 break;
12 }
13 i++;
14 }
15 if (flag==0)
16 printf("%d is a prime number",n);
17 else
18 printf("%d is not a prime number",n);
19 }

for loop
for Loop
• for is an entry-controlled loop
• Statements inside the body of for are repeatedly executed till the condition is true
• for is keyword
Synta
x
for (initialization; condition; updateStatement)
{
// statements
}

 The initialization statement is executed only once.


 Then, the condition is evaluated. If the condition is false, the for loop is
terminated.
 If the condition is true, statements inside the body of for loop are
executed, and the update statement is updated.
 Again the condition is evaluated.
WAP to print numbers 1 to n (for loop)
Outpu
Program
t
1 #include<stdio.h> Enter a number:5
2 void main() 1
3 { 2
4 int i,n; 3
5 printf("Enter a number:"); 4
6 scanf("%d",&n); 5
7 for(i=1;i<=n;i++)
8 {
9 printf("%d\n",i);
10 }
11 }
WAP to find factors of a number (for loop)
Outpu
Program
t
1 #include <stdio.h> Enter n to find factors=12
2 void main() 1,2,3,4,6,12,
3 {
4 int i,n;
5 printf("Enter n to find factors=");
6 scanf("%d",&n);
7 for(i=1;i<=n;i++)
8 {
9 if(n%i==0)
10 printf("%d,",i);
11 }
12 }
WAP to check given number is perfect or not(for
loop)
1 void main(){
2 int i,n,sum=0; Outpu
3 printf("Enter a number:"); t
4 scanf("%d",&n); Enter a number:6
5 for(i=1;i<n;i++) 1+2+3=6
6 is a perfect number
6 {
7 if(n%i==0) Outpu
8 { t
9 printf("%d+",i); Enter a number:8
1+2+4+=7
10 sum=sum+i;
8 is not a perfect number
11 }
12 } Outpu
13 printf("=%d",sum); t
Enter a number:496
14 if(sum==n)
1+2+4+8+16+31+62+124+248+=496
15 printf("\n%d is a perfect number",n); 496 is a perfect number
16 else
17 printf("\n
18 %d is not a perfect number",n);
}

do while loop
do while Loop
• do while is an exit-controlled loop.
• Statements inside the body of do while are repeatedly executed till the condition is
true.
• Do and while are keywords.
Synta
x
do
{
// statement
}
while (condition);

 Loop body will be executed first, and then condition is checked.


 If the condition is true, the body of the loop is executed again and the
condition is evaluated.
 This process goes on until the condition becomes false.
 If the condition is false, the loop ends.
WAP to print Odd numbers between 1 to n(do while
loop)
Outpu
Program
t
1 void main() Enter a number:5
2 { 1,3,5
3 int i=1,n;
4 printf("Enter a number:");
5 scanf("%d",&n);
6 do
7 {
8 if(i%2!=0)
9 {
10 printf("%d,",i);
11 }
12 i=i+1;
13 }
14 while(i<=n);
15 }
WAP to find factors of a number(do while loop)

Outpu
Program
t
1 void main() Enter a number:6
2 { 1,2,3,6,
3 int i=1,n;
4 printf("Enter a number:");
5 scanf("%d",&n);
6 do
7 {
8 if(n%i==0)
9 {
10 printf("%d,",i);
11 }
12 i=i+1;
13 }
14 while(i<=n);
15 }
WAP to print reverse a number(do while
loop)
Outpu
Program
t
1 void main() Enter a number=1234
2 { 4321
3 int n;
4 printf("Enter a number:");
5 scanf("%d",&n);
6 do
7 {
8 printf("%d",n%10);
9 n=n/10;
10 }
11 while(n!=0);
12 }

goto statement
goto Statement
• goto is an virtual loop
• The goto statement allows us to transfer control of the program to the specified
label.
• goto is keyword

Synta Synta
x x
goto label label:
; .
. .
. .
. goto label
label: ;
 The label is an identifier. When the goto statement is encountered, the
control of the program jumps to label: and starts executing the code.
WAP to print Odd numbers between 1 to n(goto)

Outpu
Program
t
1 void main() Enter a number:5
2 { 1,3,5
3 int i=1,n;
4 printf("Enter a number:");
5 scanf("%d",&n);
6 odd:
7 if(i%2!=0)
8 {
9 printf("%d,",i);
10 }
11 i=i+1;
12 if(i<=n)
13 {
14 goto odd;
15 }
16 }
WAP to find factors of a number(goto)
Outpu
Program
t
1 void main() Enter a number:6
2 { 1,2,3,6,
3 int i=1,n;
4 printf("Enter a number:");
5 scanf("%d",&n);
6 odd:
7 if(n%i==0)
8 {
9 printf("%d,",i);
10 }
11 i=i+1;
12 if(i<=n)
13 {
14 goto odd;
15 }
16 }
Types of loops
Entry Control Entry Control Virtual
Exit Control Loop
Loop Loop Loop
int i=1; int i; int i=1; int i=1;
while(i<=10) for(i=1;i<=10;i++) do labelprint:
{ { { printf("%d",i+
printf("%d",i+ printf("%d",i); printf("%d",i+ +);
+); } +); if(i<=10)
} } goto labelprin
while(i<=10); t;

conditio False Loop Statemen


Label
n Body t
True True
Loop conditio conditio
n n
Body False True False
goto

Pattern
• Always detect pattern in pattern
Pattern
There are important points to note in pattern
1. Determine, how many rows?
2. Determine, how many numbers/characters/columns in a row?
3. Determine, Increment/Decrement among the number of
rows.
4. Determine, starting in each row
WAP to print given pattern (nested loop)
* Program
** 1 void main()
*** 2 {
**** 3 int i,j;
***** 4 for(i=1;i<=5;i++)
5 {
No. of rows: 5
6 for(j=1; j<=i; j++)
No. of characters 7 {
Row-1: * 8 printf("*");
Row-2: ** 9 }
Row-3: *** 10 printf("\n");
Row-4: **** 11 }
Row-5: ***** 12 }

Inner loop:
Increment
Outer loop:
Starting:
Increment*
WAP to print given pattern (nested loop)
1 Program
12 1 void main()
123 2 {
1234 3 int i,j;
12345 4 for(i=1;i<=5;i++)
5 {
No. of rows: 5
6 for(j=1; j<=i; j++)
No. of values 7 {
Row-1: 1 8 printf("%d",j);
Row-2: 12 9 }
Row-3: 123 10 printf("\n");
Row-4: 1234 11 }
Row-5: 12345 12 }

Inner loop:
Increment
Outer loop:
Starting:
Increment1
WAP to print given pattern (nested loop)
5 Program
54 1 void main()
543 2 {
5432 3 int i,j;
54321 4 for(i=5;i>0;i--)
5 {
No. of rows: 5
6 for(j=5; j>=i ; j-
No. of values 7 -)
Row-1: 5 8 {
Row-2: 54 9 printf("%d",j)
Row-3: 543 10 ;
Row-4: 5432 11 }
Row-5: 54321 12 printf("\n");
}
Inner loop: }
Decrement
Outer loop:
Decrement/Incremen
Starting:
t 5
WAP to print given pattern (nested loop)
Program
* 1 void main() First we need to print
2 { 4 spaces before
** 3 int i,j,k; printing *
4 for(i=1;i<=5;i++)
*** 5 {
No. of rows: 5 *
6 for(k=5;k>i;k--)
**** 7 { **
No. of values
**** 8 printf(" "); ***
Row-1: ----*
* 9 }
Row-2: ---** ****
Row-3: --*** 10 for(j=1;j<=i;j++) ****
11 { *
Row-4: -**** After printing spaces
Row-5: ***** 12 printf("*");
this inner loop prints
13 }
*
Inner loop: Decrement 14 printf("\n");
Outer loop: 15 }
Decrement/Increment 16 }
Starting: -(space)
Ending: *
The bitwise XOR operator is the most useful operator from a technical interview perspective.

It is used in many problems. A simple example could be “Given a set of numbers where all elements occur an even number of times
except one number, find the odd occurring number” This problem can be efficiently solved by just doing XOR to all numbers.

#include <stdio.h>

// Function to return the only odd


// occurring element
int findOdd(int arr[], int n)
{
int res = 0, i;
for (i = 0; i < n; i++)
res ^= arr[i];
return res;
} Output: The odd occurring element is 90

// Driver Method
int main(void)
{
int arr[] = { 12, 12, 14, 90, 14, 14,
14 };
int n = sizeof(arr) / sizeof(arr[0]);
printf("The odd occurring element is
%d ",
findOdd(arr, n));
return 0;
}
Type conversion
• Type conversion is converting one type of data to another
type.
• It is also known as Type Casting.
• There are two types of type conversion:
• Implicit Type Conversion
• This type of conversion is usually performed by the compiler, when necessary,
without any commands by the user.
• It is also called Automatic Type Conversion.
• Explicit Type Conversion
• These conversions
Example: are done explicitly by users
Implicit Type usingExplicit
Example: the pre-defined
Type functions.
Conversion Conversion
int a = 20; double a = 4.5, b = 4.6, c = 4.9;
double b = 20.5; int result = (int)da + (int)db +
printf("%lf", a + b); (int)dc;
printf("result
Output = %d", result);
Output
40.500000 12
getchar and putchar
Program
• getchar function reads a 1 #include <stdio.h>
single character from 2 void main( )
terminal. 3 {
4 int c;
• putchar function displays 5 printf("Enter a character: ");
6 /*
the character passed to it 7 Take a character as input */
on the screen. 8 c = getchar();
9 /* Display the character */
10 printf("Entered character is:
11 ");
putchar(c);
Outpu
}
t
Enter a character: a
Entered character is: a
gets and puts
Program
• gets function reads a line 1 #include <stdio.h>
from stdin into the buffer 2 void main( )
pointed to by s until either 3 {
4 /
a terminating newline or 5 *Character array of length 100*/
EOF (End of File) occurs. 6 char str[100];
7 printf("Enter a string: ");
• puts function writes the 8 /* Take a string as input */
string 's' and 'a' trailing 9 gets( str );
10 /* Display the string */
newline to stdout. 11 printf("Entered string is: ");
12 puts( str );
}
Outpu
t
Enter a string: india
Entered string is: india
Preprocessor
• Preprocessors are programs that process our source code before
compilation.
• There are a number of steps involved between writing a program and
executing a program in C.
• Let us have a look at these steps before we actually start learning about
Preprocessors.
C Program

Objec Executabl
Are there No
t e Code
preprocess Compiler Code Linker
or directive

Yes
Preprocessor perform
action
Macros
• A macro is a fragment of code which has been given a name.
Whenever the name is used in program, it is replaced by the
contents of the macro.
• Macro definitions are not variables and cannot be changed by
your program code like variables.
• The ‘#define’ directive is used to define a macro.
• Do not put a semicolon ( ; ) at the end of #define statements.
• There are two types of macros:
• Object-like Macros
• Function-like Macros
Macros
Descripti Object-like Macros Function-like Macros
on
Definition The object-like macro is an identifier The function-like macro looks like
that is replaced by value. function call.
Use It is used to represent numeric It is used to represent function.
constants.
Syntax #define CNAME value #define CNAME (expression)
Example #define PI 3.14 #define MIN(a,b) ((a)<(b)?(a):(b))
Program 1 #include <stdio.h> 1 #include <stdio.h>
2 #define PI 3.14 2 #define MIN(a,b) ((a)<(b)?(a):
3 void main() 3 (b))
4 { int r=2; 4 void main()
5 float a; 5 {
6 a=PI*r*r; 6 printf("%d", MIN(2, 5));
7 printf("%f", a); }
8 }

You might also like