SlideShare a Scribd company logo
Module – 2
Operators, Decision Control and
Looping Statements
Operators
 Arithmetic Operators
 Logical Operators
 Bitwise Operators
 Ternary Operators
Some more Arithmetic Operators
 Prefix Increment : ++a
example: int a=5;
b=++a; // value of b=6; a=6;
 Postfix Increment: a++
example: int a=5;
b=a++; // value of b=5; a=6;
Continued…
 Modulus (remainder): %
example:
12%5 = 2;
 Assignment by addition: +=
example:
int a=4;
a+=1; //(means a=a+1) value of a becomes 5
Can use -, /, *, % also
Continued…
 Comparison (Relational ) Operators:
<, > , <=, >= , !=, ==
 Logical Operators: !, &&, ||
example:
int a=4, b=5;
a<b returns a true(non zero number) value.
 Bitwise Operators: <<, >>, ~, &, | ,^ .
example:
int a=8;
a= a>>1; // value of a becomes 4
6
Logical Operators
i) 3 + 4*5 - 6/3*4/8 + 2*6 - 4*3*2
ii) -1.5+2.0*3.5-5.0/2.5+1.25
Truth Table For Bit Wise Operation
& – Bitwise AND
| – Bitwise OR
~ – Bitwise NOT
^ – XOR
<< – Left Shift
>> – Right Shift
Operator Precedence
 Meaning of a + b * c ?
is it a+(b*c) or (a+b)*c ?
 All operators have precedence over each other
 *, / have more precedence over +, - .
If both *, / are used, associativity comes into picture. (more on this later)
example : 5+4*3 = 5+12= 17.
Conditional Or Ternary Operators
 Conditional operators return one value if condition is true and returns
another value is condition is false.
 This operator is also called as ternary operator.
Syntax : (Condition? true_value: false_value);
Example : (A > 100 ? 0 : 1);
Precedence Table
Highest on top
++ -- (Postfix)
++ -- (Prefix)
* / %
+ -
<< >>
< >
&
|
&&
||
8 0 6 12
Evaluate Arithmetic Expression
x = 2 * 3 / 4 + 4 / 4 + 8 - 2 + 5 / 8;
a = 7 / 22 * ( 3.14 + 2 ) * 3 / 5 ;
b = 4 + 2 % - 8 ;
c = ( 10 * 2 ) ( 3 + ( 2.5 + 6 ) ( 4 + 18 ) ;
13
Data types and their sizes
14
Data types and their sizes
15
16
Operation Result Operation Result
5 / 2 2 2 / 5 0
5.0 / 2 2.5 2.0 / 5 0.4
5 / 2.0 2.5 2 / 5.0 0.4
5.0 / 2.0 2.5 2.0 / 5.0 0.4
Integer and float conversion
17
Integer and float conversion
k is integer variable and a is a real variable
ASCII Codes
18
19
20
#include <stdio.h>
int main()
{
char c;
printf("Enter a character: ");
// Reads character input from the user
scanf("%c", &c);
// %d displays the integer value of a character
// %c displays the actual character
printf("ASCII value of %c = %d", c, c);
return 0;
}
Print ASCII Value
Output ?
#include<stdio.h>
void main( )
{
int a, b ;
a = -4 - - 4 ;
b = -4 - - ( - 4 ) ;
printf ( "a = %d b = %d", a, b ) ;
}
Type Conversion
 Converting the value of one data type (int, float, double, etc.) to
another data type.
 This process is known as type conversion.
C Example
#include <stdio.h>
int main()
{
int number = 34.78;
printf("%d", number);
return 0;
}
// Output: 34
 There are two types of type conversion:
Implicit Conversion
Explicit Conversion
 In implicit type conversion, the value of one type is automatically
converted to the value of another type.
 In explicit type conversion, we manually convert values of one
data type to another type.
Implicit type conversion example
#include<stdio.h>
int main ( )
{
// character variable
char alphabet = 'a';
printf("Character Value: %cn", alphabet);
// assign character value to integer variable
int number = alphabet;
printf("Integer Value: %d", number);
return 0;
}
Explicit type conversion example
#include<stdio.h>
int main() {
// create an integer variable
int number = 35;
printf("Integer Value: %dn", number);
// explicit type conversion
double value = (double) number;
printf("Double Value: %.2lf", value);
return 0;
}
C –Type Casting
 Converting one datatype into another is known as type casting
or, type-conversion. For example, if you want to store a 'long'
value into a simple integer then you can type cast 'long' to 'int’.
 You can convert the values from one type to another explicitly
using the cast operator as follows − (type_name) expression
C Program for floating-point operation
#include <stdio.h>
main ( )
{
int sum = 17, count = 5;
double mean;
mean = (double) sum / count;
printf("Value of mean : %fn", mean );
}
 Integer promotion is the process by which values of integer type "smaller"
than int or unsigned int are converted either to int or unsigned int.
Usual Arithmetic Conversion
 The usual arithmetic conversions are implicitly performed to cast their
values to a common type. The compiler first performs integer promotion; if
the operands still have different types, then they are converted to the type
that appears highest in the following hierarchy −
//C Program of adding a character with an integer
#include <stdio.h>
main() {
int i = 17;
char c = 'c'; /* ascii value is 99 */
int sum;
sum = i + c;
printf("Value of sum : %dn", sum );
}
Control Statements or Flow Control
 Sequence Control Statements
 Decision Control Statements
 Loop Control Statements
 Case Control Statements
Decision Control Statements
Perform different set of actions based on the situation.
1. if
2. if else
3. switch
The if statement
if ( this condition is true )
execute this statement ;
if ( this condition is true )
{
execute this block;
}
The if statement
if ( this condition is true )
execute this statement ;
if ( this condition is true )
{
execute this block;
}
36
void main ( )
{
int n ;
printf ( "Enter a number n" ) ;
scanf ( "%d", &n ) ;
if ( n < =100 )
printf ( “The number is less than or equal to 100" ) ;
}
The if statement example
The if-else statement
if ( this condition is true )
execute this statement ;
else
execute this statement ;
if ( this condition is true )
{
execute this block;
}
else
{
execute this block;
}
38
void main( )
{
int n ;
printf ( "Enter a number n" ) ;
scanf ( "%d", &n ) ;
if ( n <= 100 )
printf ( “The number is less than or equal to 100" ) ;
else
printf ( “The number is greater than 100" ) ;
}
The if-else example
The if-else statement
if ( this condition is true )
execute this statement ;
else
execute this statement ;
if ( this condition is true )
{
execute this block;
}
else
{
execute this block;
}
The else-if statement
if ( expression )
execute this statement ;
else if ( expression )
execute this statement ;
else if ( expression )
execute this statement ;
else if ( expression )
execute this statement ;
else
execute this statement ;
Multi-way
decision
Note:
Last else is
optional
Nesting of if-else statements
if (expression1)
{
// code to be executed
if (expression2)
{
// code to be executed
// if condition2 is true
}
}
Switch case statements
switch( expression )
{
case value-1: Block-1;
break;
case value-2: Block-2;
break;
…………………
case value-n: Block-n;
break;
default:
Block-1;
break;
}
Statement-x; Note: default is optional
expression can
be integral or
character
43
#include <stdio.h>
int main()
{
int x;
printf (“Enter your choice”);
scanf (“%d”,&x);
switch (x)
{
case 1: printf("Choice is 1");
break;
case 2: printf("Choice is 2");
break;
case 3: printf("Choice is 3");
break;
default: printf("Choice other than 1, 2 and 3");
break;
}
return 0;
}
Switch case example
44
switch ( marks / 10 )
{
case 4 :
case 5 : grade = ‘D’; break;
case 6 :
case 7 : grade = ‘C’; break;
case 8 :
case 9 : grade = ‘B’; break;
case 10 : grade = ‘A’; break;
default : grade = ‘F’; break;
}
Switch case example
Difference between if-else and switch
 “If-else” can evaluate float conditions, “switch” cannot.
 “If-else” can evaluate relational operators, “switch” cannot.
Switch Examples
 Write a C program to print day of week name using switch case.
 Write a C program to print number of days in a month using
switch case.
 Write a C program to find maximum between two numbers using
switch case.
 C program to check positive negative or zero using switch case.
47
int main ( )
{
int num;
printf("Enter any number: ");
scanf("%d", &num);
switch (num > 0)
{ // Num is positive
case 1: printf("%d is positive.", num); break; // Num is either negative
or zero
case 0: switch (num < 0)
{
case 1: printf("%d is negative.", num);
break;
case 0: printf("%d is zero.", num); break; }
break;
}
return 0;
}
Program to check positive or negative or zero using switch
Example program
 A commercial bank has introduced an incentive of giving bonus to all
its deposit holders. The policy is as follows: A bonus of 2 percent of the
balance held is given to every one and 5 percent is given to female
account holders if their balance is more than Rs.5000.
 Note: Take gender using character variable. Example M means male
and F means female.
 Inputs : Balance amount and the gender
 Output: bonus and balance after adding bonus
The else-if statement
if ( expression )
execute this statement ;
else if ( expression )
execute this statement ;
else if ( expression )
execute this statement ;
else if ( expression )
execute this statement ;
else
execute this statement ;
Multi-way
decision
Note: Last else is
optional
50
The else-if flowchart
Example Program
 Write a C program to input marks of five subjects Physics,
Chemistry, Biology, Mathematics and Computer. Calculate
percentage and grade according to following:
Percentage >= 90% : Grade A
Percentage >= 80% : Grade B
Percentage >= 70% : Grade C
Percentage >= 60% : Grade D
Percentage >= 40% : Grade E
Percentage < 40% : Grade F
52
switch ( avg_marks / 10 )
{
case 0 :
case 1 :
case 2 :
case 3 : grade = ‘F’; break;
case 4 :
case 5 : grade = ‘E’; break;
case 6 : grade = ‘D’; break;
case 7 : grade = ‘C’; break;
case 8 : grade = ‘B’; break;
case 9 :
case 10 : grade = ‘A’; break;
default : grade = ‘F’; break;
}
Switch case example
The ? : operator
 Ternary operator is used for decision making in place of conditional
statements if and else.
 Takes three arguments.
conditional_expression ? value_if_true : value_if_false
int a = 10, b = 20, c;
if (a < b)
{ c = a;
}
else
{ c = b;
}
printf("%d", c);
int a = 10, b = 20, c;
c = (a < b) ? a : b;
printf("%d", c);
Example Program
Consider the weekly salary of a sales guy who is selling some products. If x
is the number of products sold in a week, his weekly salary is given by
4x+100 for x<40
Salary = 300 for x=40
4.5x+150 for x>40
Iterative statements
Loops in C
A sequence of statements are executed until some conditions for
termination is satisfied.
Two parts:
1. Body of
the loop
2. Control
statement
Looping process steps
1. Setting and initialization of the condition variable
2. Execution of the statements in loop
3. Test for a specified value of the condition variable for execution of
the loop
4. Incrementing or updating the condition variable
Three types of loops
 The while statement
 The do-while statement
 The for statement
The while statement
 Entry controlled loop statement
 The test condition is evaluated and if the condition is true, then the body of
the loop is executed.
while (test condition)
{
// statements inside the body of the loop
}
Print numbers from 1 to 5
60
#include <stdio.h>
int main()
{
int i = 1; // Initialization
while (i <= 5) // Testing
{
printf("%dn", i);
i++; // Incrementing
}
return 0;
}
While examples
 Write a C program to find the sum of all integers between 1 and 10.
 Write a C program to find the sum of squares of all integers between 1
and 10.
 Write a program to evaluate the equation y=xn where n is a non
negative integer.
The do while statement
 Exit controlled loop statement.
 The body of the loop is executed first.
 At the end of the loop, the test condition is evaluated.
do
{
// statements inside the body of the loop
}
while (test condition);
Program to add numbers until the user enters zero
63
#include <stdio.h>
void main()
{
double number, sum = 0;
// the body of the loop is executed at least once
do
{
printf("Enter a number: ");
scanf("%lf", &number);
sum += number;
}
while(number != 0.0);
printf("Sum = %.2lf",sum);
}
The for statement
Entry controlled loop, more concise loop control structure.
1. Initialization of the control variables is done first. Ex: i=0, count=0 (loop
control variables)
2. The value of the control variable is tested using the test condition. Ex:
i<10
3. When the body of the loop is executed, control is transferred back to for
statement. The control variable is incremented/updated using an
assignment statement. Ex: i=i+1
for (initialization; test_condition ; increment)
{
// statements inside the body of loop
}
Flow chart of for statement
65
Print numbers from 0 to 10
#include <stdio.h>
int main()
{
int i;
for (i = 0; i <= 10; ++i)
{
printf("%d ", i);
}
return 0;
}
For loop examples
 Write a C program to find the sum of all integers between 1 and 10.
 Write a C program to find the sum of squares of all integers between 1
and 10.
 Write a program to evaluate the equation y=xn where n is a non
negative integer.
 Write a program to find the factorial of a number.
 Write a program to find the gcd of two numbers.
 Write a program to print first 10 multiples of 5.
 C program to add digits of a number:
Loop Control Statements
Loop control statements change execution from its normal
sequence.
Control Statement & Description
break statement
Terminates the loop or switch statement and transfers execution to the
statement immediately following the loop or switch.
continue statement
Causes the loop to skip the remainder of its body and immediately
retest its condition prior to reiterating.
goto statement
Transfers control to the labeled statement.
69
break statement
70
// Program to calculate the sum of a maximum of 10 numbers
// If a negative number is entered, the loop terminates
void main()
{
int i;
double number, sum = 0.0;
for(i=1; i <= 10; ++i)
{
printf("Enter a n%d: ",i);
scanf("%lf",&number);
// If the user enters a negative number, the loop ends
if(number < 0.0)
{
break;
}
sum += number; // sum = sum + number;
}
printf("Sum = %.2lf",sum);
}
71
continue statement
72
// Program to calculate the sum of a maximum of 10 numbers
// Negative numbers are skipped from the calculation
void main()
{
int i;
double number, sum = 0.0;
for(i=1; i <= 10; ++i)
{
printf("Enter a n %d: ",i);
scanf("%lf",&number);
if(number < 0.0)
{
continue;
}
sum += number; // sum = sum + number;
}
printf("Sum = %.2lf",sum);
}
73
break continue
A break can appear in both switch and loop
(for, while, do) statements.
A continue can appear only in loop
(for, while, do) statements.
A break causes the switch or loop statements
to terminate the moment it is executed. Loop
or switch ends abruptly when break is
encountered.
A continue doesn't terminate the loop, it
causes the loop to go to the next iteration. All
iterations of the loop are executed even
if continue is encountered.
The continue statement is used to skip
statements in the loop that appear after
the continue.
The break statement can be used in
both switch and loop statements.
The continue statement can appear only in
loops. You will get an error if this appears in
switch statement.
When a break statement is encountered, it
terminates the block and gets the control out
of the switch or loop.
When a continue statement is encountered, it
gets the control to the next iteration of the
loop.
A break causes the innermost enclosing loop
or switch to be exited immediately.
A continue inside a loop nested within
a switch causes the next loop iteration.
Infinite Loop
 A loop becomes an infinite loop if a condition never becomes false.
 The for or while loop is traditionally used.
 Most of the time we create infinite loops by mistake.
 Commonly used in programs that keep running for long periods of time
until they are stopped.0
#include <stdio.h>
int main ()
{
for( ; ; ) // or while(1)
{
printf("This loop will run forever.n");
}
return 0;
}
75
Infinite Loop mistakes
76
int choice;
while(1)
{
printf(“1.Create databasen”);
printf(“2.Insert new recordn”);
printf(“3.Modify a recordn”);
printf(“4.Delete a recordn”);
printf(“5.Display all recordsn”);
printf(“6.Exitn”);
printf(“Enter your choice : “);
scanf(“%d”,&choice);
switch(choice)
{
case 1: printf(“Database created…..nn”); break;
case 2:printf(“Record inserted…..nn”);break;
case 3:printf(“Record modified…..nn”);break;
case 4:printf(“Record deleted…..nn”);break;
case 5:printf(“Records displayed…..nn”);break;
case 6:exit(1);
default:printf(“Wrong choicen”);
}
}
Infinite Loop example
Programming Examples
 Given a number n, print triangular pattern. We are allowed to
use only one loop.
Programming Examples
• Given a positive integer n. Print the inverted
triangular pattern.
Roots of a quadratic equation
 a, b and c are known values. a can't be 0.
 "x" is the variable or unknown.
Discriminant
 b2 − 4ac in the formula is called the Discriminant, because it can
"discriminate" between the possible types of answer:
 when b2 − 4ac is
 positive, we get two Real solutions
 Zero, we get just ONE real solution (both answers are the same)
 Negative, we get a pair of Complex solutions
 Ex: 5x2 + 6x + 1 = 0, Solution x = −0.2 or −1
Algorithm: Quadratic Equation
81
Step 1: Start
Step 2: Read the values of non-zero coefficients a,b and c.
Step 3: Compute the value of discriminant (disc) which is equal to (b*b-4*a*c).
Step 4: Check if disc is equal to 0. If true, then go toStep 5. Otherwise, go to Step 6
Step 5: Compute the roots.
root1 = (-b)/ (2*a) , root2=root1
Output the values of roots, root1 and root2. Go to Step 9.
Step 6: Check if disc is greater than zero or not. If true, then go to Step 7.Otherwise,
go to Step 8.
Step 7: Compute the real and distinct roots, root1 = (-b+sqrt(disc))/(2*a)
root2 = (-b-
sqrt(disc))/(2*a)
Output the values of roots, root1 and root2. Go to Step 9.
Step 8: Compute the complex and distinct roots.
Compute the real part, r_part = (-b)/(2*a)
Compute the imaginary part, i_part = sqrt(-disc)/(2*a)
Output roots as root1 = r_part + i_part
root2 = r_part – i_part
Step 9: Stop
82
Palindrome
int main()
{
int num,rev=0,rem,temp;
printf("Enter a number : ");
scanf("%d",&num);
temp = num;
while(num != 0)
{
rem=num%10;
rev= rev*10+rem;
num = num / 10;
}
printf("n The reverse of given number is %d ",rev);
if(temp==rev)
printf("n The given number %d is a Palindrome",temp);
else
printf("n The given number %d is not a Palindrome",temp);
}
Binomial coefficient
 The binomial theorem describes the algebraic expansion of powers of
a binomial.
 According to the theorem, it is possible to expand the
polynomial (x + y)n into a sum involving terms of the form axbyc
 where the exponents b and c are nonnegative integers with b + c = n,
and
 the coefficient a of each term is a specific positive integer depending
on n and b.
 The coefficient a in the term of axbyc is known as the binomial
coefficient.
 These coefficients for varying n and b can be arranged to form Pascal's
triangle.
 For example (for n = 4)
Binomial coefficient
85
86
Pascal’s Triangle
Pascal’s Triangle
87
The goto statement
 To branch unconditionally from one point to another in the program.
 Requires a label in order to identify the place where the branch is to be
made.
 A label is any valid variable name followed by a colon.
goto label;
-----
-----
label:
statement;
label:
statement;
-----
-----
goto label;
Example Program
main()
{
double a,b;
read:
printf(“Enter a number greater than 0n”);
scanf(“%f”,&a);
if(a<0)goto read;
b= sqrt(a);
printf(“square root=%f”,b);
}
Thank you

More Related Content

Similar to M2 (1).pptxisedepofengiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii

ICP - Lecture 7 and 8
ICP - Lecture 7 and 8ICP - Lecture 7 and 8
ICP - Lecture 7 and 8
Hassaan Rahman
 
C Unit-2.ppt
C Unit-2.pptC Unit-2.ppt
C Unit-2.ppt
Giri383500
 
C important questions
C important questionsC important questions
C important questions
JYOTI RANJAN PAL
 
C Programming
C ProgrammingC Programming
C Programming
Raj vardhan
 
An imperative study of c
An imperative study of cAn imperative study of c
An imperative study of c
Tushar B Kute
 
Control structure of c
Control structure of cControl structure of c
Control structure of c
Komal Kotak
 
Dti2143 chap 4 control statement part 2
Dti2143 chap 4 control statement part 2Dti2143 chap 4 control statement part 2
Dti2143 chap 4 control statement part 2
alish sha
 
C tutorial
C tutorialC tutorial
C tutorial
Anurag Sukhija
 
What is c
What is cWhat is c
What is c
Nitesh Saitwal
 
Claguage 110226222227-phpapp02
Claguage 110226222227-phpapp02Claguage 110226222227-phpapp02
Claguage 110226222227-phpapp02
CIMAP
 
C Operators and Control Structures.pdf
C Operators and Control Structures.pdfC Operators and Control Structures.pdf
C Operators and Control Structures.pdf
MaryJacob24
 
C tutorial
C tutorialC tutorial
presentation_data_types_and_operators_1513499834_241350.pptx
presentation_data_types_and_operators_1513499834_241350.pptxpresentation_data_types_and_operators_1513499834_241350.pptx
presentation_data_types_and_operators_1513499834_241350.pptx
KrishanPalSingh39
 
Control statements-Computer programming
Control statements-Computer programmingControl statements-Computer programming
Control statements-Computer programming
nmahi96
 
C faq pdf
C faq pdfC faq pdf
C faq pdf
DebiPanda
 
Elements of programming
Elements of programmingElements of programming
C PROGRAMMING p-3.pptx
C PROGRAMMING p-3.pptxC PROGRAMMING p-3.pptx
C PROGRAMMING p-3.pptx
D.K.M college for women
 
C C++ tutorial for beginners- tibacademy.in
C C++ tutorial for beginners- tibacademy.inC C++ tutorial for beginners- tibacademy.in
C C++ tutorial for beginners- tibacademy.in
TIB Academy
 
the refernce of programming C notes ppt.pptx
the refernce of programming C notes ppt.pptxthe refernce of programming C notes ppt.pptx
the refernce of programming C notes ppt.pptx
AnkitaVerma776806
 
Branching statements
Branching statementsBranching statements
Branching statements
ArunMK17
 

Similar to M2 (1).pptxisedepofengiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii (20)

ICP - Lecture 7 and 8
ICP - Lecture 7 and 8ICP - Lecture 7 and 8
ICP - Lecture 7 and 8
 
C Unit-2.ppt
C Unit-2.pptC Unit-2.ppt
C Unit-2.ppt
 
C important questions
C important questionsC important questions
C important questions
 
C Programming
C ProgrammingC Programming
C Programming
 
An imperative study of c
An imperative study of cAn imperative study of c
An imperative study of c
 
Control structure of c
Control structure of cControl structure of c
Control structure of c
 
Dti2143 chap 4 control statement part 2
Dti2143 chap 4 control statement part 2Dti2143 chap 4 control statement part 2
Dti2143 chap 4 control statement part 2
 
C tutorial
C tutorialC tutorial
C tutorial
 
What is c
What is cWhat is c
What is c
 
Claguage 110226222227-phpapp02
Claguage 110226222227-phpapp02Claguage 110226222227-phpapp02
Claguage 110226222227-phpapp02
 
C Operators and Control Structures.pdf
C Operators and Control Structures.pdfC Operators and Control Structures.pdf
C Operators and Control Structures.pdf
 
C tutorial
C tutorialC tutorial
C tutorial
 
presentation_data_types_and_operators_1513499834_241350.pptx
presentation_data_types_and_operators_1513499834_241350.pptxpresentation_data_types_and_operators_1513499834_241350.pptx
presentation_data_types_and_operators_1513499834_241350.pptx
 
Control statements-Computer programming
Control statements-Computer programmingControl statements-Computer programming
Control statements-Computer programming
 
C faq pdf
C faq pdfC faq pdf
C faq pdf
 
Elements of programming
Elements of programmingElements of programming
Elements of programming
 
C PROGRAMMING p-3.pptx
C PROGRAMMING p-3.pptxC PROGRAMMING p-3.pptx
C PROGRAMMING p-3.pptx
 
C C++ tutorial for beginners- tibacademy.in
C C++ tutorial for beginners- tibacademy.inC C++ tutorial for beginners- tibacademy.in
C C++ tutorial for beginners- tibacademy.in
 
the refernce of programming C notes ppt.pptx
the refernce of programming C notes ppt.pptxthe refernce of programming C notes ppt.pptx
the refernce of programming C notes ppt.pptx
 
Branching statements
Branching statementsBranching statements
Branching statements
 

Recently uploaded

Harnessing WebAssembly for Real-time Stateless Streaming Pipelines
Harnessing WebAssembly for Real-time Stateless Streaming PipelinesHarnessing WebAssembly for Real-time Stateless Streaming Pipelines
Harnessing WebAssembly for Real-time Stateless Streaming Pipelines
Christina Lin
 
ACEP Magazine edition 4th launched on 05.06.2024
ACEP Magazine edition 4th launched on 05.06.2024ACEP Magazine edition 4th launched on 05.06.2024
ACEP Magazine edition 4th launched on 05.06.2024
Rahul
 
Manufacturing Process of molasses based distillery ppt.pptx
Manufacturing Process of molasses based distillery ppt.pptxManufacturing Process of molasses based distillery ppt.pptx
Manufacturing Process of molasses based distillery ppt.pptx
Madan Karki
 
Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024
Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024
Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024
Sinan KOZAK
 
The Python for beginners. This is an advance computer language.
The Python for beginners. This is an advance computer language.The Python for beginners. This is an advance computer language.
The Python for beginners. This is an advance computer language.
sachin chaurasia
 
Comparative analysis between traditional aquaponics and reconstructed aquapon...
Comparative analysis between traditional aquaponics and reconstructed aquapon...Comparative analysis between traditional aquaponics and reconstructed aquapon...
Comparative analysis between traditional aquaponics and reconstructed aquapon...
bijceesjournal
 
A SYSTEMATIC RISK ASSESSMENT APPROACH FOR SECURING THE SMART IRRIGATION SYSTEMS
A SYSTEMATIC RISK ASSESSMENT APPROACH FOR SECURING THE SMART IRRIGATION SYSTEMSA SYSTEMATIC RISK ASSESSMENT APPROACH FOR SECURING THE SMART IRRIGATION SYSTEMS
A SYSTEMATIC RISK ASSESSMENT APPROACH FOR SECURING THE SMART IRRIGATION SYSTEMS
IJNSA Journal
 
Eric Nizeyimana's document 2006 from gicumbi to ttc nyamata handball play
Eric Nizeyimana's document 2006 from gicumbi to ttc nyamata handball playEric Nizeyimana's document 2006 from gicumbi to ttc nyamata handball play
Eric Nizeyimana's document 2006 from gicumbi to ttc nyamata handball play
enizeyimana36
 
BPV-GUI-01-Guide-for-ASME-Review-Teams-(General)-10-10-2023.pdf
BPV-GUI-01-Guide-for-ASME-Review-Teams-(General)-10-10-2023.pdfBPV-GUI-01-Guide-for-ASME-Review-Teams-(General)-10-10-2023.pdf
BPV-GUI-01-Guide-for-ASME-Review-Teams-(General)-10-10-2023.pdf
MIGUELANGEL966976
 
Literature Review Basics and Understanding Reference Management.pptx
Literature Review Basics and Understanding Reference Management.pptxLiterature Review Basics and Understanding Reference Management.pptx
Literature Review Basics and Understanding Reference Management.pptx
Dr Ramhari Poudyal
 
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODELDEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
gerogepatton
 
Question paper of renewable energy sources
Question paper of renewable energy sourcesQuestion paper of renewable energy sources
Question paper of renewable energy sources
mahammadsalmanmech
 
TIME DIVISION MULTIPLEXING TECHNIQUE FOR COMMUNICATION SYSTEM
TIME DIVISION MULTIPLEXING TECHNIQUE FOR COMMUNICATION SYSTEMTIME DIVISION MULTIPLEXING TECHNIQUE FOR COMMUNICATION SYSTEM
TIME DIVISION MULTIPLEXING TECHNIQUE FOR COMMUNICATION SYSTEM
HODECEDSIET
 
Recycled Concrete Aggregate in Construction Part III
Recycled Concrete Aggregate in Construction Part IIIRecycled Concrete Aggregate in Construction Part III
Recycled Concrete Aggregate in Construction Part III
Aditya Rajan Patra
 
spirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptxspirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptx
Madan Karki
 
Recycled Concrete Aggregate in Construction Part II
Recycled Concrete Aggregate in Construction Part IIRecycled Concrete Aggregate in Construction Part II
Recycled Concrete Aggregate in Construction Part II
Aditya Rajan Patra
 
Advanced control scheme of doubly fed induction generator for wind turbine us...
Advanced control scheme of doubly fed induction generator for wind turbine us...Advanced control scheme of doubly fed induction generator for wind turbine us...
Advanced control scheme of doubly fed induction generator for wind turbine us...
IJECEIAES
 
ML Based Model for NIDS MSc Updated Presentation.v2.pptx
ML Based Model for NIDS MSc Updated Presentation.v2.pptxML Based Model for NIDS MSc Updated Presentation.v2.pptx
ML Based Model for NIDS MSc Updated Presentation.v2.pptx
JamalHussainArman
 
Presentation of IEEE Slovenia CIS (Computational Intelligence Society) Chapte...
Presentation of IEEE Slovenia CIS (Computational Intelligence Society) Chapte...Presentation of IEEE Slovenia CIS (Computational Intelligence Society) Chapte...
Presentation of IEEE Slovenia CIS (Computational Intelligence Society) Chapte...
University of Maribor
 
IEEE Aerospace and Electronic Systems Society as a Graduate Student Member
IEEE Aerospace and Electronic Systems Society as a Graduate Student MemberIEEE Aerospace and Electronic Systems Society as a Graduate Student Member
IEEE Aerospace and Electronic Systems Society as a Graduate Student Member
VICTOR MAESTRE RAMIREZ
 

Recently uploaded (20)

Harnessing WebAssembly for Real-time Stateless Streaming Pipelines
Harnessing WebAssembly for Real-time Stateless Streaming PipelinesHarnessing WebAssembly for Real-time Stateless Streaming Pipelines
Harnessing WebAssembly for Real-time Stateless Streaming Pipelines
 
ACEP Magazine edition 4th launched on 05.06.2024
ACEP Magazine edition 4th launched on 05.06.2024ACEP Magazine edition 4th launched on 05.06.2024
ACEP Magazine edition 4th launched on 05.06.2024
 
Manufacturing Process of molasses based distillery ppt.pptx
Manufacturing Process of molasses based distillery ppt.pptxManufacturing Process of molasses based distillery ppt.pptx
Manufacturing Process of molasses based distillery ppt.pptx
 
Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024
Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024
Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024
 
The Python for beginners. This is an advance computer language.
The Python for beginners. This is an advance computer language.The Python for beginners. This is an advance computer language.
The Python for beginners. This is an advance computer language.
 
Comparative analysis between traditional aquaponics and reconstructed aquapon...
Comparative analysis between traditional aquaponics and reconstructed aquapon...Comparative analysis between traditional aquaponics and reconstructed aquapon...
Comparative analysis between traditional aquaponics and reconstructed aquapon...
 
A SYSTEMATIC RISK ASSESSMENT APPROACH FOR SECURING THE SMART IRRIGATION SYSTEMS
A SYSTEMATIC RISK ASSESSMENT APPROACH FOR SECURING THE SMART IRRIGATION SYSTEMSA SYSTEMATIC RISK ASSESSMENT APPROACH FOR SECURING THE SMART IRRIGATION SYSTEMS
A SYSTEMATIC RISK ASSESSMENT APPROACH FOR SECURING THE SMART IRRIGATION SYSTEMS
 
Eric Nizeyimana's document 2006 from gicumbi to ttc nyamata handball play
Eric Nizeyimana's document 2006 from gicumbi to ttc nyamata handball playEric Nizeyimana's document 2006 from gicumbi to ttc nyamata handball play
Eric Nizeyimana's document 2006 from gicumbi to ttc nyamata handball play
 
BPV-GUI-01-Guide-for-ASME-Review-Teams-(General)-10-10-2023.pdf
BPV-GUI-01-Guide-for-ASME-Review-Teams-(General)-10-10-2023.pdfBPV-GUI-01-Guide-for-ASME-Review-Teams-(General)-10-10-2023.pdf
BPV-GUI-01-Guide-for-ASME-Review-Teams-(General)-10-10-2023.pdf
 
Literature Review Basics and Understanding Reference Management.pptx
Literature Review Basics and Understanding Reference Management.pptxLiterature Review Basics and Understanding Reference Management.pptx
Literature Review Basics and Understanding Reference Management.pptx
 
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODELDEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
 
Question paper of renewable energy sources
Question paper of renewable energy sourcesQuestion paper of renewable energy sources
Question paper of renewable energy sources
 
TIME DIVISION MULTIPLEXING TECHNIQUE FOR COMMUNICATION SYSTEM
TIME DIVISION MULTIPLEXING TECHNIQUE FOR COMMUNICATION SYSTEMTIME DIVISION MULTIPLEXING TECHNIQUE FOR COMMUNICATION SYSTEM
TIME DIVISION MULTIPLEXING TECHNIQUE FOR COMMUNICATION SYSTEM
 
Recycled Concrete Aggregate in Construction Part III
Recycled Concrete Aggregate in Construction Part IIIRecycled Concrete Aggregate in Construction Part III
Recycled Concrete Aggregate in Construction Part III
 
spirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptxspirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptx
 
Recycled Concrete Aggregate in Construction Part II
Recycled Concrete Aggregate in Construction Part IIRecycled Concrete Aggregate in Construction Part II
Recycled Concrete Aggregate in Construction Part II
 
Advanced control scheme of doubly fed induction generator for wind turbine us...
Advanced control scheme of doubly fed induction generator for wind turbine us...Advanced control scheme of doubly fed induction generator for wind turbine us...
Advanced control scheme of doubly fed induction generator for wind turbine us...
 
ML Based Model for NIDS MSc Updated Presentation.v2.pptx
ML Based Model for NIDS MSc Updated Presentation.v2.pptxML Based Model for NIDS MSc Updated Presentation.v2.pptx
ML Based Model for NIDS MSc Updated Presentation.v2.pptx
 
Presentation of IEEE Slovenia CIS (Computational Intelligence Society) Chapte...
Presentation of IEEE Slovenia CIS (Computational Intelligence Society) Chapte...Presentation of IEEE Slovenia CIS (Computational Intelligence Society) Chapte...
Presentation of IEEE Slovenia CIS (Computational Intelligence Society) Chapte...
 
IEEE Aerospace and Electronic Systems Society as a Graduate Student Member
IEEE Aerospace and Electronic Systems Society as a Graduate Student MemberIEEE Aerospace and Electronic Systems Society as a Graduate Student Member
IEEE Aerospace and Electronic Systems Society as a Graduate Student Member
 

M2 (1).pptxisedepofengiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii

  • 1. Module – 2 Operators, Decision Control and Looping Statements
  • 2. Operators  Arithmetic Operators  Logical Operators  Bitwise Operators  Ternary Operators
  • 3. Some more Arithmetic Operators  Prefix Increment : ++a example: int a=5; b=++a; // value of b=6; a=6;  Postfix Increment: a++ example: int a=5; b=a++; // value of b=5; a=6;
  • 4. Continued…  Modulus (remainder): % example: 12%5 = 2;  Assignment by addition: += example: int a=4; a+=1; //(means a=a+1) value of a becomes 5 Can use -, /, *, % also
  • 5. Continued…  Comparison (Relational ) Operators: <, > , <=, >= , !=, ==  Logical Operators: !, &&, || example: int a=4, b=5; a<b returns a true(non zero number) value.  Bitwise Operators: <<, >>, ~, &, | ,^ . example: int a=8; a= a>>1; // value of a becomes 4
  • 7. i) 3 + 4*5 - 6/3*4/8 + 2*6 - 4*3*2 ii) -1.5+2.0*3.5-5.0/2.5+1.25
  • 8. Truth Table For Bit Wise Operation & – Bitwise AND | – Bitwise OR ~ – Bitwise NOT ^ – XOR << – Left Shift >> – Right Shift
  • 9. Operator Precedence  Meaning of a + b * c ? is it a+(b*c) or (a+b)*c ?  All operators have precedence over each other  *, / have more precedence over +, - . If both *, / are used, associativity comes into picture. (more on this later) example : 5+4*3 = 5+12= 17.
  • 10. Conditional Or Ternary Operators  Conditional operators return one value if condition is true and returns another value is condition is false.  This operator is also called as ternary operator. Syntax : (Condition? true_value: false_value); Example : (A > 100 ? 0 : 1);
  • 11. Precedence Table Highest on top ++ -- (Postfix) ++ -- (Prefix) * / % + - << >> < > & | && ||
  • 12. 8 0 6 12 Evaluate Arithmetic Expression x = 2 * 3 / 4 + 4 / 4 + 8 - 2 + 5 / 8; a = 7 / 22 * ( 3.14 + 2 ) * 3 / 5 ; b = 4 + 2 % - 8 ; c = ( 10 * 2 ) ( 3 + ( 2.5 + 6 ) ( 4 + 18 ) ;
  • 13. 13 Data types and their sizes
  • 14. 14 Data types and their sizes
  • 15. 15
  • 16. 16 Operation Result Operation Result 5 / 2 2 2 / 5 0 5.0 / 2 2.5 2.0 / 5 0.4 5 / 2.0 2.5 2 / 5.0 0.4 5.0 / 2.0 2.5 2.0 / 5.0 0.4 Integer and float conversion
  • 17. 17 Integer and float conversion k is integer variable and a is a real variable
  • 19. 19
  • 20. 20 #include <stdio.h> int main() { char c; printf("Enter a character: "); // Reads character input from the user scanf("%c", &c); // %d displays the integer value of a character // %c displays the actual character printf("ASCII value of %c = %d", c, c); return 0; } Print ASCII Value
  • 21. Output ? #include<stdio.h> void main( ) { int a, b ; a = -4 - - 4 ; b = -4 - - ( - 4 ) ; printf ( "a = %d b = %d", a, b ) ; }
  • 22. Type Conversion  Converting the value of one data type (int, float, double, etc.) to another data type.  This process is known as type conversion.
  • 23. C Example #include <stdio.h> int main() { int number = 34.78; printf("%d", number); return 0; } // Output: 34
  • 24.  There are two types of type conversion: Implicit Conversion Explicit Conversion  In implicit type conversion, the value of one type is automatically converted to the value of another type.  In explicit type conversion, we manually convert values of one data type to another type.
  • 25. Implicit type conversion example #include<stdio.h> int main ( ) { // character variable char alphabet = 'a'; printf("Character Value: %cn", alphabet); // assign character value to integer variable int number = alphabet; printf("Integer Value: %d", number); return 0; }
  • 26. Explicit type conversion example #include<stdio.h> int main() { // create an integer variable int number = 35; printf("Integer Value: %dn", number); // explicit type conversion double value = (double) number; printf("Double Value: %.2lf", value); return 0; }
  • 27. C –Type Casting  Converting one datatype into another is known as type casting or, type-conversion. For example, if you want to store a 'long' value into a simple integer then you can type cast 'long' to 'int’.  You can convert the values from one type to another explicitly using the cast operator as follows − (type_name) expression
  • 28. C Program for floating-point operation #include <stdio.h> main ( ) { int sum = 17, count = 5; double mean; mean = (double) sum / count; printf("Value of mean : %fn", mean ); }
  • 29.  Integer promotion is the process by which values of integer type "smaller" than int or unsigned int are converted either to int or unsigned int. Usual Arithmetic Conversion  The usual arithmetic conversions are implicitly performed to cast their values to a common type. The compiler first performs integer promotion; if the operands still have different types, then they are converted to the type that appears highest in the following hierarchy −
  • 30.
  • 31. //C Program of adding a character with an integer #include <stdio.h> main() { int i = 17; char c = 'c'; /* ascii value is 99 */ int sum; sum = i + c; printf("Value of sum : %dn", sum ); }
  • 32. Control Statements or Flow Control  Sequence Control Statements  Decision Control Statements  Loop Control Statements  Case Control Statements
  • 33. Decision Control Statements Perform different set of actions based on the situation. 1. if 2. if else 3. switch
  • 34. The if statement if ( this condition is true ) execute this statement ; if ( this condition is true ) { execute this block; }
  • 35. The if statement if ( this condition is true ) execute this statement ; if ( this condition is true ) { execute this block; }
  • 36. 36 void main ( ) { int n ; printf ( "Enter a number n" ) ; scanf ( "%d", &n ) ; if ( n < =100 ) printf ( “The number is less than or equal to 100" ) ; } The if statement example
  • 37. The if-else statement if ( this condition is true ) execute this statement ; else execute this statement ; if ( this condition is true ) { execute this block; } else { execute this block; }
  • 38. 38 void main( ) { int n ; printf ( "Enter a number n" ) ; scanf ( "%d", &n ) ; if ( n <= 100 ) printf ( “The number is less than or equal to 100" ) ; else printf ( “The number is greater than 100" ) ; } The if-else example
  • 39. The if-else statement if ( this condition is true ) execute this statement ; else execute this statement ; if ( this condition is true ) { execute this block; } else { execute this block; }
  • 40. The else-if statement if ( expression ) execute this statement ; else if ( expression ) execute this statement ; else if ( expression ) execute this statement ; else if ( expression ) execute this statement ; else execute this statement ; Multi-way decision Note: Last else is optional
  • 41. Nesting of if-else statements if (expression1) { // code to be executed if (expression2) { // code to be executed // if condition2 is true } }
  • 42. Switch case statements switch( expression ) { case value-1: Block-1; break; case value-2: Block-2; break; ………………… case value-n: Block-n; break; default: Block-1; break; } Statement-x; Note: default is optional expression can be integral or character
  • 43. 43 #include <stdio.h> int main() { int x; printf (“Enter your choice”); scanf (“%d”,&x); switch (x) { case 1: printf("Choice is 1"); break; case 2: printf("Choice is 2"); break; case 3: printf("Choice is 3"); break; default: printf("Choice other than 1, 2 and 3"); break; } return 0; } Switch case example
  • 44. 44 switch ( marks / 10 ) { case 4 : case 5 : grade = ‘D’; break; case 6 : case 7 : grade = ‘C’; break; case 8 : case 9 : grade = ‘B’; break; case 10 : grade = ‘A’; break; default : grade = ‘F’; break; } Switch case example
  • 45. Difference between if-else and switch  “If-else” can evaluate float conditions, “switch” cannot.  “If-else” can evaluate relational operators, “switch” cannot.
  • 46. Switch Examples  Write a C program to print day of week name using switch case.  Write a C program to print number of days in a month using switch case.  Write a C program to find maximum between two numbers using switch case.  C program to check positive negative or zero using switch case.
  • 47. 47 int main ( ) { int num; printf("Enter any number: "); scanf("%d", &num); switch (num > 0) { // Num is positive case 1: printf("%d is positive.", num); break; // Num is either negative or zero case 0: switch (num < 0) { case 1: printf("%d is negative.", num); break; case 0: printf("%d is zero.", num); break; } break; } return 0; } Program to check positive or negative or zero using switch
  • 48. Example program  A commercial bank has introduced an incentive of giving bonus to all its deposit holders. The policy is as follows: A bonus of 2 percent of the balance held is given to every one and 5 percent is given to female account holders if their balance is more than Rs.5000.  Note: Take gender using character variable. Example M means male and F means female.  Inputs : Balance amount and the gender  Output: bonus and balance after adding bonus
  • 49. The else-if statement if ( expression ) execute this statement ; else if ( expression ) execute this statement ; else if ( expression ) execute this statement ; else if ( expression ) execute this statement ; else execute this statement ; Multi-way decision Note: Last else is optional
  • 51. Example Program  Write a C program to input marks of five subjects Physics, Chemistry, Biology, Mathematics and Computer. Calculate percentage and grade according to following: Percentage >= 90% : Grade A Percentage >= 80% : Grade B Percentage >= 70% : Grade C Percentage >= 60% : Grade D Percentage >= 40% : Grade E Percentage < 40% : Grade F
  • 52. 52 switch ( avg_marks / 10 ) { case 0 : case 1 : case 2 : case 3 : grade = ‘F’; break; case 4 : case 5 : grade = ‘E’; break; case 6 : grade = ‘D’; break; case 7 : grade = ‘C’; break; case 8 : grade = ‘B’; break; case 9 : case 10 : grade = ‘A’; break; default : grade = ‘F’; break; } Switch case example
  • 53. The ? : operator  Ternary operator is used for decision making in place of conditional statements if and else.  Takes three arguments. conditional_expression ? value_if_true : value_if_false int a = 10, b = 20, c; if (a < b) { c = a; } else { c = b; } printf("%d", c); int a = 10, b = 20, c; c = (a < b) ? a : b; printf("%d", c);
  • 54. Example Program Consider the weekly salary of a sales guy who is selling some products. If x is the number of products sold in a week, his weekly salary is given by 4x+100 for x<40 Salary = 300 for x=40 4.5x+150 for x>40
  • 56. Loops in C A sequence of statements are executed until some conditions for termination is satisfied. Two parts: 1. Body of the loop 2. Control statement
  • 57. Looping process steps 1. Setting and initialization of the condition variable 2. Execution of the statements in loop 3. Test for a specified value of the condition variable for execution of the loop 4. Incrementing or updating the condition variable
  • 58. Three types of loops  The while statement  The do-while statement  The for statement
  • 59. The while statement  Entry controlled loop statement  The test condition is evaluated and if the condition is true, then the body of the loop is executed. while (test condition) { // statements inside the body of the loop }
  • 60. Print numbers from 1 to 5 60 #include <stdio.h> int main() { int i = 1; // Initialization while (i <= 5) // Testing { printf("%dn", i); i++; // Incrementing } return 0; }
  • 61. While examples  Write a C program to find the sum of all integers between 1 and 10.  Write a C program to find the sum of squares of all integers between 1 and 10.  Write a program to evaluate the equation y=xn where n is a non negative integer.
  • 62. The do while statement  Exit controlled loop statement.  The body of the loop is executed first.  At the end of the loop, the test condition is evaluated. do { // statements inside the body of the loop } while (test condition);
  • 63. Program to add numbers until the user enters zero 63 #include <stdio.h> void main() { double number, sum = 0; // the body of the loop is executed at least once do { printf("Enter a number: "); scanf("%lf", &number); sum += number; } while(number != 0.0); printf("Sum = %.2lf",sum); }
  • 64. The for statement Entry controlled loop, more concise loop control structure. 1. Initialization of the control variables is done first. Ex: i=0, count=0 (loop control variables) 2. The value of the control variable is tested using the test condition. Ex: i<10 3. When the body of the loop is executed, control is transferred back to for statement. The control variable is incremented/updated using an assignment statement. Ex: i=i+1 for (initialization; test_condition ; increment) { // statements inside the body of loop }
  • 65. Flow chart of for statement 65
  • 66. Print numbers from 0 to 10 #include <stdio.h> int main() { int i; for (i = 0; i <= 10; ++i) { printf("%d ", i); } return 0; }
  • 67. For loop examples  Write a C program to find the sum of all integers between 1 and 10.  Write a C program to find the sum of squares of all integers between 1 and 10.  Write a program to evaluate the equation y=xn where n is a non negative integer.  Write a program to find the factorial of a number.  Write a program to find the gcd of two numbers.  Write a program to print first 10 multiples of 5.  C program to add digits of a number:
  • 68. Loop Control Statements Loop control statements change execution from its normal sequence. Control Statement & Description break statement Terminates the loop or switch statement and transfers execution to the statement immediately following the loop or switch. continue statement Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating. goto statement Transfers control to the labeled statement.
  • 70. 70 // Program to calculate the sum of a maximum of 10 numbers // If a negative number is entered, the loop terminates void main() { int i; double number, sum = 0.0; for(i=1; i <= 10; ++i) { printf("Enter a n%d: ",i); scanf("%lf",&number); // If the user enters a negative number, the loop ends if(number < 0.0) { break; } sum += number; // sum = sum + number; } printf("Sum = %.2lf",sum); }
  • 72. 72 // Program to calculate the sum of a maximum of 10 numbers // Negative numbers are skipped from the calculation void main() { int i; double number, sum = 0.0; for(i=1; i <= 10; ++i) { printf("Enter a n %d: ",i); scanf("%lf",&number); if(number < 0.0) { continue; } sum += number; // sum = sum + number; } printf("Sum = %.2lf",sum); }
  • 73. 73 break continue A break can appear in both switch and loop (for, while, do) statements. A continue can appear only in loop (for, while, do) statements. A break causes the switch or loop statements to terminate the moment it is executed. Loop or switch ends abruptly when break is encountered. A continue doesn't terminate the loop, it causes the loop to go to the next iteration. All iterations of the loop are executed even if continue is encountered. The continue statement is used to skip statements in the loop that appear after the continue. The break statement can be used in both switch and loop statements. The continue statement can appear only in loops. You will get an error if this appears in switch statement. When a break statement is encountered, it terminates the block and gets the control out of the switch or loop. When a continue statement is encountered, it gets the control to the next iteration of the loop. A break causes the innermost enclosing loop or switch to be exited immediately. A continue inside a loop nested within a switch causes the next loop iteration.
  • 74. Infinite Loop  A loop becomes an infinite loop if a condition never becomes false.  The for or while loop is traditionally used.  Most of the time we create infinite loops by mistake.  Commonly used in programs that keep running for long periods of time until they are stopped.0 #include <stdio.h> int main () { for( ; ; ) // or while(1) { printf("This loop will run forever.n"); } return 0; }
  • 76. 76 int choice; while(1) { printf(“1.Create databasen”); printf(“2.Insert new recordn”); printf(“3.Modify a recordn”); printf(“4.Delete a recordn”); printf(“5.Display all recordsn”); printf(“6.Exitn”); printf(“Enter your choice : “); scanf(“%d”,&choice); switch(choice) { case 1: printf(“Database created…..nn”); break; case 2:printf(“Record inserted…..nn”);break; case 3:printf(“Record modified…..nn”);break; case 4:printf(“Record deleted…..nn”);break; case 5:printf(“Records displayed…..nn”);break; case 6:exit(1); default:printf(“Wrong choicen”); } } Infinite Loop example
  • 77. Programming Examples  Given a number n, print triangular pattern. We are allowed to use only one loop.
  • 78. Programming Examples • Given a positive integer n. Print the inverted triangular pattern.
  • 79. Roots of a quadratic equation  a, b and c are known values. a can't be 0.  "x" is the variable or unknown.
  • 80. Discriminant  b2 − 4ac in the formula is called the Discriminant, because it can "discriminate" between the possible types of answer:  when b2 − 4ac is  positive, we get two Real solutions  Zero, we get just ONE real solution (both answers are the same)  Negative, we get a pair of Complex solutions  Ex: 5x2 + 6x + 1 = 0, Solution x = −0.2 or −1
  • 81. Algorithm: Quadratic Equation 81 Step 1: Start Step 2: Read the values of non-zero coefficients a,b and c. Step 3: Compute the value of discriminant (disc) which is equal to (b*b-4*a*c). Step 4: Check if disc is equal to 0. If true, then go toStep 5. Otherwise, go to Step 6 Step 5: Compute the roots. root1 = (-b)/ (2*a) , root2=root1 Output the values of roots, root1 and root2. Go to Step 9. Step 6: Check if disc is greater than zero or not. If true, then go to Step 7.Otherwise, go to Step 8. Step 7: Compute the real and distinct roots, root1 = (-b+sqrt(disc))/(2*a) root2 = (-b- sqrt(disc))/(2*a) Output the values of roots, root1 and root2. Go to Step 9. Step 8: Compute the complex and distinct roots. Compute the real part, r_part = (-b)/(2*a) Compute the imaginary part, i_part = sqrt(-disc)/(2*a) Output roots as root1 = r_part + i_part root2 = r_part – i_part Step 9: Stop
  • 82. 82
  • 83. Palindrome int main() { int num,rev=0,rem,temp; printf("Enter a number : "); scanf("%d",&num); temp = num; while(num != 0) { rem=num%10; rev= rev*10+rem; num = num / 10; } printf("n The reverse of given number is %d ",rev); if(temp==rev) printf("n The given number %d is a Palindrome",temp); else printf("n The given number %d is not a Palindrome",temp); }
  • 84. Binomial coefficient  The binomial theorem describes the algebraic expansion of powers of a binomial.  According to the theorem, it is possible to expand the polynomial (x + y)n into a sum involving terms of the form axbyc  where the exponents b and c are nonnegative integers with b + c = n, and  the coefficient a of each term is a specific positive integer depending on n and b.  The coefficient a in the term of axbyc is known as the binomial coefficient.  These coefficients for varying n and b can be arranged to form Pascal's triangle.  For example (for n = 4)
  • 88. The goto statement  To branch unconditionally from one point to another in the program.  Requires a label in order to identify the place where the branch is to be made.  A label is any valid variable name followed by a colon. goto label; ----- ----- label: statement; label: statement; ----- ----- goto label;
  • 89. Example Program main() { double a,b; read: printf(“Enter a number greater than 0n”); scanf(“%f”,&a); if(a<0)goto read; b= sqrt(a); printf(“square root=%f”,b); }