0% found this document useful (0 votes)
13 views147 pages

Cunit 2

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

Cunit 2

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

Unit 2

Operators and Expressions: Arithmetic operators, Unary operators,


Relational and Logical Operators, Assignment Operators, Conditional
Operators. Expressions, Precedence and Associativity, Evaluating
Expressions, Type Conversion.
Selection-Making Decision: Two Way Selection, Multiway Selection,
Standard Character Functions. Repetition: Concepts of a loop, Pretest
and Post-test Loops, Initialization and Updating,
Loops in C: The while loop, the do While loop, the for loop, the break
and continue statement, the goto statement.
Operators and Expressions
• C supports a rich set of operators. Operators are used in programs to
manipulate data and variables.
• They usually form a part of the mathematical of logical expressions.
Categories of Operators
◼ Arithmetic operators
◼ Relational operators
◼ Logical operators
◼ Assignment operators
◼ Increment and Decrement operators
◼ Conditional operators
◼ Bitwise operators
◼ Special operators
ARITHMETIC OPERATORS
◼ The operators are
◼ + (Addition)
◼ - (Subtraction)
◼ * (Multiplication)
◼ / (Division)
◼ % (Modulo division)
◼ The Division operator produces the quotient.
◼ The modulo division produces the remainder of an integer division.
◼ The modulo division operator cannot be used on floating point
data.
◼ Note: C does not have any operator for exponentiation
Integer Arithmetic
◼ When both the operands in a single arithmetic expression are integers, the
expression is called an integer expression, and the operation is called integer
arithmetic.
◼ If a=14 and b=4, then
◼ a-b=10
◼ a+b=18
◼ a*b=56
◼ a/b=3
◼ a%b=2
Integer Arithmetic
• ◼ What are the results of the following?
• ◼ 6/7=?
• ◼ 3/7=?
• ◼ 21/3=?
• ◼ During modulo division the sign of the result is always the sign of
the first operand.
• ◼ -14 % 3 = -2
• ◼ -14 % -3 = -2
• ◼ 14 % -3 = 2
Real Arithmetic
An arithmetic operation involving only real operands is called real
arithmetic.
◼ If x and y are floating then we will have
◼ 1) x = 6.0 / 7.0 = 0.857143
◼ 2) y = 1.0 / 3.0 = 0.333333
◼ The operator % cannot be used with real
operands.
Mixed-mode Arithmetic
• ◼ When one of the operands is real and the other is integer, the
expression is called a mixed mode arithmetic expression and its result
is always a real number.
• ◼ Eg: 1) 15 / 10.0 = 1.5
RELATIONAL OPERATORS
◼ Comparisons can be done with the help of relational operators.
◼ The expression containing a relational operator is termed as a
relational expression.
◼ The value of a relational expression is either one or zero
RELATIONAL OPERATORS
◼ 1) < (is less than)
◼ 2) <= (is less than or equal to)
◼ 3) > (is greater than)
◼ 4) >= (is greater than or equal to)
◼ 5) = = (is equal to)
◼ 6) != (is not equal to)
LOGICAL OPERATORS
◼ Following are three logical operators.
◼ && (logical AND)
◼ || (logical OR)
◼ ! (logical NOT)
◼ Eg:
◼ 1) if(age>55 && sal<1000)
◼ 2) if(number<0 || number>100)
ASSIGNMENT OPERATORS
◼ The usual assignment operator is ‘=’.
◼ In addition, C has a set of ‘shorthand’ assignment operators.
◼ Eg: x += y+1;
◼ This is same as the statement x=x+(y+1);
◼ a + =1 → a = a + 1
◼ a - = 1 →a = a – 1
◼ a *= n + 1 → a = a * (n+1)
◼ a /= n + 1 → a = a / (n+1)
◼ a %= b → a = a % b
INCREMENT AND DECREMENT OPERATORS

◼ These are the increment and decrement operator:


◼ ++ and --
◼ The operator ++ adds 1 to the operands while -- subtracts 1.
◼ It takes the following form:
◼ ++m; or m++
◼ --m; or m—
◼ x= 4++; // gives error, because 4 is constant
INCREMENT AND DECREMENT OPERATORS

x= a++ 1. x= a
x= ++a 1. a=a+1

2. a=a+1 2. x= a
INCREMENT AND DECREMENT OPERATORS-
Example
void main()
{
int x,i; i=10;
x=i++;
printf("x: %d",x);
printf("i: %d",i);
}
void main() void main()
{ {
int x,i; i=10; int x,i; i=10;
x=++i; x=++i;
printf("x: %d",x); printf("x: %d",x);
printf("i: %d",i); printf("i: %d",i);
} }
Conditional Operators
• The conditional operator takes three operands, so it is a ternary operator.
The conditional operator is the only ternary operator available in the C
programming language, so the names ternary operator and conditional
operator are used alternatively to mean the conditional operator.
Bitwise operators
Unary Operators
1. sizeof :
sizeof(int)
2. Unary Plus/Minus:
+3, -3
3. Cast Operator:
float(x)
#include <stdio.h>
int main() printf("%d\n",sizeof(a));
{ printf("%d\n",sizeof(b));
int a; printf("%d\n",sizeof(c));
float b; printf("%d\n",sizeof(d));
char c; printf("%d\n",sizeof(e));
double d; printf("%d\n",sizeof(f));
short e; printf("%d\n",sizeof(g));
long int f; printf("%d",sizeof(h));
long long int g; return 0;
long double h; }
Expressions
An expression is a sequence of operands and operators that reduces to
a single value. It can be simple or compound.
Simple Expression contains only one operator. Ex: 2+3
Complex Expression contains more than one operator
ex: 2+3+6*5
The order in which the operators in complex expressions are evaluated
is determined by a set of priorities known as precedence.
If two operators with the same precedence occur in a complex
expression, another attribute that takes control is associativity.
Expressions (Conti.)
• An expression always reduces to a single value.
• Simple expressions are divided into six categories:

• Primary
• Postfix
• Prefix
• Unary
• Binary
• Ternary
Precedence and
Associativity
Evaluate an Expression
Let a=3 , b=4, c=5 , then Solve:
x= a* 4 + b / 2 – c * b
y = --a * (3+b) / 2 – c++ * b
#include<stdio.h>
int main()
Evaluate an {
//local declarations
Expression int a=3;
int b=4;
Let a=3 , b=4, c=5 , then Solve: int c=5;
int x;
x= a* 4 + b / 2 – c * b int y;
y = --a * (3+b) / 2 – c++ * b
//statements
printf("initial values of variables:\n");
printf("a=%d\tb=%d\tc=%d\n\n",a,b,c);
x=a*4+b/2-c*b;
printf("value of the expression a*4+b/2-c*b :%d\n",x);
y=--a*(3+b)/2-c++*b;
printf("value of the expression --a*(3+b)/2-c++*b :%d\n",y);
printf("values of variables are now:\n");
printf("a=%d\tb=%d\tc=%d\n\n",a,b,c);
return 0;
}
Problems : Evaluation of expressions
• If x=2, y=3 and z=1 ; evaluate the following expressions
• x+2/6+y
• y-3*z+2
• z-(x+z)%2+4
• x-2*(3+z)+y
• y++ + z-- + x++
Type Conversion
• Expressions with different data types?
To evaluate, one of the types must be converted
1. Implicit Type Conversion.
2. Explicit Type Conversion.
Implicit Type Conversion
When the types of the two operands in a binary expression are different, C
automatically converts one type to another based on:
• Conversion Rank
• Conversion in Assignment Expressions
• Promotion
• Demotion

• Implicit type casting means conversion of data types without losing its original
meaning. This type of typecasting is essential when you want to change data
types without changing the significance of the values stored inside the variable.
• Implicit type conversion in C happens automatically when a value is copied to its
compatible data type. During conversion, strict rules for type conversion are
applied. If the operands are of two different data types, then an operand having
lower data type is automatically converted into a higher data type.
#include<stdio.h>
int main(){
short a=10; //initializing variable of short data type
int b; //declaring int variable
b=a; //implicit type casting
printf("%d\n",a);
printf("%d\n",b); Output:
}
10
10
#include <stdio.h>
main() {
int number = 1;
char character = 'k'; /*ASCII value is 107 */
int sum;
sum = number + character;
printf("Value of sum : %d\n", sum ); Output:
}
Value of sum : 108
Conversion Rank
#include <stdio.h>
main() {
int num = 13;
char c = 'k'; /* ASCII value is 107 */
float sum;
sum = num + c;
printf("sum = %f\n", sum ); Output:
}
sum = 120.000000
Explicit type Conversions
• Uses unary cast operator:
int a;
(float) a;
#include<stdio.h>
int main()
{
float a = 1.2;
int b = (int)a + 1;
printf("Value of a is %f\n", a);
printf("Value of b is %d\n", b); Output:
return 0;
} Value of a is 1.200000
Value of b is 2
#include <stdio.h>
int main()
{
int a=5; O U T P U T :
a = 5
float x=5.63; y = 1 0 . 6 3
x = 5 . 6 3
float y=a+x; //implicit promotion c = 1 6 . 2 6
float c= x+y; b = 1 5 . 6 3
z = 1 6
int b= x + (int) y; // explicit conversion
int z= x+ y;
printf("a= %d\n", a);
printf("x= %f\n", x);
printf("y= %f\n", y);
printf("c=%f\n", c);
printf("b=%d\n", b);
printf("z=%d\n", z) ;
return 0;
}
#include <stdio.h>
int main()
{ Output:

int a=5;
float x=5.63;
float y=a+x; //implicit promotion
a= 5
float c= x+y; x= 5.630000
int b= x + (int) y; // explicit conversion y= 10.630000
int z= x+ y;
printf("a= %d\n", a); c=16.260000
printf("x= %f\n", x); b=15
printf("y= %f\n", y);
printf("c=%f\n", c); z=16
printf("b=%d\n", b);
printf("z=%d\n", z) ;
return 0;
}
//statements
// Demonstrate
Automatic promotion of printf("bool + char is char:%c\n", b+c);
numeric types: printf(“int * short is int: %d\n",i*s);
printf("float * char is float: %f\n",d*c);
#include<stdio.h>
#include<stdbool.h> c= c + b; //bool promoted to char
int main() d= d + c; // char promoted to float
{ b= false;
//local declarations b= - d; //Float demoted to bool
bool b=true;
char c='A'; printf("\n After execution...\n");
66
float d=245.3; printf("char + true: %c\n”,c); 310.3
0c
int i=3650; printf("float + char :%f\n",d);
short s=78; printf("bool = - float:%f\n",b);

return 0;
}
#include<stdio.h> printf("fltnum1 contains: %6.2f\n",fltnum1);
int main() printf("fltnum2 contains: %6.2f\n",fltnum2);
{ fltnum3=(double)(intnum1/intnum2);
//local declarations printf("\n(double)(intnum1 /intnum2):%6.2f\n",fltnum3);
char achar='\0‘;
int intnum1=100; fltnum3=(double)intnum1/intnum2;
int intnum2=45; printf("\n(double) intnum1 /intnum2:%6.2f\n",fltnum3);
double fltnum1=100.0; achar=(char)(fltnum1 - fltnum2);
double fltnum2=45.0; printf("(char)(fltnum1 - fltnum2) :%c\n",achar);
double fltnum3; return 0;
}
//statements
printf("achar numeric : %3d\n",achar);
printf("intnum1 contains: %3d\n",intnum1);
printf("intnum2 contains: %3d\n",intnum2);
Programs
1. C-Program to calculate quotient and reminder of two numbers.
2. C-Program to calculate the sum of three numbers / C-Program to demonstrate
a Simple Calculator.
3. C-Program to calculate the area and circumference of a circle using PI as a
defined constant.
c=2*pi*r
area= pi*r*r
4. C-Program to convert temperature given in Celsius to Fahrenheit and
Fahrenheit to Celsius
C = 5/9(°F – 32)
F = 9/5°C + 32
Selection-Making Decision
Two-Way Selection
• If… else
• Null else
• Nested if statements
If…else
• An if…else statement is a composite
statement used to make decisions
between two alternatives.

Ex:

1 2
If (a > 1)
a++;
else
a--;
If…..else wIth compound statements:
if (j !=3)
{
b++;
printf(“%d”, b);
}
else
{
c++;
printf(“%d”,c);
}
NULL else statements
If (expression)
{ If (expression)
-------------- {
} --------------
} //endif
else
;
1. Program to find the entered number is odd or even?

Using Simple if(Null if)


if …. Else

2. Program to check whether a person is eligible to vote or not.


#include<stdio.h> #include<stdio.h>
int main()
int main() {
{ int number=0;
printf("enter a number:");
int number=0; scanf("%d",&number);
if(number%2==0)
printf("Enter a number:");
{
scanf("%d",&number);
printf("%d is even number",number);
if(number%2==0) }
{ else
{
printf("%d is even number",number);
} printf("%d is odd number",number);
}
return 0; return 0;
}
}
nested … If statements
if ( Expression 1)
{
if( Expression 2)
statement2;
else
statement 1;
}
else
statement 3;

statement n;
Example Programs
• Write a program to find largest of 3 numbers.
#include<stdio.h>
int main()
{
int a,b,c;
printf("Enter the value of a,b,c\n");
scanf("%d %d %d",&a, &b, &c);
if((b>a && c>a))
{
if(b>c)
printf("b is largest");
else
printf("c is largest");
}
else
printf("a is largest");
return 0;
}
Dangling else problem
Dangling else problem

if (exp)
{
if(exp)
st1
}
else
{
st2
}
Return Statement
• A return statement terminates a function. All functions including the
main must have a return statement. When there is no return
statement at the end of the function, the system inserts one with a
void return value.
return expression;
A return value of 0 tells the OS that the program executed successfully
Multiway Selection
In addition to two-way selection, most programming
languages provide another selection concept known as
multiway selection. Multiway selection chooses among
several alternatives. C has two different ways to
implement multiway selection: the switch statement
and else-if construct.

Topics discussed in this section:


The switch Statement
The else-if

Computer Science: A Structured


55
Programming Approach Using C
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;
PROGRAM 5-6 Demonstrate the switch Statement

Computer Science: A Structured


57
Programming Approach Using C
#include <stdio.h>
int main()
{
char operation;
double n1, n2;
printf("Enter an operator (+, -, *, /): ");
scanf("%c", &operation);
printf("Enter two operands: ");
scanf("%lf %lf",&n1, &n2);
switch(operation)
{
case '+': printf("%.1lf + %.1lf = %.1lf",n1, n2, n1+n2);
break;
case '-’: printf("%.1lf - %.1lf = %.1lf",n1, n2, n1-n2);
break;
case '*': printf("%.1lf * %.1lf = %.1lf",n1, n2, n1*n2);
break;
case '/': printf("%.1lf / %.1lf = %.1lf",n1, n2, n1/n2);
break;
// operator doesn't match any case constant +, -, *, /
default: printf("Error! operator is not correct"); }
return 0;
}
Enter an operator (+, -, *, /): -
Enter two operands: 32.5
12.4
32.5 - 12.4 = 20.1
What will be the output?
#include <stdio.h>
int main()
{
int language = 10;
switch (language)
{
case 1: printf("C#\n");
break;
case 2: printf("C\n");
break;
case 3: printf("C++\n");
break;
default: printf("Other programming language\n");
}
}
What will be the output
#include <stdio.h>
int main()
{
int number=5;
switch (number)
{
case 1:
case 2:
case 3:
printf("One, Two, or Three.\n");
break;
case 4:
case 5:
case 6:
printf("Four, Five, or Six.\n");
break;
default:
printf("Greater than Six.\n");
}
}
Output?
#include <stdio.h>
int main()
{
int ID = 500;
int password = 000;
printf("Plese Enter Your ID:\n ");
scanf("%d", & ID);
switch (ID)
{
case 500: printf("Enter your password:\n ");
scanf("%d", & password);
switch (password)
{
case 000: printf("Welcome Dear Programmer\n");
break;
default: printf("incorrect password");
break;
}
break;
default: printf("incorrect ID");
break;
}
}
PROGRAM 5-7 Multivalued case Statements

Computer Science: A Structured


63
Programming Approach Using C
Rules and Summary
• Rules for switch statement
• An expression must always execute to a result.
• Case labels must be constants and unique.
• Case labels must end with a colon ( : ).
• A break keyword must be present in each case.
• There can be only one default label.
• We can nest multiple switch statements.
• Summary
• A switch is a decision making construct in ‘C.’
• A switch is used in a program where multiple decisions are involved.
• A switch must contain an executable test-expression.
• Each case must include a break keyword.
• Case label must be constants and unique.
• The default is optional.
• Multiple switch statements can be nested within one another.

Computer Science: A Structured Programming Approach Using


64
C
C-Program to read a test score, calculate
the grade for the score and print the grade
#include<stdio.h>
int main()
{
int marks,temp;
printf("\n-----------------------------------");
printf("\nEnter The Marks Between 0 To 100:");
printf("\nEnter The Mark: ");
scanf("%d", &marks);
if(marks>100)
{
/* Marks greater than 100 */
printf("\nDon't Be Smart Enter your Marks Between Limit\n");
}
else
{
temp=marks/10;
switch(temp)
{
case 10 :
case 9 :
printf("\n Your Grade is: A"); /* Marks between 90-100 */
break;
case 8 :
printf("\n Your Grade is: B" ); /* Marks between 80-89 */
break;
case 7 :
printf("\n Your Grade is: C" ); /* Marks between 70-79 */
break;
case 6 :
printf("\n Your Grade is: D" ); /* Marks between 60-69 */
break;
default :
printf("\n You Grade is: F or Fail\n"); /* Marks less than 40 */
}
}
if else if ladder
• if else if ladder in C programming is used to test a series of
conditions sequentially. Furthermore, if a condition is tested only
when all previous if conditions in the if-else ladder are false. If
any of the conditional expressions evaluate to be true, the
appropriate code block will be executed, and the entire if-else
ladder will be terminated.
Else if ladder
Syntax:
// any if-else ladder starts
with an if statement only
if(condition)
{ }
else if(condition)
{ // this else if will be executed
when condition in if is
false and
// the condition of this else if
is true
}....
// once if-else ladder can
have multiple else if
else { // at the end we put else }
Write a program to display wether a number is +ve, -ve or zero

int main()
{
int n = 0;

// all Positive numbers will make this


// condition true
if (n > 0) {
printf("Positive");
}

// all Negative numbers will make this


// condition true
else if (n < 0) {
printf("Negative");
}

// if a number is neither Positive nor Negative


else {
printf("Zero");
}
return 0;
}
C Program to Calculate Grade According to marks

#include <stdio.h>
int main()
{
int marks = 91;
if (marks <= 100 && marks >= 90)
printf("A+ Grade");
else if (marks < 90 && marks >= 80)
printf("A Grade");
else if (marks < 80 && marks >= 70)
printf("B Grade");
else if (marks < 70 && marks >= 60)
printf("C Grade");
else if (marks < 60 && marks > 50)
printf("D Grade");
else if (marks < 50)
printf("F Failed");
return 0;
}
An electricity board charges the following rates for the use of
electricity:
for the first 200 units 80 paise per unit:
for the next 100 units 90 paise per unit:
beyond 300 units rupees 1 per unit.

All users are charged a minimum of rupees 100 as a meter charge. If the
total amount is more than Rs 400, then an additional surcharge of 15%
of the total amount is charged.
Write a program to read the name of the user, the number of units
consumed, and print out the charges.
#include<stdio.h> else
#include<string.h> charge = 1.00;
amt = unit_con*charge;
void main()
if (amt>400)
{ surcharge = amt*15/100.0;
int cust_no, unit_con;
float charge,surcharge=0, amt, total_amt; total_amt = amt+surcharge;
char nm[25];
printf("\t\t\t\nElectricity Bill\n\n");
printf("Enter the customer IDNO :\t");
printf("Customer IDNO :\t%d",cust_no);
scanf("%d",&cust_no);
printf("\nCustomer Name :\t%s",nm);
printf("Enter the customer Name :\t"); printf("\nunit Consumed :\t%d",unit_con);
scanf("%s",nm); printf("\nAmount Charges @Rs. %4.2f per
printf("Enter the unit consumed by customer :\t"); unit:\t%0.2f",charge,amt);
scanf("%d",&unit_con); printf("\nSurchage Amount :\t%.2f",surcharge);
printf("\nMinimum meter charge Rs :\t%d",100);
if (unit_con <200 )
printf("\nNet Amount Paid By the Customer
charge = 0.80; :\t%.2f",total_amt+100);
else if (unit_con>=200 && unit_con<300) }
Repetition Statements
(loops)

74
Concept of Loop
We must design a loop so that before and after the
iteration, it checks to see if the task is done. If it is not
done the loop repeats one more time, or else it
terminates.
• Pretest Loop
• Post-Test Loop
Event Controlled loops
Initialize Initialize
Condition Condition

false
Condition Action
true
Update
Action
Condition

Update
Condition
true Condition

false
exit exit
Post-test loop
Pre-test loop
Counter Controlled loops
Set count to 0 Set count to 0

false
Count < n Action
true
Increment
Action
count

Increment
count
true Count < n

false
exit exit
Post-test loop
Pre-test loop
Loop Comparison

Pretest Loop Post-test Loop


Initialization 1 Initialization 1
Number of tests n+1 Number of tests n
Action executed n Action executed n
Updating n Updating executed n
executed
Minimum 0 Minimum Iteration 1
Iteration
Loops – While, Do, For

• Repetition Statements
• While
• Do
• For

79
Repetition Statements
• Repetition statements allow us to execute a statement or
a block of statements multiple times
• Often they are referred to as loops
• Like conditional statements, they are controlled by
boolean expressions
• Java has three kinds of repetition statements:
while
do
for
• The programmer should choose the right kind of loop
statement for the situation
80
The while Statement
• A while statement has the following syntax:
while ( condition )
statement;

• If the condition is true, the statement is


executed
• Then the condition is evaluated again, and if it is still
true, the statement is executed again
• The statement is executed repeatedly until the
condition becomes false

81
Logic of a while Loop

condition
evaluated

true false

statement

5
The while Statement
• An example of a while statement:
int count = 0;
while (count < 2)
{
printf(“welcome to java!");
count++;
}
• If the condition of a while loop is false initially, the
statement is never executed
• Therefore, the body of a while loop will execute
zero or more times

83
animation

Trace while Loop


Initialize count
int count = 0;
while (count < 2)
{
printf("Welcome to Java!");
count++;
}

7
animation
Trace while Loop, cont.
(count < 2) is true
int count = 0;
while (count < 2)
{
printf("Welcome to Java!");
count++;
}

8
animation
Trace while Loop, cont.
Print Welcome to Java
int count = 0;
while (count < 2)
{
printf("Welcome to Java!");
count++;
}

9
animation
Trace while Loop, cont.
Increase count by 1
int count = 0; count is 1 now

while (count < 2)


{
printf("Welcome to Java!");
count++;
}

10
animation
Trace while Loop, cont.
(count < 2) is still true since count
int count = 0; is 1

while (count < 2)


{
printf("Welcome to Java!");
count++;
}

11
animation
Trace while Loop, cont.
Print Welcome to Java
int count = 0;
while (count < 2)
{
printf("Welcome to Java!");
count++;
}

12
animation
Trace while Loop, cont.
Increase count by 1
int count = 0; count is 2 now

while (count < 2)


{
printf("Welcome to Java!");
count++;
}

13
animation
Trace while Loop, cont.
(count < 2) is false since count is 2
int count = 0; now

while (count < 2)


{
printf("Welcome to Java!");
count++;
}

14
animation
Trace while Loop
The loop exits. Execute the next
int count = 0; statement after the loop.

while (count < 2)


{
printf("Welcome to Java!");
count++;
}

15
Example (Average)
#include<stdio.h>
int main()
{
int sum=0, count=0;
float avg;

while( count <10)


{
count++;
sum+= count;
}
avg= (float ) sum/count;
printf(“%f”,avg);
}

93
Infinite Loops
• Executing the statements in the body of a while loop must
eventually make the condition false
• If not, it is called an infinite loop, which will execute until the user
interrupts the program
• This is a common logical error
• You should always double check the logic of a program to ensure that
your loops will terminate

94
Infinite Loops
• An example of an infinite loop:

int count = 1;
while (count <= 25)
{
printf(“%d”,count);
count = count - 1;
}
• This loop will continue executing until the user
externally interrupts the program.

95
Nested Loops
• Similar to nested if statements, loops can be nested as well
• That is, the body of a loop can contain another loop
• For each iteration of the outer loop, the inner loop iterates
completely

96
Nested Loops
• How many times will the string "Here" be printed?
count1 = 1;
while (count1 <= 10)
{
count2 = 1;
while (count2 <= 20)
{
System.out.println ("Here");
count2++;
}
count1++;
}
10 * 20 = 200
97
The do Statement
• A do statement has the following syntax:

do
{
statement;
}
while ( condition );

• The statement is executed once initially, and then


the condition is evaluated

• The statement is executed repeatedly until the


condition becomes false

98
Flowchart of a do Loop

statement

true

condition
evaluated

false

99
The do Statement
• An example of a do loop:
int count = 0;
do
{
printf("Welcome to Java!");
count++;
}
while (count < 2); Don’t forget this semicolon!

• The body of a do loop executes at least once

100
Comparing while and do
The while Loop The do Loop

statement
condition
evaluated
true

condition
true false
evaluated

statement
false

101
animation

Trace do Loop
Initialize count
int count = 0;
do
{
printf("Welcome to Java!");
count++;
} while (count < 2);

25
animation

Trace do Loop, cont.


Print Welcome to Java
int count = 0;
do
{
printf("Welcome to Java!");
count++;
} while (count < 2);

26
animation

Trace do Loop, cont.


Increase count by 1
int count = 0; count is 1 now

do
{
printf("Welcome to Java!");
count++;
} while (count < 2);

27
animation

Trace do Loop, cont.


(count < 2) is true
int count = 0;
do
{
printf("Welcome to Java!");
count++;
} while (count < 2);

28
animation

Trace do Loop, cont.


Print Welcome to Java
int count = 0;
do
{
printf("Welcome to Java!");
count++;
} while (count < 2);

29
animation

Trace do Loop, cont.


Increase count by 1
int count = 0; count is 2 now

do
{
printf("Welcome to Java!");
count++;
} while (count < 2);

30
animation

Trace do Loop, cont.


(count < 2) is false since count is 2
int count = 0; now

do
{
printf("Welcome to Java!");
count++;
} while (count < 2);

31
animation

Trace do Loop
The loop exits. Execute the next
int count = 0; statement after the loop.

do
{
printf("Welcome to Java!");
count++;
} while (count < 2);

32
The for Statement
• A for statement has the following syntax:

The initialization The statement is


is executed once executed until the
before the loop begins condition becomes false

for ( initialization ; condition ; increment )


statement;

The increment portion is executed


at the end of each iteration

110
The for Statement
• A for loop is functionally equivalent to the following while
loop structure:
initialization;
while ( condition )
{
statement;
increment;
}

• Example:
for(int i = 0; i < 10; i++) int i = 0;
{ while(i < 10)
//some code {
} //some code
i++;
}
Flowchart of a for loop

initialization

condition
evaluated

true false

statement

increment

112
Flowchart - example

Initial-Action i=0

for (int i = 0; i < 100; i++)


{ Loop
printf("Welcome false false
Continuation to Java!"); (i < 100)?
} Condition?
true true
Statement(s) System.out.println(
(loop body) "Welcome to Java");

Action-After-Each-Iteration i++

113
(A) (B)
The for Statement
• The initialization section can be used to declare a variable

• Like a while loop, the condition of a for loop is tested prior


to executing the loop body. Therefore, the body of a for loop
will execute zero or more times

• The increment section can be used to increment or decrement


a variable, for example:
for (int num=100; num > 0; num -= 5)
printf(“%d”,num);

114
Infinite for-loop
• If the condition is left out, it is always considered to be
true, and therefore creates an infinite loop

for ( ; ; ) { Equivalent while (true) {


// Do something // Do something
} }
(a) (b)

115
animation

Trace for Loop, cont.


Execute initializer
i is now 0
for (int i = 0; i < 2; i++)
{
printf("Welcome to Java!");
}

116
animation

Trace for Loop, cont.


(i < 2) is true
since i is 0
for (int i = 0; i < 2; i++)
{
printf("Welcome to Java!");
}

117
animation

Trace for Loop, cont.


Print Welcome to Java

for (int i = 0; i < 2; i++)


{
printf("Welcome to Java!");
}

118
animation

Trace for Loop, cont.


Execute increment statement
i now is 1
for (int i = 0; i < 2; i++)
{
printf("Welcome to Java!");
}

119
animation

Trace for Loop, cont.


(i < 2) is still true
since i is 1
for (int i = 0; i < 2; i++)
{
printf("Welcome to Java!");
}

120
animation

Trace for Loop, cont.


Print Welcome to Java

for (int i = 0; i < 2; i++)


{
printf("Welcome to Java!");
}

121
animation

Trace for Loop, cont.


Execute increment statement
i now is 2
for (int i = 0; i < 2; i++)
{
printf("Welcome to Java!");
}

122
animation

Trace for Loop, cont.


(i < 2) is false
since i is 2
for (int i = 0; i < 2; i++)
{
printf("Welcome to Java!");
}

123
animation

Trace for Loop, cont.


Exit the loop. Execute the next
statement after the loop
for (int i = 0; i < 2; i++)
{
printf("Welcome to Java!");
}

124
Which Loop to Use?
Use the one that is most intuitive and comfortable for
you. In general:
- A for loop may be used if the number of repetitions is
known, as, for example, when you need to print a
message 100 times.
- A while loop may be used if the number of repetitions
is not known, as in the case of reading the numbers
until the input is 0.
- A do-while loop can be used to replace a while loop if
the loop body has to be executed before testing the
continuation condition. 125
#include <stdio.h>
int main() {
int i = 1;

while (i <= 5)
{
printf("%d\n", i);
++i;
}

return 0;
}
Output:
#include <stdio.h>
int main() { 1
int i = 1; 2
3
4
while (i <= 5) 5
{
printf("%d\n", i);
++i;
}

return 0;
}
#include <stdio.h>

int main() {
int i;

for (i = 1; i < 11; ++i)


{
printf("%d ", i);
}
return 0;
}
#include <stdio.h> Output:
1
2
int main() { 3
4
int i; 5
6
7
8
for (i = 1; i < 11; ++i) 9
10
{
printf("%d\n ", i);
}
return 0;
}
// Program to calculate the sum of first n natural
numbers
// Positive integers 1,2,3...n are known as natural
numbers
for(count = 1; count <= num; ++count)
#include <stdio.h> {
int main() sum += count;
{ }
int num, count, sum = 0;
printf("Sum = %d", sum);
printf("Enter a positive integer: "); return 0;
scanf("%d", &num); }
Output:
// for loop terminates when num is less than Enter a positive integer: 10
Sum = 55
count
The break statement

• The break statement causes execution to “break” out of the repetitive loop
execution (goes to just outside the loop’s closing “}”)

132
Example:
int i;

for (i = 0; i < 10; i++) {


if (i == 4) {
break;
}
printf("%d\n", i);
}
Example: Output:

0
int i; 1
2
3
for (i = 0; i < 10; i++) {
if (i == 4) {
break;
}
printf("%d\n", i);
}
Continue
The continue statement breaks one iteration (in the loop), if a specified
condition occurs, and continues with the next iteration in the loop.

int i;
for (i = 0; i < 10; i++) {
if (i == 4) {
continue;
}
printf("%d\n", i);
}
Continue
The continue statement breaks one iteration (in the loop), if a specified
condition occurs, and continues with the next iteration in the loop.

int i; Output:
0
1
for (i = 0; i < 10; i++) { 2
if (i == 4) { 3
continue; 5
} 6
7
printf("%d\n", i); 8
} 9
goto
• Goto statement in C is a jump statement that
is used to jump from one part of the code to
any other part of the code in C.
• Goto statement helps in altering the normal
flow of the program according to our needs.
• This is achieved by using labels, which means
defining a block of code with a name so that
we can use the goto statement to jump to that
label.
Example:
#include <stdio.h>
#include <math.h> // to make the number positive multiply by -1
n = n*(-1);

int main() // declare positive label


{
// initialize variable whose absolute value is to be printed positive :
int n = -11;
printf("The absolute value is %d", n);

// if the number is already positive, print it directly return 0;


if(n>=0)
{ }
// goto statement
goto positive;
}
Example:
#include <stdio.h>
#include <math.h> // to make the number positive multiply by -1
n = n*(-1);

int main() // declare positive label


{
// initialize variable whose absolute value is to be printed positive :
int n = -11;
printf("The absolute value is %d", n);

// if the number is already positive, print it directly return 0;


if(n>=0)
{ }
// goto statement
goto positive; Output:
} The absolute value is 11
Example programs:
1. Write a C program to generate Fibonacci series of n numbers.
2. Write a C program to find the factorial of a given number
3. Write a C program to find the sum of digits of a given number.
4. Write a C program to find whether a given number is palindrome or
not
#include <stdio.h>
int main()
{
int i, n; // initialize first and second terms
int t1 = 0, t2 = 1; // initialize the next term (3rd term)
int nextTerm; // get no. of terms from user
printf("Enter the number of terms: ");
scanf("%d", &n); // print the first two terms t1 and t2
printf("Fibonacci Series: %d, %d, ", t1, t2); // print 3rd to nth terms
for (i = 2; i < n; ++i)
{
nextTerm = t1 + t2;
printf("%d\n ", nextTerm);
t1 = t2;
t2 = nextTerm;
}
return 0;
}
#include <stdio.h>
int main()
{
int n, i;
int fact = 1;
printf("Enter an integer: ");
scanf("%d", &n); // shows error if the user enters a negative integer
if (n < 0)
printf("Error! Factorial of a negative number doesn't exist.");
else
{
for (i = 1; i <= n; ++i)
{
fact *= i;
}
printf("Factorial of %d = %d", n, fact);
}
return 0;
}
Sum of digits

To get sum of each digits by c program, use the following algorithm:


• Step 1: Get number by user
• Step 2: Get the modulus/remainder of the number
• Step 3: sum the remainder of the number
• Step 4: Divide the number by 10
• Step 5: Repeat the step 2 while number is greater than 0.
#include<stdio.h>
int main()
{
int n,sum=0,temp;
printf("Enter a number:");
scanf("%d",&n);
while(n>0)
{
temp=n%10;
sum=sum+m;
n=n/10;
}
printf("Sum is=%d",sum);
return 0;
}
#include <stdio.h>
int main()
{
int n, reversed = 0, remainder, original;
printf("Enter an integer: ");
scanf("%d", &n);
original = n; // palindrome if orignal and reversed
// reversed integer is stored in reversed variable //are equal
while (n != 0) if (original == reversed)
{ printf("%d is a palindrome.",
remainder = n % 10; original);
reversed = reversed * 10 + remainder; else
n /= 10; printf("%d is not a palindrome.",
} original);
}
return 0;
}
#include <stdio.h>
#include <conio.h>
void main()
{
// declaration of variables
int num, binary_num, decimal_num = 0, base = 1, rem;
printf (" Enter a binary number with the combination of 0s and 1s \n");
scanf (" %d", &num); // accept the binary number (0s and 1s)
binary_num = num; // assign the binary number to the binary_num variable
while ( num > 0)
{
rem = num % 10; /* divide the binary number by 10 and store the remainder in rem variable. */
decimal_num = decimal_num + rem * base;
num = num / 10; // divide the number with quotient
base = base * 2;
}
printf ( " The binary number is %d \t", binary_num); // print the binary number
printf (" \n The decimal number is %d \t", decimal_num); // print the decimal
}

You might also like