You are on page 1of 183

18CSS101J

PROGRAMMING FOR
PROBLEM SOLVING

UNIT 2
Course Learning Outcome (CLO – 1)

• Apply the logic operators and expressions.


• Use loop constructs and recursion.
• Use array to store and retrieve data.
Topics that will be covered in this Session

• Relational and logical Operators


• Condition Operators, Operator Precedence
• Expressions with Pre / Post Increment Operator
• Expression with Conditional and Assignment Operators
• If Statement in Expression
• L value and R value in Expression
RELATIONAL OPERATORS
Relational Operator
• Relational operator checks the relationship between two operands.
• These operators are used to compare the value of two variables.
• If the relation is true, it returns value 1 and if the relation is false, it returns
value 0.

Syntax:

(arithmetic_expression 1) relational_operator (arithmetic_expression 2)

Example:

10<= 20
Relational Operator (Cont..)

• A simple relational Operators


Greater than (>) Operator
• Represented as ‘>’, the greater than operator checks whether the first
operand is greater than the second operand or not. If so, it returns true.
Otherwise it returns false. For example, 6>5 will return true.

Program: Output:

#include <stdio.h> M is greater than n


int main() • In this program, relational operator
{ (>) is used to compare 2 values
int m=40,n=20; whether m is greater than n.
if (m > n) • If m is greater than n, output is
printf("m is greater than n"); displayed as ” m is greater than n”.
else Else, output is displayed as “m is less
printf("m is less than n"); than n”.
}
Less than (<) Operator
• Represented as ‘>’, the less than operator checks whether the first operand
is less than the second operand or not. If so, it returns true. Otherwise it
returns false. For example, 6<5 will return false.
Program: Output:

#include <stdio.h> m is greater than n


int main()
{ • In this program, relational
int m=40,n=20; operator (>) is used to compare
if (m < n) 2 values whether m is less than
printf("m is less than n"); n.
else • If m is less than n, output is
printf("m is greater than n"); displayed as ” m is less than
} n”. Else, output is displayed as
“m is greater than n”.
Greater than or equal to (>=) Operator
• Represented as ‘>=’, the greater than or equal to operator checks whether
the first operand is greater than or equal to the second operand. If so, it
returns true else it returns false. For example, 5>=5 will return true.

Program: Output:

#include <stdio.h> m is less than n


int main()
{ • In this program, relational operator
int m=10,n=20; (>=) is used to compare 2 values
if (m >= n) whether m is greater than or equal to
printf("m is greater than or equal to n"); n.
else
• If m is greater than or equal to than n,
printf("m is less than n");
}
output is displayed as ” m is greater
than or equal to n”. Else, output
is displayed as “m is less than n”.
Less than or equal to (<=) Operator
• Represented as ‘<=’, the less than or equal to operator checks whether the
first operand is less than or equal to the second operand. If so, it returns
true else it returns false. For example, 5<=5 will return true.
Program: Output:

#include <stdio.h> m is greater than n


int main()
• In this program, relational
{
operator (<=) is used to compare 2
int m=40,n=20;
values whether m is less than or
if (m <= n)
equal to n.
printf("m is less than or equal to n");
• If m is less than or equal to than n,
else
output is displayed as ” m is less
printf("m is greater than n");
than or equal to n”. Else, output is
}
displayed as “m is greater than n”.
Equal to (==) Operator
• Represented as ‘==’, the equal to operator checks whether the two given
operands are equal or not. If so, it returns true. Otherwise it returns false.
For example, 5==5 will return true. Output:

M and n are not equal


Program:
• In this program, relational operator (==)
#include <stdio.h> is used to compare 2 values whether
int main() they are equal are not.
{ • If both values are equal, output is
int m=40,n=20; displayed as ” values are equal”. Else,
if (m == n) output is displayed as “values are not
printf("m and n are equal"); equal”.
else • Double equal sign (==) should be used
printf("m and n are not equal"); to compare 2 values. We should not
} single equal sign (=).
Not Equal to (!=) Operator
• Represented as ‘!=’, the not equal to operator checks whether the two given
operands are equal or not. If not, it returns true. Otherwise it returns false.
It is the exact boolean complement of the ‘==’ operator. For
example, 5!=5 will return false.
Program: Output:

M and n are not equal


#include <stdio.h>
int main()
{ • In this program, relational operator
int m=40,n=20; (!=) is used to compare 2 values
if (m != n) whether they are equal are not.
printf("m and n are equal"); • If both values are equal, output is
else displayed as ” values are equal”.
printf("m and n are not equal"); Else, output is displayed as “values
} are not equal”.
Different Relational Operators Summary
Example
Output
Relational Operator Complements
• Among the six relational operators, each one is a complement of another
operator.
> is complement of < =
< is complement of > =
= = is complement of ! =
• We can simplify an expression involving the not and the less than
operators using the complements as shown below:
LOGICAL OPERATOR
Logical Operator
• An expression containing logical operator returns either 0 or 1 depending
upon whether expression results true or false. It is otherwise called as
compound relational expression.
Logical Operator – Truth Table
Syntax:
(arithmetic expression 1) logical_operator (arithmetic expression 2)

Example:
a > b && x == 10
Logical AND (&&) Operator
• The ‘&&’ operator returns true when both the conditions under
consideration are satisfied. Otherwise it returns false.
• For example, a && b returns true when both a and b are true (i.e. non-
zero).
Program:

#include <stdio.h>
int main() Output:
{
AND condition not
int a=10,b=4,c=10,d=20;
satisfied
if (a>b && c==d)
printf(“a is greater than b AND c is equal to d \n");
else
printf(“AND condition not satisfied");
}
Logical OR (||) Operator
• The ‘||’ operator returns true even if one (or both) of the conditions under
consideration is satisfied. Otherwise it returns false.
• For example, a || b returns true if one of a or b or both are true (i.e. non-
zero). Of course, it returns true when both a and b are true.

Program:

#include <stdio.h> Output:


int main()
{ a is greater than b OR c
int a=10,b=4,c=10,d=20; is equal to d
if (a>b || c==d)
printf(“a is greater than b OR c is equal to d \n");
else
printf(“Neither a is greater than b nor c is equal");
}
Logical NOT (!) Operator
• The ‘!’ operator returns true the condition in consideration is not satisfied.
Otherwise it returns false.
• For example, !a returns true if a is false, i.e. when a=0.

Program:
Output:
#include <stdio.h>
int main() A is not zero
{
int a=10;
if ( !a )
printf(“a is zero\n");
else
printf(“a is not zero”);
}
Example

Output
CONDITION OPERATOR
Condition Operator
• The conditional statements are the decision-making statements that
depend upon the output of the expression. It is represented by two
symbols, i.e., '?' and ':’.
• As a conditional operator works on three operands, so it is also known as
the ternary operator.
• The behavior of the conditional operator is similar to the ‘if-else’ statement
as 'if-else' statement is also a decision-making statement.
Syntax: Example: Achieved using if-else:
Condition Operator - Example
. Program:

#include <stdio.h>
int main()
{
int age;
printf("Enter your age");
scanf("%d",&age);
(age>=18)? (printf("eligible for voting")) : (printf("not eligible for voting"));
return 0;
}

Output: Output:
OPERATOR PRECEDENCE
Operator Precedence
• The operators within C are grouped hierarchically according to their
precedence.
• Operations with a higher precedence are carried out before operations
having a lower precedence.
• The natural order of evaluation can be altered through the use of
parentheses.
• Parenthesis can be nested, one pair within another.
• In such cases, the innermost operations are carried out first, then the next
innermost operations and so on.
• Associativity is the order in which consecutive operations within the same
precedence group are carried out.
Operator Precedence - Example
• Operator precedence determines which operator is performed first in an
expression with more than one operators with different precedence.
Operator Associativity
• Operators Associativity is used when two operators of same precedence
appear in an expression.
• Associativity can be either Left to Right or Right to Left.
• For example:
‘*’ and ‘/’ have same precedence and their associativity
is Left to Right, so the expression “100 / 10 * 10” is treated as “(100 /
10) * 10”.
Operator Associativity - Example
Operator Precedence & Associativity
• Operators Precedence and Associativity are two characteristics of
operators that determine the evaluation order of sub-expressions in
absence of brackets.
• Associativity is only used when there are two or more operators of
same precedence.
• All operators with the same precedence have same associativity.
• Precedence and associativity of postfix ++ and prefix ++ are different.
• Comma has the least precedence among all operators and should be
used carefully.
• There is no chaining of comparison operators in C.
Operator Precedence & Associativity - Example
Summary of Operator Precedence & Associativity
EXPRESSION WITH PRE /
POST INCREMENT
OPERATOR
Expression with Pre Increment Operator
• The pre increment operator is used to increment the value of some variable
before using it in an expression.
• In the pre increment the value is incremented at first, then used inside the
expression.
• If the expression is a = ++b; and b is holding 5 at first, then a will hold 6.
Because increase b by 1, then set the value of a with it.

Syntax
a = ++ b;
Expression with Pre Increment Operator -
Example
Program:
Output:
#include <stdio.h>
int main() Pre Increment Operation
{
int x=10,a; a = 11
a= ++x; x = 11
printf(“Pre Increment Operation");
printf(“\n a = %d“,a);
printf(“\n x = %d“,x);
return 0;
}
Expression with Post Increment Operator
• The post increment operator is used to increment the value of some
variable after using it in an expression.
• In the post increment the value is used inside the expression, then
incremented by one.
• If the expression is a = b++; and b is holding 5 at first, then a will also hold
5. Because increase b by 1 after assigning it into a.

Syntax:
a = b ++;
Expression with Post Increment Operator -
Example
Program:
Output:
#include <stdio.h>
int main() Post Increment Operation
{
int x=10,a; a = 10
a= x++; x = 11
printf(“Post Increment Operation");
printf(“\n a = %d“,a);
printf(“\n x = %d“,x);
return 0;
}
EXPRESSION WITH PRE /
POST DECREMENT
OPERATOR
Expression with Pre Decrement Operator
• The pre decrement operator is used to decrement the value of some
variable before using it in an expression.
• In the pre decrement the value is decremented at first, then used inside the
expression.
• If the expression is a = --b; and b is holding 5 at first, then a will hold 4.
Because decrease b by 1, then set the value of a with it.

Syntax
a = -- b;
Expression with Pre Decrement Operator -
Example
Program:
Output:
#include <stdio.h>
int main() Pre Decrement Operation
{
int x=10,a; a=9
a= --x; x=9
printf(“Pre Decrement Operation");
printf(“\n a = %d“,a);
printf(“\n x = %d“,x);
return 0;
}
Expression with Post Decrement Operator
• The post decrement operator is used to decrement the value of some
variable after using it in an expression.
• In the post decrement the value is used inside the expression, then
decremented by one.
• If the expression is a = b--; and b is holding 5 at first, then a will also hold
5. Because decrease b by 1 after assigning it into a.

Syntax:
a = b --;
Expression with Post Decrement Operator -
Example
Program:
Output:
#include <stdio.h>
int main() Post Decrement Operation
{
int x=10,a; a=10
a= x--; X=9
printf(“Post Decrement Operation");
printf(“\n a = %d“,a);
printf(“\n x = %d“,x);
return 0;
}
EXPRESSION WITH
CONDITIONAL
OPERATORS
Expressions with Conditional Operator
• The conditional operator is kind of similar to the if-else statement as it
does follow the same algorithm as of if-else statement but the conditional
operator takes less space and helps to write the if-else statements in the
shortest way possible.
Syntax:

Variable = Expression1 ? Expression2 : Expression3

If else Statement:
Example:

max = (num1 > num2) ? num1 : num2


Expressions with Conditional Operator
Syntax: Flowchart:
Expressions with Conditional Operator
Program:

#include <stdio.h>
int main() Output:
{
int m,n,max; Enter the value of m and n
printf("Enter the value of m and n"); 10 12
scanf("%d %d",&m,&n);
max=(m > n) ? m : n; The maximum is 12
printf("The maximum is %d",max);
return 0;
}
EXPRESSION WITH
ASSIGNMENT
OPERATORS
Assignment Operator
• Assignment operators are used to assigning value to a variable.
• The left side operand of the assignment operator is a variable and right
side operand of the assignment operator is a value.
• The value on the right side must be of the same data-type of the variable
on the left side otherwise the compiler will raise an error.
Assignment Operator - Example
Program

Output
L VALUE AND R VALUE IN
EXPRESSION
L value in Expression
• L-Value of Expressions refer to a memory locations.
• In any assignment statement L-Value of Expression must be a
container(i.e. must have ability to hold the data).
• Variable is the only container in C programming thus L Value must be any
Variable.
• L Value cannot be a Constant, Function or any of the available data type in
C. L-Value stands for Left Value. Diagram Showing L Value in Expression.
R value in Expression
• In any Assignment statement R-Value of Expression must be anything
which is capable of returning Constant Expression or Constant Value.
• R Value stands for Right value of the expression.
R value in Expression - Example

• R value may be a Constant or Constant Expression


• R value may be a MACRO
• R Value may be a variable
L value & R value in Expression - Example
L value & R value in Expression - Example
IF STATEMENT IN
EXPRESSION
If statement in Expression
• It is one of the powerful conditional statement.
• If statement is responsible for modifying the flow of execution of a
program.
• If statement is always used with a condition.
• The condition is evaluated first before executing any statement inside the
body of If. The syntax for if statement is as follows:

• The condition evaluates to either true or


false.
• True is always a non-zero value, and false
is a value that contains zero.
• Instructions can be a single instruction or
a code block enclosed by curly braces { }.
If statement in Expression (Cont…)

• The condition evaluates to either true or


false.
• True is always a non-zero value, and false
is a value that contains zero.
• Instructions can be a single instruction or
a code block enclosed by curly braces { }.
If statement in Expression (Cont…)
Program Output
18CSS101J
PROGRAMMING FOR
PROBLEM SOLVING

UNIT 2
Course Learning Outcome (CLO – 1)

• Apply the logic operators and expressions.


• Use loop constructs and recursion.
• Use array to store and retrieve data.
Topics that will be covered in this Session

• Control Statements – if and else


• Else if and nested if, switch case
• Iterations, conditional and unconditional branching
• For loop
• While Loop
• Do while, goto, break, continue
CONTROL STATEMENTS
Control Statements

• Control statements enable us to specify the flow of program control; ie,


the order in which the instructions in a program must be executed.
• They make it possible to make decisions, to perform tasks repeatedly or to
jump from one section of code to another.
• Decision making statements in programming languages decides the
direction of flow of program execution.
• Conditional Statements in C programming are used to make decisions
based on the conditions.
• Conditional statements execute sequentially when there is no condition
around the statements.
Control Statements (Cont..)

• C language possesses such decision-making capabilities by supporting the


following statements:
o if statement
o switch statement
o Conditional operator statement
o goto statement
• These statements are popularly known as decision-making statements.
Since these statements ‘control’ the flow of execution, they are also known
as control statements.
IF STATEMENTS
if Statements
• The if statement may be implemented in different forms depending on the
complexity of conditions to be tested. The different forms are,
• Simple if statement
• if else statement
• Nested if else statement
• if else ladder statement
Simple if Statements
• if statement is the most simple decision making statement.
• It is used to decide whether a certain statement or block of statements will
be executed or not i.e if a certain condition is true then a block of statement
is executed otherwise not.
Simple if Statements (Cont..)
• The if statement evaluates the test expression inside the parenthesis().
• If the test expression is evaluated to true, statements inside the body of if
are executed.
• If the test expression is evaluated to false, statements inside the body of if
are not executed.
Simple if Statements - Example
// Program to display a number if it is negative Output:

#include <stdio.h> Enter an integer: -8


int main() You entered -8.
{ The if statement is easy.
int number;
printf("Enter an integer: "); Enter an integer: 5
scanf("%d", &number); The if statement is easy.
// true if number is less than 0
if (number < 0) Enter an integer: 0
{ The if statement is easy.
printf("You entered %d.\n", number);
}
printf("The if statement is easy.");
return 0;
}
Simple if Statements - Example
// Program to find biggest among two numbers Output:

#include <stdio.h> Enter the x and y value:


int main() 5
{ 2
int x,y;
printf("Enter the x and y value: "); x is greater than y.
scanf("%d%d", &x,&y);

if (x > y) Enter the x and y value:


{ 2
printf(“x is greater than y.\n"); 5
}

return 0;
}
If – else Statements
• The if...else statement is an extension of the simple if statement.
• If the test expression is true, then the true-block statement(s), immediately
following the if statements are executed; otherwise, the false-block
statement(s) are executed.
• In either case, either true-block or false-block will be executed, not both.
• The general form is,
If – else Statements (Cont..)
• Let us consider an example of counting the number of boys and girls in a class. We use
code 1 for a boy and 2 for a girl.
• The program statement to do this may be written as follows:

• The first test determines whether or not the student is a boy.


• If yes, the number of boys is increased by 1 and the program continues to the second test.
• The second test again determines whether the student is a girl.
If – else Statements (Cont..)
• Once a student is identified as a boy, there is no need to test again for a girl. A student can
be either a boy or a girl, not both.
• The above program segment can be modified using the else clause as follows:

• Here, if the code is equal to 1, the statement boy = boy + 1; is executed and the control is
transferred to the statement xxxxxx, after skipping the else part.
• If the code is not equal to 1, the statement boy = boy + 1; is skipped and the statement in
the else part girl = girl + 1; is executed before the control Xreaches the statement xxxxxxxx.
If – else Statements (Cont..)
• If the test expression is evaluated to true, statements inside the body of if
are executed and statements inside the body of else are skipped from
execution.
• If the test expression is evaluated to false, statements inside the body of
else are executed and statements inside the body of if are skipped from
execution.
If - else Statements - Example
// Check whether an integer is odd or even
Output:
#include <stdio.h>
int main()
Enter an integer: 10
{
10 is an even integer.
int number;
printf("Enter an integer: ");
scanf("%d", &number);
Enter an integer: 7
if (number%2 == 0)
10 is an odd integer.
{
printf("%d is an even integer.",number);
}
else
{
printf("%d is an odd integer.",number);
}
return 0;
}
If - else Statements - Example
// Find biggest among two numbers
Output:
#include <stdio.h>
int main()
y is greater than x.
{
int x, y;
x = 15;
y = 18;
if (x > y )
{
printf("x is greater than y");
}
else
{
printf("y is greater than x");
}
return 0;
}
Nested if – else Statements
• When a series of decisions are
involved, we may have to use
more than one if...else statement in
nested form.
• If the condition-1 is false, the
statement-3 will be executed;
otherwise it continues to perform
the second test.
• If the condition-2 is true, the
statement-1 will be evaluated;
otherwise the statement-2 will be
evaluated and then the control is
transferred to the statement-x.
Nested if – else Statements (Cont..)
Nested if – else Statements (Cont..)
• A commercial bank has introduced
an incentive policy of giving bonus
to all its deposit holders.
• The policy is as follows: A bonus of
2 per cent of the balance held on
31st December is given to every
one, irrespective of their balance,
and 5 per cent is given to female
account holders if their balance is
more than Rs. 5000.
Nested if – else Statements (Cont..)
• When nesting, care should be exercised to match every if with an else. Consider the
following alternative to the above program.

• There is an ambiguity as to over which if the else belongs to.


• In C, an else is linked to the closest non-terminated if. Therefore, the else is associated
with the inner if and there is no else option for the outer if.
• This means that the computer is trying to execute the statement
balance = balance + bonus;
• without really calculating the bonus for the male account holders.
Nested if – else Statements (Cont..)
• Consider another alternative, which also looks correct:

• In this case, else is associated with the outer if and therefore bonus is
calculated for the male account holders.
• However, bonus for the female account holders, whose balance is equal to
or less than 5000 is not calculated because of the missing else option for
the inner if.
Nested if - else Statements - Example
// Find biggest among three numbers else
{
#include <stdio.h> if(b > c)
void main( ) printf("b is the greatest");
{ else
int a, b, c; printf("c is the greatest");
printf("Enter 3 numbers..."); }
scanf("%d%d%d",&a, &b, &c); }
if(a > b)
{ Output:
if(a > c)
printf("a is the greatest"); Enter 3 numbers...
else 8 5 23
printf("c is the greatest"); C is the greatest
}
Nested if - else Statements - Example
Output:

Enter two integers:


8 5
Result: 8 > 5

Enter two integers:


5 5
Result: 5 = 5

Enter two integers:


2 7
Result: 2 < 7
if – else ladder Statements
• There is another way of putting ifs together when multipath decisions are
involved.
• A multipath decision is a chain of ifs in which the statement associated
with each else is an if. This construct is known as the else if ladder.
• The conditions are evaluated from the top (of the ladder), downwards.
• As soon as a true condition is found, the statement associated with it is
executed and the control is transferred to the statement-x (skipping the
rest of the ladder).
• When all the n conditions become false, then the final else containing the
default-statement will be executed.
if – else ladder Statements (Cont..)
if – else ladder Statements (Cont..)
if – else Ladder Statements (Cont..)
• Let us consider an example of • This grading is done using else if ladder
grading the students in an if (marks > 79)
academic institution. The grading grade = “Honours”;
is done according to the following else if (marks > 59)
rules: grade = “First Division”;
else if (marks > 49)
grade = “Second Division”;
else if (marks > 39)
grade = “Third Division”;
else
grade = “Fail”;
printf (“%s\n”, grade);
if – else Ladder Statements - Example
• An electric power distribution company else if (units <= 400)
charges its domestic consumers as follows: charges = 100 + 0.65 * (units - 200);
else if (units <= 600)
charges = 230 + 0.8 * (units - 400);
else
charges = 390 + (units - 600);
main()
printf(“\n\nCustomer No: %d: Charges =
{ %.2f\n”,custnum, charges);
int units, custnum; }
float charges; Output:
printf(“Enter CUSTOMER NO. and UNITS
consumed\n”);
scanf(“%d %d”, &custnum, &units);
if (units <= 200)
charges = 0.5 * units;
if - else Ladder Statements - Example
// To display the grade of student
Output:

Enter the marks of a student:


85
Grade=B

Enter the marks of a student:


12
Fail

Enter the marks of a student:


52
Grade=E
if - else Ladder Statements - Example
//To Print weekday based on given number
#include<stdio.h> else if(day==3) else if(day==6) OUTPUT:
int main() { {
{ printf("TUESDAY."); printf("FRIDAY."); Enter day number:5
int day; } } THURSDAY
printf("Enter day number: "); else if(day==4) else if(day==7)
scanf("%d", &day); { { Enter day number:8
if(day==1) printf("WEDNESDAY."); printf("SATURDAY."); INVALID DAY
{ } }
printf("SUNDAY."); else if(day==5) else Enter day number:1
} { { MONDAY
else if(day==2) printf("THURSDAY."); printf("INVALID DAY.");
{ } } Enter day number:6
printf("MONDAY."); return(0); FRIDAY
} }
SWITCH STATEMENTS
The Switch Statements
• The switch statement tests the value of a given variable (or expression) against a
list of case values and when a match is found, a block of statements associated
with that case is executed. The general form of the switch statement is as shown
below:.
• The expression is an integer expression or characters.
Value-1, value-2 ..... are constants or constant
expressions (evaluable to an integral constant) and
are known as case labels.
• Each of these values should be unique within a
switch statement. block-1, block-2 .... are statement
lists and may contain zero or more statements.
• There is no need to put braces around these blocks.
The case labels end with a colon (:).
The Switch Statements (Cont..)

• When the switch is executed, the value of the expression is successfully


compared against the values value-1, value-2,.... If a case is found whose
value matches with the value of the expression, then the block of
statements that follows the case are executed.
• The break statement at the end of each block signals the end of a particular
case and causes an exit from the switch statement, transferring the control
to the statement-x following the switch.
• The default is an optional case. When present, it will be executed if the
value of the expression does not match with any of the case values. If not
present, no action takes place if all matches fail and the control goes to the
statement-x.
The Switch Statements (Cont..)
The Switch Statements (Cont..)
• The switch statement can be used o grade the student
Switch Statements - Example

Output:
Switch Statements - Example
// Print the color
Output:
Rule for Switch Statements
• The switch expression must be an integral type.
• Case labels must be constants or constant expressions.
• Case labels must be unique. No two labels can have the same value.
• Case labels must end with colon.
• The break statement transfers the control out of the switch statement.
• The break statement is optional. That is, two or more case labels may belong to the same
statements.
• The default label is optional. If present, it will be executed when the expression does not
find a matching case label.
• There can be at most one default label.
• The default may be placed anywhere but usually placed at the end.
• It is permitted to nest switch statements.
Difference between Switch case & Nested if
Switch case statement Nested if
• No two case statements can have identical • Same conditions ca be evaluated any
constants in the same switch. number of times.
• The switch case statement checks more • The nested if statement, switch case
option to take a decision. multiple conditions.
• In switch case statement “nested if” can • In nested if statement, switch case can be
be used. used.
• Switch case can check only constant • Nested if can check relational and logical
values. expressions.
The Nested Switch Statements
• It is possible to have a switch as a part of the statement sequence of an outer
switch. Even if the case constants of the inner and outer switch contain common
values, no conflicts will arise.
Nested Switch Statements - Example

Output:
ITERATION
Iteration
• Iteration is the process where a set of instructions or statements is
executed repeatedly for a specified number of time or until a condition is
met.
• These statements also alter the control flow of the program and thus can
also be classified as control statements in C Programming Language.
• Iteration statements are most commonly know as loops.
• Also the repetition process in C is done by using loop control instruction.

Iteration (Cont..)

• Conditional statement executes only once in the program where as


looping statements executes repeatedly several number of time.
• Advantages
o Reduce length of Code
o Take less memory space.
o Burden on the developer is reducing.
o Time consuming process to execute the program is reduced.


Iteration (Cont..)
• For example, suppose we want to calculate the sum of squares of all
integers between 1 and 10, we can write a program using the if statement
as follows:
This program does the following things:
1. Initializes the variable n.
2. Computes the square of n and adds it to
sum.
3. Tests the value of n to see whether it is
equal to 10 or not. If it is equal to 10, then the
program prints the results.
4. If n is less than 10, then it is incremented
by one and the control goes back to compute
the sum again. The program evaluates the
statement: sum = sum + n * n
Iteration (Cont..)

• In looping, a sequence of statements are executed until some conditions


for termination of the loop are satisfied.
• A program loop therefore consists of two segments, one known as the
body of the loop and the other known as the control statement.
• The control statement tests certain conditions and then directs the
repeated execution of the statements contained in the body of the loop.
• Depending on the position of the control statement in the loop, a control
structure may be classified either as the entry-controlled loop or as the
exit-controlled loop.

Iteration (Cont..)
• In the entry-controlled loop, the
control conditions are tested before the
start of the loop execution.
• If the conditions are not satisfied, then
the body of the loop will not be
executed.
• In the case of an exit-controlled loop,
the test is performed at the end of the
body of the loop and therefore the
body is executed unconditionally for
the first time.
• The entry-controlled and exit-
controlled loops are also known as pre-
test and post-test loops respectively.
Iteration (Cont..)
• The test conditions should be carefully stated in order to perform the
desired number of loop executions. It is assumed that the test condition
will eventually transfer the control out of the loop.
• In case, due to some reason it does not do so, the control sets up an infinite
loop and the body is executed over and over again.
• A looping process, in general, would include the following four steps:
1) Setting and initialization of a condition variable.
2) Execution of the statements in the loop.
3) Test for a specified value of the condition variable for execution of the
loop.
4) Incrementing or updating the condition variable.
Iteration (Cont..)

• The test may be either to determine whether the loop has been repeated
the specified number of times or to determine whether a particular
condition has been met.
• The C language provides for three constructs for performing loop
operations. They are:
1) The while statement.
2) The do statement.
3) The for statement.
Iteration (Cont..)
Sentinel Loops
• Based on the nature of control variable and the kind of value assigned to it for testing the
control expression, the loops may be classified into following two general categories:
1) Counter-controlled loops
2) Sentinel-controlled loops
• When we know in advance exactly how many times the loop will be executed, we use a
counter controlled loop. We use a control variable known as counter.
• The counter must be initialized, tested and updated properly for the desired loop
operations.
• The number of times we want to execute the loop may be a constant or a variable that is
assigned a value.
• A counter-controlled loop is sometimes called definite repetition loop.
• In a sentinel-controlled loop, a special value called a sentinel value is used to change the
loop control expression from true to false.
THE WHILE LOOP
While Loop
• A while loop in C programming
repeatedly executes a target
statement as long as a given
condition is true.
• in the while loop, first the
condition is checked and then the
statements in while loop are
executed.
• If a condition is false at the first
place then the do while would run
once, however the while loop
would not run at all.
While Loop
• The while is an entry-controlled loop statement. The test-condition is
evaluated and if the condition is true, then the body of the loop is
executed.
• After execution of the body, the test-condition is once again evaluated and
if it is true, the body is executed once again. This process of repeated
execution of the body continues until the test-condition finally becomes
false and the control is transferred out of the loop.
• On exit, the program continues with the statement immediately after the
body of the loop.
• The body of the loop may have one or more statements. The braces are
needed only if the body contains two or more statements. It is a good
practice to use braces even if the body has only one statement.
While Loop (Cont..)

• The body of the loop is executed 10 times for n = 1, 2, ....., 10, each time
adding the square of the value of n, which is incremented inside the loop.
• The test condition may also be written as n < 11; the result would be the
same. This is a typical example of counter-controlled loops. The variable n
is called counter or control variable.
While Loop - Example
// Sum of the digits
Output:
#include <stdio.h>
Enter the value:
int main()
456
{
The sum of the digit is 15
int n,r,sum=0;
printf(“ Enter the value of n:”);
scanf(“%d”,&n);
Enter the value:
while(n>0)
123
{
The sum of the digit is 6
r=n%10;
sum=sum=r;
n=n/10;
}
printf(“The sum of the digit is %d“,sum);
return 0;
}
While Loop - Example
// Given number is Armstrong or not
Output:
#include <stdio.h>
int main() {
Enter the value of n:
int n,r,arm=0,t;
2589
printf("Enter the value of n:");
scanf("%d",&n);
The number 2589 is not
t=n;
an Armstrong number.
while(n>0) {
r=n%10;
arm=arm+r*r*r;
n=n/10;
Enter the value of n:
}if(t==arm)
153
printf("The number %d is an armstrong number.",t);
else
The number 153 is an
printf("The number %d is not an armstrong number.",t);
Armstrong number.
return 0;
}
While Loop - Example
// Factorial on n numbers
Output:
#include <stdio.h>
int main() Enter the value of n:
{ 5
int n,i=1,fact=1;
printf("Enter the value of n : "); 5! = 120
scanf("%d",&n);
while(i<=n)
{
fact=fact*i; Enter the value of n:
i++; 6
}
printf("%d ! = %d",n,fact); 6! = 720
return 0;
}
While Loop - Example
// Find the average of n numbers
#include <stdio.h> Output:
int main() {
int n,i=0;
How many numbers : 5
float x,avg,sum=0;
printf("How many numbers : "); Enter the numbers
scanf("%d",&n); 23 76 9 456 632
printf("Enter the numbers\n"); Average = 239.200000
while(i<n)
{
scanf("%f",&x);
sum=sum+x; How many numbers : 5
i++; Enter the numbers
}
56 65 45 85 21
avg=sum/n;
printf("Average = %f",avg); Average = 54.400002
return 0;
}
THE DO WHILE LOOP
Do While Loop
• A do while loop is similar to while loop with one exception that it executes
the statements inside the body of do-while before checking the condition.
• The do statement, the program proceeds to evaluate the body of the loop
first.
• At the end of the loop, the test-condition in the while statement is
evaluated.
• If the condition is true, the program continues to evaluate the body of the
loop once again. This process continues as long as the condition is true.
• When the condition becomes false, the loop will be terminated and the
control goes to the statement that appears immediately after the while
statement.
Do While Loop (Cont..)
• The general form is,
Do While Loop (Cont..)
• The test-condition is evaluated at the bottom of the loop, the do...while
construct provides an exit-controlled loop and therefore the body of the
loop is always executed at least once.
• This segment of a program reads a
number from the keyboard until a
zero or a negative number is keyed
in, and assigned to the sentinel
variable number.
• The test conditions may have
compound relations as well. For
instance, the statement

while (number > 0 && number < 100);


Do While Loop - Example
// Reverse the given digits
Output:
#include <stdio.h>
Enter the value:
int main()
456
{
The reversed digit is 654
int n,r,rev=0;
printf(“ Enter the value of n:”);
scanf(“%d”,&n);
Enter the value:
do
123
{
The reversed digit is 321
r=n%10;
rev=rev=r;
n=n/10;
}while(n>0);
printf(“The reversed digit is %d“,rev);
return 0;
}
Do While Loop - Example
// Sum of n numbers Output:

#include <stdio.h> Enter a number:


int main() 10
{ Sum of 10 is 55
int num, i, sum = 0;
printf("Enter a number: ");
scanf("%d", &num); Enter a number:
i = 0; 20
do Sum of 20 is 210
{
sum = sum + i;
i++;
} while (i <= num);
printf(" \n Sum of %d is %d", num, sum);
return 0;}
Difference between while and do while loop
While Loop Do While Loop
• while loop is called Entry-Controlled • do-while loop is called Exit-Controlled
Loop. Loop.
• When a loop is constructed using the • When a loop is constructed using the do-
while statement, the test for continuation while statement, the test for continuation
of the loop is carried out at the beginning of the loop is carried out at the end of
of each pass. each pass.
• If the condition is false in the first time, • Even if the condition is false in the first
then the statements enclosed within the time, the statements enclosed within the
loop will not be executed. loop will be executed once, since the test
for repetition does not occur until the end
of the first pass through the loop.
THE FOR LOOP
For Loop
• A for loop is a repetition control structure that allows you to efficiently
write a loop that needs to execute a specific number of times.

• The initial value of the for loop is performed only once.


• The condition is a Boolean expression that tests and compares the counter
to a fixed value after each iteration, stopping the for loop when false is
returned.
• The incrementation/decrementation increases (or decreases) the counter by
a set value.
For Loop (Cont..)

• This for loop is executed 10 times and prints the


digits 0 to 9 in one line.
• The three sections enclosed within parentheses must
be separated by semicolons. There is no semicolon at
the end of the increment section, x = x+1.
For Loop - Example
// Given number is prime or not
Output:
#include <stdio.h>
Input a number:
int main() {
13
int num,i,ctr=0;
13 is a prime number.
printf("Input a number: ");
scanf("%d",&num);
for(i=2;i<=num/2;i++){
Input a number:
if(num % i==0){
25
ctr++;
25 is not a prime number.
break; } }
if(ctr==0 && num!= 1)
printf("%d is a prime number.\n",num);
else
printf("%d is not a prime number",num);
return 0;
}
For Loop - Example
// To display the first 10 natural numbers. Output:

#include <stdio.h> The first 10 natural numbers


int main() are:
{ 1
int i; 2
printf("The first 10 natural numbers are:\n"); 3
for (i=1;i<=10;i++) 4
5
{
6
printf("%d ",i);
7
printf("\n");
8
} 9
return 0; 10
}
NESTED LOOP
Nested loop
• C programming allows to use one loop inside another loop.

Nested For Loop: Nested while Loop: Nested do while Loop:


Nested For Loop - Example
// To find the prime numbers from 2 to 50
Output:
2 is prime
#include <stdio.h>
3 is prime
int main()
5 is prime
{
7 is prime
int i, j;
11 is prime
for(i = 2; i<50; i++)
13 is prime
{
17 is prime
for(j = 2; j <= (i/j);j++)
19 is prime
if(!(i%j))
23 is prime
break;
29 is prime
if(j > (i/j))
31 is prime
printf("%d is prime\n", i);
37 is prime
}
41 is prime
return 0;
43 is prime
}
47 is prime
Nested do while Loop - Example
// To find the prime numbers from 2 to 50
Output:
Nested while Loop - Example
// Print the value in row and column
Output:
GOTO
Goto
• The goto requires a label in order to identify the place where the branch is
to be made.
• A label is any valid variable name, and must be followed by a colon.
• The label is placed immediately before the statement where the control is
to be transferred. • If the label: is before the statement
goto label; a loop will be formed
and some statements will be
executed repeatedly. Such a jump is
known as a backward jump.
• If the label: is placed after the goto
label; some statements will be
skipped and the jump is known as
a forward jump.
Goto (Cont..)
• A goto is often used at the end of a program to direct the control to go to the input
statement, to read further data. Consider the following example:
• This program is written to evaluate the
square root of a series of numbers read
from the terminal.
• The program uses two goto statements, one
at the end, after printing the results to
transfer the control back to the input
statement and the other to skip any further
computation when the number is negative.
• Due to the unconditional goto statement at
the end, the control is always transferred
back to the input statement.
• This program puts the computer in a
permanent loop known as an infi nite loop.
Goto - Example
#include <stdio.h> Output:
int main()
{ 0 1 2 3 4 5
int i; Came outside of loop i = 5
for(i = 0; i<10; i++)
{
printf("%d ",i);
if(i == 5)
break;
}
printf("came outside of loop i = %d",i);
return 0;
}
BREAK
Break
• When a break statement is Syntax: break;
encountered inside a loop, the loop
is immediately terminated and the
program control resumes at the
next statement following the loop.
• It can be used to terminate a case
in the switch statement.
• If you are using nested loops, the
break statement will stop the
execution of the innermost loop
and start executing the next line of
code after the block.
Break - Example
#include <stdio.h> Output:
int main()
{ value of a: 10
int a = 10; value of a: 11
while( a < 20 ) value of a: 12
{ value of a: 13
printf("value of a: %d\n", a); value of a: 14
a++; value of a: 15
if( a > 15)
{
break;
}
}
return 0;
}
CONTINUE
Continue
• The continue statement in C Syntax: continue;
programming works somewhat
like the break statement.
• It forces the next iteration of the
loop to take place, skipping any
code in between.
• For loop, continue statement
causes the conditional test and
increment portions of the loop to
execute.
• The while and do...while loops,
continue statement causes the
program control to pass to the
conditional tests.
Continue - Example
#include <stdio.h>
int main()
Output:
{
int a = 10;
value of a: 10
do
value of a: 11
{
value of a: 12
if( a == 15)
value of a: 13
{
value of a: 14
a = a + 1;
value of a: 16
continue;
value of a: 17
}
value of a: 18
printf("value of a: %d\n", a);
value of a: 19
a++;
} while( a < 20 );
return 0;
}
18CSS101J
PROGRAMMING FOR
PROBLEM SOLVING

UNIT 2
Course Learning Outcome (CLO – 1)

• Apply the logic operators and expressions.


• Use loop constructs and recursion.
• Use array to store and retrieve data.
Topics that will be covered in this Session

• Array Basic and Types


• Array initialization and declaration
• Initialization: one dimensional array
• Accessing, Indexing one dimensional array operations
• One dimensional array operations
• Array program – 1D
ARRAY BASIC & TYPES
Array
• Arrays a kind of data structure that can store a fixed-size sequential
collection of elements of the same type.
• An array is used to store a collection of data, but it is often more useful to
think of an array as a collection of variables of the same type.
• Arrays are the derived data type in C programming language which can
store the primitive type of data such as int, char, double, float, etc.
• It also has the capability to store the collection of derived data types, such
as pointers, structure, etc.
• The array is the simplest data structure where each data element can be
randomly accessed by using its index number.
Array (Cont..)
• Instead of declaring individual variables, such as number0, number1, ...,
and number99, you declare one array variable such as numbers and use
numbers[0], numbers[1], and ..., numbers[99] to represent individual
variables.
• A specific element in an array is accessed by an index.
• All arrays consist of contiguous memory locations.
• The lowest address corresponds to the first element and the highest
address to the last element.
Need for Array
• Used to represent a list of numbers / names .
• Used to represent tabular data in 2, 3 or more dimensions.
• Important Data Structure in any programming language.
• Arrays are faster than dynamic memory allocation.
• Array types are automatically deallocated, when they go out of scope.
Array Definition
• Collection of elements of similar data types.
• Each element is located in separate memory locations.
• Each Array element share a common name
Characteristics of Array

• All elements in the arrays share a common name


• Elements distinguished by index number
• Index (or) element number of an array plays vital role for calling each
element
• Specific array elements can be modified
• Value of array element can be assigned to variables
• Array elements stored in continuous memory locations
Properties of Array
• Each element of an array is of same data type and carries the same size,
i.e., int = 4 bytes.
• Elements of the array are stored at contiguous memory locations where
the first element is stored at the smallest memory location.
• Elements of the array can be randomly accessed since we can calculate the
address of each element of the array with the given base address and the
size of the data element.
Advantages of Array
• Code Optimization: Less code to the access the data.
• Ease of traversing: By using the for loop, we can retrieve the elements of
an array easily.
• Ease of sorting: To sort the elements of the array, we need a few lines of
code only.
• Random Access: We can access any element randomly using the array.
• Easy access to all the elements.
Disadvantages of Array

• Fixed Size: Whatever size, we define at the time of declaration of the


array, we can't exceed the limit.
• Allows a fixed number of elements to be entered which is decided at the
time of declaration. Unlike a linked list, an array in C is not dynamic.
• Insertion and deletion of elements can be costly since the elements are
needed to be managed in accordance with the new memory allocation.
Types of Array
• Array can be classified into two types.
1) One dimensional array
2) Multi dimensional array

Array

One Dimensional Multi Dimensional


Array Array

Two Dimensional Three Dimensional n Dimensional


Array Array Array
ARRAY INITIALIZATION &
DECLARATION
Array Declaration
• To declare an array in C, a programmer specifies the type of the elements
and the number of elements required by an array as follows −
Datatype arrayname [arraysize];
• This is called a single-dimensional array. The arraysize must be an integer
constant greater than zero and type can be any valid C data type.
• For example, to declare a 10-element array called balance of type double,
use this statement −
double balance[10];
• Here balance is a variable array which is sufficient to hold up to 10 double
numbers.
Array Initialization
• Arrays may be initialized when they are declared, just as any other
variables.
• Place the initialization data in curly {} braces following the equals sign.
• An array may be partially initialized, by providing fewer data items than
the size of the array. The remaining array elements will be automatically
initialized to zero.
• If an array is to be completely initialized, the dimension of the array is not
required. The compiler will automatically size the array to fit the
initialized data.
Array Initialization - Example
• An array can be initialize in C either one by one or using a single
statement as follows −
double balance[5] = {1000.0, 2.0, 3.4, 7.0, 50.0};
• The number of values between braces { } cannot be larger than the number
of elements that we declare for the array between square brackets [ ].
• If you omit the size of the array, an array just big enough to hold the
initialization is created. Therefore, if you write −
double balance[ ] = {1000.0, 2.0, 3.4, 7.0, 50.0};
• You will create exactly the same array as you did in the previous example.
Following is an example to assign a single element of the array −
balance[4] = 50.0;
Array Initialization - Example
balance[4] = 50.0;
• The above statement assigns the 5th element in the array with a value of
50.0.
• All arrays have 0 as the index of their first element which is also called the
base index and the last index of an array will be total size of the array
minus 1.
• Shown below is the pictorial representation of the array we discussed
above −
Array - Example

#include <stdio.h> Output:


int main()
{ Value of arr[0] is 10
Value of arr[1] is 20
int i; Value of arr[2] is 30
int arr[5] = {10,20,30,40,50}; Value of arr[3] is 40
for (i=0;i<5;i++) Value of arr[4] is 50
{
printf("value of arr[%d] is %d \n", i, arr[i]);
}
return 0;
}
ONE DIMENSIONAL
ARRAY
One Dimensional Array
• The array which is used to represent and store data in a linear form is
called single or one dimensional array.
• If there is one subscript, then it is called one dimensional array.
• In c programming language, single dimensional arrays are used to store
list of values of same datatype.
• Single dimensional arrays are used to store a row of values.
• In single dimensional array, data is stored in linear form.
• Single dimensional arrays are also called as one-dimensional
arrays, Linear Arrays or simply 1-D Arrays.
Declaration of one Dimensional Array
• A one-dimensional array definition can be expressed as
storage-class data-type array[arraysize];
where
• array → array name
• Data-type → any valid datatype
• arraysize → size of the array
• The storage-class is optional.

Example : int x[100];


Initialization of one Dimensional Array
• Arrays can be initialized. The general form is
data-type array[size] = {value1, value2,..., valuen};
Example: int digits[10]={1,2,3,4,5,6,7,8,9,10};

• The array size need not be specified explicitly when initial values are
included as part of an array definition.

Example : int digits[]={1,2,3,4,5,6,7,8,9,10};


• The array size will be automatically set equal to the number of initial
values included within the definition.
Processing of one Dimensional Array
• Single operations which involve entire arrays are not permitted in C.
• If a and b are similar arrays, operations must be carried out on an element-
by-element basis.
• This is usually accomplished within a loop, where each pass through the
loop is used to process one array element.
• The number of passes through the loop is equal to the number of array
elements to be processed.
Accessing Array Elements
• Array elements are accessed by using an integer index. Array index starts
with 0 and goes till size of array minus 1.
• Name of the array is also a pointer to the first element of array.
• Suppose you declared an array mark. The first element is mark[0], the
second element is mark[1] and so on.
Pictorial representation of the array
• Consider the below example:

int age[5]={22, 25, 30, 32, 35};


Memory representation of the array
• The process of assigning address to a single dimensional array elements is
called memory allocation.
• All the array elements occupy contiguous space in memory.
• There is a difference of 4 among the addresses of subsequent neighbors,
that is because this array is of integer types and an integer holds 4 bytes of
memory.
Characteristics of one Dimensional Array
• Array size should be positive number only.
• String array always terminates with null characters (‘\0’).
• Array elements are counted from 0 to n-1.
• Useful for multiple reading of elements.
Disadvantages of one Dimensional Array
• There is no easy method to initialize large number of array elements.
• It is difficult to initialize selected elements.
One Dimensional Array - Example
// To find sum of n numbers

#include <stdio.h> Output:


int main()
{ How many numbers: 5
int n,a[100],i,sum=0; Enter 5 numbers
printf("How many numbers : "); 85
scanf("%d",&n); 63
printf("Enter %d numbers\n",n); 45
for(i=0;i<n;i++) 25
{ 89
scanf("%d",&a[i]); Sum = 307
sum=sum+a[i];
}
printf("Sum = %d",sum);
return 0;
}
One Dimensional Array - Example
// To find the average of n numbers
#include <stdio.h>
int main() { Output:
int n,a[100],i;
float sum=0,avg; How many numbers: 5
printf("How many numbers : "); Enter 5 numbers
scanf("%d",&n); 58
printf("Enter %d numbers\n",n); 36
for(i=0;i<n;i++) 21
{ 52
scanf("%d",&a[i]); 58
sum=sum+a[i]; Average = 45.000000
}
avg=sum/n;
printf(“Average = %f",avg);
return 0;
}
One Dimensional Array - Example
// To find maximum of n numbers
#include <stdio.h>
int main() { Output:
int n,a[100],i,max;
printf("How many numbers : "); How many numbers: 5
scanf("%d",&n); Enter 5 numbers
printf("Enter %d numbers\n",n); 89
for(i=0;i<n;i++) { 32
scanf("%d",&a[i]); } 100
max=a[0]; 24
for(i=0;i<n;i++) { 54
if(a[i]>max) { Maximum = 100
max=a[i];
} }
printf("Maximum = %d",max);
return 0;
}
One Dimensional Array - Example
// to find minimum of n numbers
#include <stdio.h>
int main() { Output:
int n,a[100],i,min;
printf("How many numbers : "); How many numbers: 5
scanf("%d",&n); Enter 5 numbers
printf("Enter %d numbers\n",n); 89
for(i=0;i<n;i++) { 32
scanf("%d",&a[i]); } 100
min=a[0]; 24
for(i=0;i<n;i++) { 54
if(a[i]<min) { Minimum = 24
min=a[i];
} }
printf("Minimum = %d",min);
return 0;
}
One Dimensional Array - Example
// To find the maximum & minimum of n numbers

Output:

How many numbers: 5


Enter 5 numbers
62
36
21
52
58
Minimum = 21
Maximum = 62
One Dimensional Array - Example
// To reverse an array
Output:

How many numbers: 5


Enter the elements
58
36
21
52
65

The reversed array is


65
52
21
36
58

You might also like