SlideShare a Scribd company logo
18CSS101J
Programming for Problem Solving
UNIT II
Dr.A.Kathirvel, Professor
Dept. of Computer Science and Engineering
Faculty of Engineering &Technology,
SRM Institute of Science andTechnology, Vadapalani campus,
Chennai
RESOURCES
Sno BOOK
1 Zed A Shaw,Learn C the HardWay:Practical Exercises on
the Computational SubjectsYou Keep Avoiding (Like C),
AddisonWesley,2015
2 W.Kernighan,Dennis M.Ritchie,The C Programming
Language,2nd ed.Prentice Hall,1996
3 Bharat Kinariwala,Tep Dobry,Programming in C,eBook
4 http://www.c4learn.com/learn-c-programming-
language/
UNIT 2 Operators, Looping, Array
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 -
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
Array Basic and Types - Array Initialization and Declaration -
Initialization: one Dimensional Array - Accessing, Indexing one
Dimensional Array Operations - One Dimensional Array
operations - Array Programs – 1D
Contents
 Arithmetic operations
 Arithmetic expressions
 Relational operators
 Logical operators
 Assignment operators
 Increment and decrement operators
 Conditional operators
 Type conversions in expressions
4
5
Objectives
♥ To be able to construct and evaluate
expressions.
♥ To master operator precedence and
associativity
♥ To understand implicit type conversion
and explicit type conversion.
Introduction
 An operator is a symbol that tells the computer to perform
certain manipulations.
 An expression is a sequence of operands and operators that
reduces to a single value.
 C operators can be classified into a number of categories.
◦ Arithmetic operators
◦ Relational operators
◦ Logical operators
◦ Assignment operators
◦ Increment and decrement operators
◦ Conditional operators
◦ Bitwise operators
◦ Special operators
6
Arithmetic operators
 The arithmetic operators in C
Operator meaning
+ Addition or unary plus
- Subtraction or unary minus
* Multiplication
/ Division
% modulo division
7
Arithmetic operators
Note:,
Integer division truncates remainder
The % operator cannot be applied to a float
or double.
The precedence of arithmetic operators
Unary + or -
* / %
+ -
8
Arithmetic expressions
An arithmetic expression is a combination of
variables, constants, and operators.
For example,
a*b-c  a*b-c
(m+n)(x+y)  (m+n)*(x+y)
ax2+bx+c  a*x*x+b*x+c
9
Relational Operators
Operator Meaning
< less that
<= less than or equal to
> greater than
>= greater than or equal to
== equal to
!= not equal to
10
• The relational operators in C are :
Relational Operators
A relational expression yields a value of 1
or 0.
5 < 6 1
-34 + 8 > 23 - 5 0
if a=3, b=2, c =1; then a > b > c is ?
the associativity of relational operators is
left  right
11
Relational Operators
Relational operators are used to compare two values to form a
condition.
Math C Plain English
= == equals [example: if(a==b) ]
[ (a=b) means put the value of b into a ]
< < less than
 <= less than or equal to
> > greater than
 >= greater than or equal to
 != not equal to
Logical operators
 C has the following three logical operators
&& meaning logical and
|| meaning logical or
! meaning logical not ( unary operator )
 Expressions connected by && or || are
evaluated left to right, and evaluation stops
as soon as the truth or falsehood of the result
is known.
13
Assignment operators
 The use of shorthand assignment operators has
three advantages:
1.What appears on the left-hand side need not
be repeated and therefore it becomes easier to
write.
2.The statement is more concise and easier to
read.
3.The statement is more efficient.
14
Increment and decrement operators
 C provides two unusual operators for incrementing and
decrementing variables.
 The increment operator ++ adds 1 to its operand, while the
decrement operator -- subtracts 1.
 The unusual aspect is that ++ and -- may be used either as
prefix operators (before the variable, as in ++n), or postfix
operators (after the variable: n++).
 In both cases, the effect is to increment n. But the
expression ++n increments n before its value is used, while
n++ increments n after its value has been used.
15
 The increment and decrement operators can be used in
complex statements. Example:
m=n++ -j +10;
 Consider the expression
m = - n++ ;
 The precedence of ++ and – operators are the same as those
of unary + and -.
 The associatively of them is right to left.
 m = - n++; is equivalent to m = - (n++)
16
Conditional operator
 a ternary operator pair “? : ” is available in C to
construct conditional expressions of the form
expr1 ? expr2 : expr3
 the expression expr1 is evaluated first. If it is non-
zero (true), then the expression expr2 is evaluated,
and that is the value of the conditional expression.
Otherwise expr3 is evaluated, and that is the value.
Only one of expr2 and expr3 is evaluated.
17
Conditions
Examples:
Number_of_Students < 200
10 > 20
20 * j == 10 + i
 z = (a > b) ? a : b;
/* z = max(a, b) */
19
Special operators
 The Comma Operator
 The comma operator can be used to link the related
expressions together.A comma-linked list of expressions is
evaluated left to right and the value of right-most expression
is the value of the combined expression. For example, the
statement
 value = (x=10, y=5, x+y);
 first assigns the value 10 to x, then assigns 5 to y, and finally
assigns 15 to value. Since comma operator has the lowest
precedence of all operators, the parentheses are necessary.
20
Type conversions in expressions
 ImplicitType Conversion
 C permits mixing of constants and variables of different
types in an expression. C automatically converts any
intermediate values to the proper type so that the expression
can be evaluated without loosing any significance.This
automatic conversion is known as implicit type conversion.
 The rule of type conversion: the lower type is automatically
converted to the higher type.
21
Some Computational Problems
 When expressions include real values, then it is important to
take necessary precautions to guard against certain
computational errors. For example, consider the following
statements:
◦ a = 1.0 / 3.0;
◦ b = a * 3.0;
 There is no guarantee that the value of b will equal 1.
 Another problem is division by zero.
 The third problem is to avoid overflow and underflow
errors.
22
Operator Precedence
Which comes first?
* / %
+ -
< <= >= >
== !=
=
Answer:
More Operator Precedence
 Precedence of operators (from highest to lowest)
 Parentheses ( … )
 Unary operators !
 Multiplicative operators * / %
 Additive operators + -
 Relational ordering < <= >= >
 Relational equality == !=
 Logical and &&
 Logical or ||
 Assignment =
More Operator Precedence
 Examples
5 != 6 || 7 <= 3
(5 !=6) || (7 <= 3)
5 * 15 + 4 == 13 && 12 < 19 || !false == 5 < 24
Sorting Two Numbers
int value1;
int value2;
int temp;
Printf("Enter two integers: “);
Scanf(“%d%d”, &value1,&value2;
if(value1 > value2){
temp = value1;
value1 = value2;
value2 = temp;
}
Printf("The input in sorted order: %d%d“, value1 ,
value2;
if-else, switch, while, for, do-while
Control Statements
Conditional Statements
 So far statements of our programs execute sequentially one
after another.
 What happens when
 we want to execute a statement depending on a condition?
 e.g. If there is enough money in the bank account, give the money
 we want to execute one statement when a condition holds and
another statement when a condition does not hold?
 e.g. If dollar is high, sell dollar. Otherwise, buy dollar.
 we want to select from many statements according to one or more
criteria (selection).
 e.g. If dollar is high and euro is low, sell dollar and buy euro. If dollar is low and
euro is high, sell euro and buy dollar. If both of them are high, sell both and buy
YTL.
 You achieve conditional execution with if-else statements
Syntax
if (<condition>)
{
<statement_true_1>;
...
<statement_true_N>;
}
else
{
<statement_false_1>;
...
<statement_false_N>;
}
 If condition is TRUE then
statement_true_1 …
statement_true_N
are executed,
if condition is FALSE
statement_false_1 …
statement_false_N
are executed.
if (<condition>)
{
<statement_true_1>;
...
<statement_true_N>;
}
 else and statement_false’s are
optional
 if condition is FALSE then
nothing will be executed and
execution continues with the
next statement in the program
 <condition> must be in
brackets
Another Syntax (without { })
if (<condition>)
<statement_true>;
else
<statement_false>;
if (<condition>)
<statement_true>;
• Can be used when there is only one statement
• Not suggested (we will see why)
Flow diagram of if-else
test
condition
true
statements
true
next
statement
false
false
statements
if-else example
 Write a program that inputs two integer numbers
and displays the maximum one.
 Two solutions
 using if and else together
 using only if (no else)
33
 The conditional operator (?:) can be used in place of an
if…else statement.
printf( grade >= 60 ? "Passed" : "Failed" );
– The first operand is a boolean expression that evaluates to true
or false.
– The second operand is the value if the expression is true
– The third operand is the value if the expression is false.
Conditional operator (?:)
< less than number < 5
<= less than or equal number <= 0
> greater than num1 > num2
>= greater than or equal num1 >= num2
== equality check num1 == 0
!= inequality check num1 != num2
Relational Operators
 Relational operators are used to compare values:
 They take two operands
 operands can be literals, variables or expressions
 Used for many types
 numeric comparisons
 string comparisons (alphabetical)
Logical operators
 Boolean expressions can be combined using logical
operators: AND, OR, NOT
 In C we use && || ! respectively
A B A || B A && B
true true true true
true false true false
false true true false
false false false false
A ! A
true false
false true
Example
• Range check: between 0 and 100 (includes 0 and 100), or not?
If so, display a message saying that the number is in the range.
If not, the message should say “out of the range”.
• Solution 1: using logical AND operator
if (num >= 0 && num <= 100)
printf("number is in the range");
else
printf("number is out of range");
• Solution 2: using logical AND and NOT operators
if ( ! (num >= 0 && num <= 100) )
printf("number is out of range");
else
printf("number is in the range");
• Solution 3: using logical OR operator
if (num < 0 || num > 100)
printf("number is out of range");
else
printf("number is in the range");
Operator Precedence - Revisited
 Upper operator groups have precedence
Operator Explanation Associativity
+ - ! plus and minus signs, logical NOT right-to-left
* / % multiplication, division and modulus left-to-right
+ - addition, subtraction left-to-right
< <= > >= inequality comparison operators left-to-right
== != equal, not equal comparison left-to-right
&& logical and left-to-right
|| logical or left-to-right
= += -=
*= /= %=
assignment operators right-to-left
Nested if statements
 if/else statements are inside other if/else
statements
 Method to select from multiple choices
 Example: input a numeric grade and convert to
letter grade
90 .. 100 A
80 .. 89 B
70 .. 79 C
60 .. 69 D
0 .. 59 F
otherwise F
39
 This may be written in C# as
if ( grade >= 90 )
printf( "A" );
else
if ( grade >= 80 )
printf( "B" );
else
if ( grade >= 70 )
printf( "C" );
else
if ( grade >= 60 )
printf( "D" );
else
printf( "F" );
Nested if statements
40
 Most C programmers prefer to use else if:
if ( grade >= 90 )
printf( "A" );
else if ( grade >= 80 )
printf( "B" );
else if ( grade >= 70 )
printf( "C" );
else if ( grade >= 60 )
printf( "D" );
else
printf( "F" );
Nested if statements (Cont.)
Short-circuit Evaluation
 Some subexpressions in Boolean expressions are not evaluated if the entire
expression’s value is already known using the subexpression evaluated so far.
 Rule: Evaluate the first (leftmost) boolean subexpression. If its value is
enough to judge about the value of the entire expression, then stop there.
Otherwise continue evaluation towards right.
if (count != 0 && scores/count < 60)
{
printf("low average");
}
 In this example, if the value of count is zero, then first subexpression becomes false
and the second one is not evaluated.
 In this way, we avoid “division by zero” error (that would cause to stop the
execution of the program)
 Alternative method to avoid division by zero without using short-circuit evaluation:
if (count != 0)
{
if (scores/count < 60)
{
printf("low average");
}
}
Dangling Else Problem
if ( x % 2 == 0)
if ( x < 0 )
printf("{0} is an even, negative number %d“, x);
else
printf("{0} is an odd number%d“, x);
 What does it display for x=4?
 The problem is that it displays “odd number” message for positive
even numbers and zero.
 Reason is that, although indentation says the reverse, else belongs
to second (inner) if
 else belongs to the most recent if
 Solution: use braces (see next slide)
Solution to Dangling Else Problem
if ( x % 2 == 0)
{
if ( x < 0 )
printf("{0} is an even, negative number &d“, x);
}
else
{
printf("{0} is an odd number %d“, x);
}
 Now else belongs to the first if
 if – else matching rule
 Each else belongs to the nearest if for which there is no else and in the same
compound block
switch statement
 The switch multiple-selection statement performs different
actions based on the value of an expression.
 Each action is associated with the value of a constant
integral expression or a constant string expression that the
expression may assume.
 Syntax
 Switch( var or identifier)
 { case 1:
 statement;
 break:
 Case 2:
statement;
 break:
 Case n:
private void IncrementLetterGradeCounter( int grade )
{
switch ( grade / 10 )
{
case 9: // grade was in the 90s
case 10: // grade was 100
++aCount;
break; // necessary to exit switch
case 8: // grade was between 80 and 89
++bCount;
break; // exit switch
case 7: // grade was between 70 and 79
++cCount;
break; // exit switch
case 6: // grade was between 60 and 69
++dCount;
break; // exit switch
default: // grade was less than 60
++fCount;
break; // exit switch
}
} // end method IncrementLetterGradeCounter
Flow diagram of switch
47
 The expression after each case can be only a
constant integral expression or a constant string
expression.
 You can also use null and character constants
which represent the integer values of characters.
 The expression also can be a constant that contains a
value which does not change for the entire
application.
switch statement
Multiple Selection:
The switch Statement
value1
action 1
value2
action 2
value3
action 3
value4
action 4
multiway
expression
Multiple Selection:
The switch Statement
Syntax:
switch (<selector expression>) {
case <label1> : <sequence of statements>;
break;
case <label2> : <sequence of statements>;
break;
case <labeln> : <sequence of statements>;
break;
default : <sequence of statements>;
}
Multiple Selection:
The switch Statement
Meaning:
 Evaluate selector expression.
 The selector expression can only be: a bool, an integer, an enum
constant, or a char.
 Match case label.
 Execute sequence of statements of matching label.
 If break encountered,
go to end of the switch statement.
 Otherwise continue execution.
Multiple Selection:
The switch Statement
action
action
action
action
case 1
case 2
case 3
default
switch Statement: Example 1
• If you have a 95, what grade will you get?
switch(int(score)/10){
case 10:
case 9: printf("Grade = A“);
case 8: printf("Grade = B“);
case 7: printf("Grade = C“);
case 6: printf("Grade = D“);
default: printf("Grade = F“);
}
switch Statement: Example 2
switch(int(score)/10){
case 10:
case 9: printf( "Grade = A“);
break;
case 8: printf( “Grade = B”);
break;
case 7: printf( "Grade = C“);
break;
case 6: printf( "Grade = D“);
break;
default: printf( "Grade = F“);;
}
switch Statement: Example 2
is equivalent to:
if (score >= 90)
printf("Grade = A“);;
else if (score >= 80)
printf("Grade = B“);
else if (score >= 70)
printf("Grade = C“);
else if (score >= 60)
printf("Grade = D“);
else // score < 59
printf("Grade = F“);;
switch Statement: Example 2
#include <stdio.h>
int main()
{ char answer;
printf( "Is 18CSS101J an easy course? (y/n):) “);
scanf(“%c”, &answer);
switch (answer){
case 'Y':
case 'y': printf( "I think so too!" );
break;
case 'N':
case 'n': printf( "Are you kidding?" );
break;
default:
printf( "Is that a yes or no?“);
}
return 0;
}
switch Statement with Multiple
Labels: Example 3
switch (watts) {
case 25 : lifespan = 2500;
break;
case 40 :
case 60 : lifespan = 1000;
break;
case 75 : lifespan = 750;
break;
default :
lifespan = 0;
} // end switch
Points to Remember
 The expression followed by each case label must be a
constant expression.
 No two case labels may have the same value.
 Two case labels may be associated with the same statements.
 The default label is not required.
 There can be only one default label, and it is usually last.
Flow diagram of while loop
if (test) while (test)
{ {
statement list; statement list;
} }
test
Statement list
Next statement
true
false
test
Statement list
Next statement
true
false
Sum Example (not in book)
 What if we want to compute the sum of
 100 values
 an undetermined number of values
 What we need is a program to be able to read as
many values as we want and then compute the
sum
 This is possible with loops
 Good solution is to use loops.
 Code is developed on board.
 This type of loops are called counting loops
 number of iterations is known
Another simple example
 Calculate the sum of the integer numbers between 1 and 10
int sum = 0; // this program piece
int i = 1; // calculates the sum of
while (i <= 10) // integers between and
{ // including 1 and 10
sum = sum + i;
i += 1;
}
Walkthrough of the example
int sum = 0;
int i = 1;
while (i <= 10)
{
sum = sum + i;
i = i + 1;
}
Console.Write(sum);
i<=10
sum=sum+i;
i=i+1;
true
Console.Write(sum);
false
1i
sum 0
2
1
Walkthrough of the example
int sum = 0;
int i = 1;
while (i <= 10)
{
sum = sum + i;
i = i + 1;
}
Console.Write(sum);
i<=10
sum=sum+i;
i=i+1;
true false
2i
sum 1
3
3
Console.Write(sum);
Walkthrough of the example
int sum = 0;
int i = 1;
while (i <= 10)
{
sum = sum + i;
i = i + 1;
}
Console.Write(sum);
i<=10
sum=sum+i;
i=i+1;
true
cout<<sum;
false
3i
sum 3
4
6
Console.Write(sum);
Walkthrough of the example
int sum = 0;
int i = 1;
while (i <= 10)
{
sum = sum + i;
i = i + 1;
}
Console.Write(sum);
i<=10
sum=sum+i;
i=i+1;
true
cout<<sum;
false
10i
sum 45
11
55
Console.Write(sum);
while loop syntax
<initialization>
while (<test>)
{
<statement1>;
...
<statementN>;
<update>
}
while loop sum example
 Sum of numbers from 1..10
int sum = 0;
int i = 1;
while (i <= 10)
{
sum = sum + i;
i = i + 1;
}
Printf(“%d”,sum);
initialization
body statements
update
test
Counter-controlled loop example
 Consider the following problem statement:
A class of 10 students took a quiz. The grades
(integers in
the range 0 to 100) for this quiz are available to you.
Determine the class average on the quiz.
 The algorithm must input each grade, keep track of
the total of all grades input, perform the averaging
calculation and display the result.
Counter-controlled loop code
// initialization
total = 0; // initialize the total
gradeCounter = 1; // initialize the loop counter
while ( gradeCounter <= 10 ) // test
{
printf( "Enter grade: " ); // prompt the user
scanf(“%d”, &grade); // read grade
total = total + grade; // add the grade to total
gradeCounter = gradeCounter + 1; // update
}
// termination phase
average = total / 10; // integer division yields integer result
Sentinel-controlled loop example
Consider the following problem:
Develop a class-averaging application that
processes grades for an arbitrary number of
students each time it is run.
In this example, no indication is given of how
many grades the user will enter during the
application’s execution.
Sentinel-controlled algorithm
initialize total to zero
initialize counter to zero
prompt the user to enter the first grade
input the first grade (possibly the sentinel)
while the user has not yet entered the sentinel
add this grade into the running total
add one to the grade counter
prompt the user to enter the next grade
input the next grade (possibly the sentinel)
if the counter is not equal to zero
set the average to the total divided by the counter
display the average
else
display “No grades were entered”
for loop syntax compared with while
<initialization>
while (<test>)
{
<statement1>;
...
<statementN>;
<update>
}
for (<initialization>;
<test>;
<update> )
{
<statement1>;
...
<statementN>;
}
Example
 Calculate the sum of the integer numbers between 1 and 10
int sum = 0; // this program piece
int i = 1; // calculates the sum of
while (i <= 10) // integers between and
{ // including 1 and 10
sum = sum + i;
i = i + 1;
}
Same example with for loop
int sum = 0;
int i = 1;
while (i <= 10)
{
sum = sum + i;
i = i + 1;
}
int sum = 0;
for (int i=1; i <= 10; i=i+1)
{
sum = sum + i;
}
Scope of the counter variable in for
for (int i=1; i <= 10; i=i+1)
 If the initialization expression declares the control variable,
the control variable will not exist outside the for statement.
 This restriction is known as the variable’s scope.
 Similarly, a local variable can be used only in the method that
declares the variable and only from the point of declaration.
int i;
for (i=1; i <= 10; i=i+1)
for loop syntax
 Comma-separated lists that enable you to use
multiple initialization expressions or multiple
increment expressions:
for ( int i = 2; i <= 20; total +=
i, i += 2 )
; // empty statement
Bad loops
1. for (int i = 10; i < 5; i=i+1)
{
printf("How many times do I print?");
}
2. for (int i = 10; i >= 1; i=i+1)
{
printf("How many times do I print?");
}
3. int i = 1;
while (i < 20)
{
printf("How many times do I print?");
}
Other Common Problems
 Easy to iterate one more or one less times
 Test each loop with the inputs that cause:
 zero iterations of the loop body
 one iteration of the loop body
 maximum number of iterations
 one less than the maximum number of iterations
 Use the debugger and watch the variables.
Developing Loops
 Some loops are easy to develop, others are not
 Sometimes the proper loop test and body are hard to
design
 Practice helps, but remember:
 Good design comes from experience, experience comes
from bad design
Factorial
 n! = 1x2x…xn is “n factorial”; used in math, statistics
long factorial(long n)
// pre: 0 <= n
// post: returns n! (1 x 2 x … x n)
 Similar to sum, but this time we will calculate a product
within the loop. At the end we will return the final
product.
 The loop will iterate n times, multiplying by 1, 2, …, n
 Suppose we use a variable called product to hold the result,
then product is n! when the loop terminates. Then we will
return it at the end.
Factorial
long Factorial(int num)
{
long product = 1;
int count = 0;
while (count < num)
{
count += 1;
product *= count;
}
return product;
}
 Issues
 Why did we use long? What happens if we use int instead?
 What happens if we initialize count to 1?
Downward-counting loop
 Calculate n to the power of m: nm=nxnx…xn
 Example: 25=2x2x2x2x2=32
int power = 1;
int n, m;
for (int i = m; i <= 1; i--)
{
power = power * n;
}
Exercise:
Determining if a number is Prime
 1 is NOT prime, 2 is prime, 3 is prime, 5 is prime, 17 is prime, …
137, 193?
 We do not need to check even numbers other than 2 (2 is a special case)
 To check 193, divide it by 3, 5, 7, 9, 11, 13
 Note that 14x14 = 196, so 13 largest potential factor?
 We can use modulus operator to check divisibility
 Check odd numbers as potential divisors
 Watch out for 2, it is a special case
 How far should we go to check potential divisors?
 up to and including Math.Sqrt(number) + 1
 If there was a bigger factor, a smaller factor would exist. And this smaller one
must have been checked before. So we do not need to go beyond this limit.
 +1 is there to make sure that there will be no problems with precision
 Write code as exercise at home
Nested loops – Example
 Write a function to display a perpendicular isosceles
triangle of stars (perpendicular side length is parameter)
 e.g. if side length is 6 , the output should look like
*
**
***
****
*****
******
 Exercise: write the same loops downward-counting this time.
Exercise: Multiplication Table
 On ith line print, i*1, i*2, i*3, ... , i*i
 Total number of lines is an input. Display lines starting
with 1.
Please enter the number of lines in the
multiplication table: 9
1
2 4
3 6 9
4 8 12 16
5 10 15 20 25
6 12 18 24 30 36
7 14 21 28 35 42 49
8 16 24 32 40 48 56 64
9 18 27 36 45 54 63 72 81
The do-while loop
 Similar to while loop, but the test is after the execution of the loop body
 The while loop may never execute, do-while loop executes at least once
<initialization>
do
{
<statement1>;
...
<statementN>;
<update>
} while (<condition>);
 Example: Prompt for a number between 0 and 100, loop until such a number
is entered (user should enter at least one number)
do
{
printf(“enter number in range [0..100]");
Scanf(“%d”, &num);
} while (num < 0 || num > 100 );
Don’t
forget
86
break and continue
• The continue statement skips the remaining statements in the
loop body and tests whether to proceed with the next iteration
of the loop.
• In a for statement, the increment expression executes, then
the application evaluates the loop-continuation test.
Software Engineering
Some programmers feel that break and continue statements
violate structured programming, since the same effects are
achievable with structured programming techniques.
BREAK STATEMENT IN C
Break statement is used to terminate
the while loops, switch case loops
and for loops from the subsequent
execution.
Syntax: break;
87
88
#include <stdio.h>
int main()
{
int i;
for(i=0;i<10;i++)
{
if(i==5)
{
printf("nComing
out of for loop when i =
5");
break;
}
printf("%d ",i);
}
}
OUTPUT
0 1 2 3 4
Coming out of for loop
when i = 5
CONTINUE STATEMENT IN C:
Continue statement is used to continue
the next iteration of for loop, while loop
and do-while loops. So, the remaining
statements are skipped within the loop
for that particular iteration.
Syntax : continue;
89
90
#include <stdio.h>
int main()
{
int i;
for(i=0;i<10;i++)
{
if(i==5 || i==6)
{
printf("nSkipping %d
from display using " 
"continue statement n",i);
continue;
}
printf("%d ",i);
}
}
OUTPUT
0 1 2 3 4
Skipping 5 from display using
continue statement
Skipping 6 from display using
continue statement
7 8 9
GOTO STATEMENT IN C
 goto statements is used to transfer the normal
flow of a program to the specified label in the
program.
 Below is the syntax for goto statement in C.
 { …….
go to label;
…….
…….
LABEL:
statements;
}91
92
#include <stdio.h>
int main()
{
int i;
for(i=0;i<10;i++)
{
if(i==5)
{
printf("nWe are using goto statement when i =
5");
goto HAI;
}
printf("%d ",i);
}
HAI : printf("nNow, we are inside label name
"hai" n");
}
OUTPUT
0 1 2 3 4
We are using goto statement when i
= 5
Now, we are inside label name “hai”
Arrays
Introduction
Arrays
Structures of related data items
Static entity - same size throughout
program
A few types
C-like, pointer-based arrays
C++, arrays as objects
Arrays
 Array
 Consecutive group of memory locations
 Same name and type
 To refer to an element, specify
 Array name and position number
 Format: arrayname[ position number ]
 First element at position 0
 n element array c:
c[ 0 ], c[ 1 ]…c[ n - 1 ]
 Array elements are like normal variables
c[ 0 ] = 3;
Printf(“%d”, c[ 0 ]);
 Performing operations in subscript. If x = 3,
c[ 5 – 2 ] == c[ 3 ] == c[ x ]
Array in C
 C Array is a collection of variables belongings to the same data
type.You can store group of data of same data type in an array.
 Array might be belonging to any of the data types
 Array size must be a constant value.
 Always, Contiguous (adjacent) memory locations are used to
store array elements in memory.
 It is a best practice to initialize an array to zero or null while
declaring, if we don‟t assign any values to array.
96
Arrays
c[6]
-45
6
0
72
1543
-89
0
62
-3
1
6453
78
Name of array (Note that all
elements of this array have
the same name, c)
c[0]
c[1]
c[2]
c[3]
c[11]
c[10]
c[9]
c[8]
c[7]
c[5]
c[4]
Position number of the element
within array c
Declaring Arrays
 Declaring arrays - specify:
 Name
 Type of array
 Number of elements
 Examples
int c[ 10 ];
float hi[ 3284 ];
 Declaring multiple arrays of same type
 Similar format as other variables
 Example
int b[ 100 ], x[ 27 ];
Examples Using Arrays
 Initializers
int n[ 5 ] = { 1, 2, 3, 4, 5 };
 If not enough initializers, rightmost elements become 0
 If too many initializers, a syntax error is generated
int n[ 5 ] = { 0 }
 Sets all the elements to 0
 If size omitted, the initializers determine it
int n[] = { 1, 2, 3, 4, 5 };
 5 initializers, therefore n is a 5 element array
Examples of Array
 int a[10]; // integer array
 char b[10]; // character array i.e. string
100
Initializing Arrays
 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;
101
 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 in previous slide −
 double salary = balance[9];
 The above statement will take the 10th element from the array and
assign the value to salary variable.
102
Types of Arrays
 There are 2 types of C arrays.They are,
 One dimensional array
 Multi dimensional array
 Two dimensional array
 Three dimensional array
 four dimensional array etc…
103
ONE DIMENSIONAL ARRAY IN C:
 Array declaration Syntax :
 data-type arr_name[array_size];
 int age [5];
 Array initialization syntax:
 data_type arr_name [arr_size]=(value1, value2, value3,….)
 int age[5]={0, 1, 2, 3, 4};
 Array accessing syntax:
 arr_name[index];
 age[0]; /*0 is accessed*/
age[1]; /*1 is accessed*/
age[2]; /*2 is accessed*/
104
Character array example
 char str[10];
char str[10]={„H‟,„a‟,„i‟};
(or)
char str[0] =„H‟;
char str[1] =„a‟;
char str[2] =„i;
 str[0]; /*H is accessed*/
str[1]; /*a is accessed*/
str[2]; /*i is accessed*/
105
EXAMPLE PROGRAM FOR ONE DIMENSIONAL ARRAY IN C
#include<stdio.h>
int main()
{
int i;
int arr[5] = {10,20,30,40,50};
// declaring and Initializing array in C
//To initialize all array elements to 0, use int
arr[5]={0};
/* Above array can be initialized as below also
arr[0] = 10;
arr[1] = 20;
arr[2] = 30;
arr[3] = 40;
arr[4] = 50; */
for (i=0;i<5;i++)
{
// Accessing each variable
printf("value of arr[%d] is %d n", i, arr[i]);
}
}
OUTPUT:
value of arr[0] is 10
value of arr[1] is 20
value of arr[2] is 30
value of arr[3] is 40
value of arr[4] is 50
106

More Related Content

What's hot

Image contro, and format functions in vb
Image contro, and format functions in vbImage contro, and format functions in vb
Image contro, and format functions in vb
Amandeep Kaur
 
Programming Language.ppt
Programming Language.pptProgramming Language.ppt
Programming Language.ppt
Lovely Professional University
 
Unit1 principle of programming language
Unit1 principle of programming languageUnit1 principle of programming language
Unit1 principle of programming language
Vasavi College of Engg
 

What's hot (20)

Symbol table in compiler Design
Symbol table in compiler DesignSymbol table in compiler Design
Symbol table in compiler Design
 
Operators and expressions in c language
Operators and expressions in c languageOperators and expressions in c language
Operators and expressions in c language
 
Loops c++
Loops c++Loops c++
Loops c++
 
SAD04 - Inheritance
SAD04 - InheritanceSAD04 - Inheritance
SAD04 - Inheritance
 
Image contro, and format functions in vb
Image contro, and format functions in vbImage contro, and format functions in vb
Image contro, and format functions in vb
 
Functions in c language
Functions in c language Functions in c language
Functions in c language
 
Practical File of C Language
Practical File of C LanguagePractical File of C Language
Practical File of C Language
 
Data Communication Assignment
Data Communication AssignmentData Communication Assignment
Data Communication Assignment
 
Theory of Computation Lecture Notes
Theory of Computation Lecture NotesTheory of Computation Lecture Notes
Theory of Computation Lecture Notes
 
Types of Statements in Python Programming Language
Types of Statements in Python Programming LanguageTypes of Statements in Python Programming Language
Types of Statements in Python Programming Language
 
Syntax
SyntaxSyntax
Syntax
 
FP 301 OOP FINAL PAPER
FP 301 OOP FINAL PAPER FP 301 OOP FINAL PAPER
FP 301 OOP FINAL PAPER
 
Theory of Automata
Theory of AutomataTheory of Automata
Theory of Automata
 
Procedural programming
Procedural programmingProcedural programming
Procedural programming
 
Data Representation
Data RepresentationData Representation
Data Representation
 
Introduction to C Programming
Introduction to C ProgrammingIntroduction to C Programming
Introduction to C Programming
 
Program control
Program controlProgram control
Program control
 
Problem solving using Computer
Problem solving using ComputerProblem solving using Computer
Problem solving using Computer
 
Programming Language.ppt
Programming Language.pptProgramming Language.ppt
Programming Language.ppt
 
Unit1 principle of programming language
Unit1 principle of programming languageUnit1 principle of programming language
Unit1 principle of programming language
 

Similar to Programming for Problem Solving

Operators and expressions
Operators and expressionsOperators and expressions
Operators and expressions
vishaljot_kaur
 
Operator & Expression in c++
Operator & Expression in c++Operator & Expression in c++
Operator & Expression in c++
bajiajugal
 
C programming session 02
C programming session 02C programming session 02
C programming session 02
Dushmanta Nath
 

Similar to Programming for Problem Solving (20)

Control statements in c
Control statements in cControl statements in c
Control statements in c
 
Programming Fundamentals lecture 7
Programming Fundamentals lecture 7Programming Fundamentals lecture 7
Programming Fundamentals lecture 7
 
This slide contains information about Operators in C.pptx
This slide contains information about Operators in C.pptxThis slide contains information about Operators in C.pptx
This slide contains information about Operators in C.pptx
 
Fundamentals of Programming Chapter 5
Fundamentals of Programming Chapter 5Fundamentals of Programming Chapter 5
Fundamentals of Programming Chapter 5
 
Operators inc c language
Operators inc c languageOperators inc c language
Operators inc c language
 
Operators and expressions
Operators and expressionsOperators and expressions
Operators and expressions
 
C – operators and expressions
C – operators and expressionsC – operators and expressions
C – operators and expressions
 
Operator & Expression in c++
Operator & Expression in c++Operator & Expression in c++
Operator & Expression in c++
 
C PRESENTATION.pptx
C PRESENTATION.pptxC PRESENTATION.pptx
C PRESENTATION.pptx
 
power point presentation on topic in C++ called "OPERATORS"
power point presentation on topic in C++ called "OPERATORS"power point presentation on topic in C++ called "OPERATORS"
power point presentation on topic in C++ called "OPERATORS"
 
C++ Expressions Notes
C++ Expressions NotesC++ Expressions Notes
C++ Expressions Notes
 
Types of Operators in C
Types of Operators in CTypes of Operators in C
Types of Operators in C
 
Operators and expressions in C++
Operators and expressions in C++Operators and expressions in C++
Operators and expressions in C++
 
Class_IX_Operators.pptx
Class_IX_Operators.pptxClass_IX_Operators.pptx
Class_IX_Operators.pptx
 
C programming session 02
C programming session 02C programming session 02
C programming session 02
 
Lecture 3
Lecture 3Lecture 3
Lecture 3
 
cprogrammingoperator.ppt
cprogrammingoperator.pptcprogrammingoperator.ppt
cprogrammingoperator.ppt
 
Operators in c programming
Operators in c programmingOperators in c programming
Operators in c programming
 
C operator and expression
C operator and expressionC operator and expression
C operator and expression
 
Operator in C language
Operator in C languageOperator in C language
Operator in C language
 

More from Kathirvel Ayyaswamy

More from Kathirvel Ayyaswamy (20)

22CS201 COA
22CS201 COA22CS201 COA
22CS201 COA
 
22cs201 COMPUTER ORGANIZATION AND ARCHITECTURE
22cs201 COMPUTER ORGANIZATION AND ARCHITECTURE22cs201 COMPUTER ORGANIZATION AND ARCHITECTURE
22cs201 COMPUTER ORGANIZATION AND ARCHITECTURE
 
22CS201 COA
22CS201 COA22CS201 COA
22CS201 COA
 
18CS3040_Distributed Systems
18CS3040_Distributed Systems18CS3040_Distributed Systems
18CS3040_Distributed Systems
 
20CS2021-Distributed Computing module 2
20CS2021-Distributed Computing module 220CS2021-Distributed Computing module 2
20CS2021-Distributed Computing module 2
 
18CS3040 Distributed System
18CS3040 Distributed System	18CS3040 Distributed System
18CS3040 Distributed System
 
20CS2021 Distributed Computing
20CS2021 Distributed Computing 20CS2021 Distributed Computing
20CS2021 Distributed Computing
 
20CS2021 DISTRIBUTED COMPUTING
20CS2021 DISTRIBUTED COMPUTING20CS2021 DISTRIBUTED COMPUTING
20CS2021 DISTRIBUTED COMPUTING
 
18CS3040 DISTRIBUTED SYSTEMS
18CS3040 DISTRIBUTED SYSTEMS18CS3040 DISTRIBUTED SYSTEMS
18CS3040 DISTRIBUTED SYSTEMS
 
Recent Trends in IoT and Sustainability
Recent Trends in IoT and SustainabilityRecent Trends in IoT and Sustainability
Recent Trends in IoT and Sustainability
 
20CS2008 Computer Networks
20CS2008 Computer Networks 20CS2008 Computer Networks
20CS2008 Computer Networks
 
18CS2005 Cryptography and Network Security
18CS2005 Cryptography and Network Security18CS2005 Cryptography and Network Security
18CS2005 Cryptography and Network Security
 
18CS2005 Cryptography and Network Security
18CS2005 Cryptography and Network Security18CS2005 Cryptography and Network Security
18CS2005 Cryptography and Network Security
 
18CS2005 Cryptography and Network Security
18CS2005 Cryptography and Network Security18CS2005 Cryptography and Network Security
18CS2005 Cryptography and Network Security
 
18CS2005 Cryptography and Network Security
18CS2005 Cryptography and Network Security 18CS2005 Cryptography and Network Security
18CS2005 Cryptography and Network Security
 
18CS2005 Cryptography and Network Security
18CS2005 Cryptography and Network Security18CS2005 Cryptography and Network Security
18CS2005 Cryptography and Network Security
 
18CS2005 Cryptography and Network Security
18CS2005 Cryptography and Network Security18CS2005 Cryptography and Network Security
18CS2005 Cryptography and Network Security
 
20CS2008 Computer Networks
20CS2008 Computer Networks20CS2008 Computer Networks
20CS2008 Computer Networks
 
20CS2008 Computer Networks
20CS2008 Computer Networks 20CS2008 Computer Networks
20CS2008 Computer Networks
 
20CS024 Ethics in Information Technology
20CS024 Ethics in Information Technology20CS024 Ethics in Information Technology
20CS024 Ethics in Information Technology
 

Recently uploaded

RS Khurmi Machine Design Clutch and Brake Exercise Numerical Solutions
RS Khurmi Machine Design Clutch and Brake Exercise Numerical SolutionsRS Khurmi Machine Design Clutch and Brake Exercise Numerical Solutions
RS Khurmi Machine Design Clutch and Brake Exercise Numerical Solutions
Atif Razi
 
Laundry management system project report.pdf
Laundry management system project report.pdfLaundry management system project report.pdf
Laundry management system project report.pdf
Kamal Acharya
 
Hall booking system project report .pdf
Hall booking system project report  .pdfHall booking system project report  .pdf
Hall booking system project report .pdf
Kamal Acharya
 
Fruit shop management system project report.pdf
Fruit shop management system project report.pdfFruit shop management system project report.pdf
Fruit shop management system project report.pdf
Kamal Acharya
 
Automobile Management System Project Report.pdf
Automobile Management System Project Report.pdfAutomobile Management System Project Report.pdf
Automobile Management System Project Report.pdf
Kamal Acharya
 

Recently uploaded (20)

Quality defects in TMT Bars, Possible causes and Potential Solutions.
Quality defects in TMT Bars, Possible causes and Potential Solutions.Quality defects in TMT Bars, Possible causes and Potential Solutions.
Quality defects in TMT Bars, Possible causes and Potential Solutions.
 
Pharmacy management system project report..pdf
Pharmacy management system project report..pdfPharmacy management system project report..pdf
Pharmacy management system project report..pdf
 
RS Khurmi Machine Design Clutch and Brake Exercise Numerical Solutions
RS Khurmi Machine Design Clutch and Brake Exercise Numerical SolutionsRS Khurmi Machine Design Clutch and Brake Exercise Numerical Solutions
RS Khurmi Machine Design Clutch and Brake Exercise Numerical Solutions
 
Event Management System Vb Net Project Report.pdf
Event Management System Vb Net  Project Report.pdfEvent Management System Vb Net  Project Report.pdf
Event Management System Vb Net Project Report.pdf
 
shape functions of 1D and 2 D rectangular elements.pptx
shape functions of 1D and 2 D rectangular elements.pptxshape functions of 1D and 2 D rectangular elements.pptx
shape functions of 1D and 2 D rectangular elements.pptx
 
HYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generationHYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generation
 
Laundry management system project report.pdf
Laundry management system project report.pdfLaundry management system project report.pdf
Laundry management system project report.pdf
 
Scaling in conventional MOSFET for constant electric field and constant voltage
Scaling in conventional MOSFET for constant electric field and constant voltageScaling in conventional MOSFET for constant electric field and constant voltage
Scaling in conventional MOSFET for constant electric field and constant voltage
 
Introduction to Casting Processes in Manufacturing
Introduction to Casting Processes in ManufacturingIntroduction to Casting Processes in Manufacturing
Introduction to Casting Processes in Manufacturing
 
Hall booking system project report .pdf
Hall booking system project report  .pdfHall booking system project report  .pdf
Hall booking system project report .pdf
 
Cloud-Computing_CSE311_Computer-Networking CSE GUB BD - Shahidul.pptx
Cloud-Computing_CSE311_Computer-Networking CSE GUB BD - Shahidul.pptxCloud-Computing_CSE311_Computer-Networking CSE GUB BD - Shahidul.pptx
Cloud-Computing_CSE311_Computer-Networking CSE GUB BD - Shahidul.pptx
 
Fruit shop management system project report.pdf
Fruit shop management system project report.pdfFruit shop management system project report.pdf
Fruit shop management system project report.pdf
 
Construction method of steel structure space frame .pptx
Construction method of steel structure space frame .pptxConstruction method of steel structure space frame .pptx
Construction method of steel structure space frame .pptx
 
NO1 Pandit Black Magic Removal in Uk kala jadu Specialist kala jadu for Love ...
NO1 Pandit Black Magic Removal in Uk kala jadu Specialist kala jadu for Love ...NO1 Pandit Black Magic Removal in Uk kala jadu Specialist kala jadu for Love ...
NO1 Pandit Black Magic Removal in Uk kala jadu Specialist kala jadu for Love ...
 
A CASE STUDY ON ONLINE TICKET BOOKING SYSTEM PROJECT.pdf
A CASE STUDY ON ONLINE TICKET BOOKING SYSTEM PROJECT.pdfA CASE STUDY ON ONLINE TICKET BOOKING SYSTEM PROJECT.pdf
A CASE STUDY ON ONLINE TICKET BOOKING SYSTEM PROJECT.pdf
 
ONLINE CAR SERVICING SYSTEM PROJECT REPORT.pdf
ONLINE CAR SERVICING SYSTEM PROJECT REPORT.pdfONLINE CAR SERVICING SYSTEM PROJECT REPORT.pdf
ONLINE CAR SERVICING SYSTEM PROJECT REPORT.pdf
 
KIT-601 Lecture Notes-UNIT-3.pdf Mining Data Stream
KIT-601 Lecture Notes-UNIT-3.pdf Mining Data StreamKIT-601 Lecture Notes-UNIT-3.pdf Mining Data Stream
KIT-601 Lecture Notes-UNIT-3.pdf Mining Data Stream
 
Automobile Management System Project Report.pdf
Automobile Management System Project Report.pdfAutomobile Management System Project Report.pdf
Automobile Management System Project Report.pdf
 
A case study of cinema management system project report..pdf
A case study of cinema management system project report..pdfA case study of cinema management system project report..pdf
A case study of cinema management system project report..pdf
 
Democratizing Fuzzing at Scale by Abhishek Arya
Democratizing Fuzzing at Scale by Abhishek AryaDemocratizing Fuzzing at Scale by Abhishek Arya
Democratizing Fuzzing at Scale by Abhishek Arya
 

Programming for Problem Solving

  • 1. 18CSS101J Programming for Problem Solving UNIT II Dr.A.Kathirvel, Professor Dept. of Computer Science and Engineering Faculty of Engineering &Technology, SRM Institute of Science andTechnology, Vadapalani campus, Chennai
  • 2. RESOURCES Sno BOOK 1 Zed A Shaw,Learn C the HardWay:Practical Exercises on the Computational SubjectsYou Keep Avoiding (Like C), AddisonWesley,2015 2 W.Kernighan,Dennis M.Ritchie,The C Programming Language,2nd ed.Prentice Hall,1996 3 Bharat Kinariwala,Tep Dobry,Programming in C,eBook 4 http://www.c4learn.com/learn-c-programming- language/
  • 3. UNIT 2 Operators, Looping, Array 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 - 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 Array Basic and Types - Array Initialization and Declaration - Initialization: one Dimensional Array - Accessing, Indexing one Dimensional Array Operations - One Dimensional Array operations - Array Programs – 1D
  • 4. Contents  Arithmetic operations  Arithmetic expressions  Relational operators  Logical operators  Assignment operators  Increment and decrement operators  Conditional operators  Type conversions in expressions 4
  • 5. 5 Objectives ♥ To be able to construct and evaluate expressions. ♥ To master operator precedence and associativity ♥ To understand implicit type conversion and explicit type conversion.
  • 6. Introduction  An operator is a symbol that tells the computer to perform certain manipulations.  An expression is a sequence of operands and operators that reduces to a single value.  C operators can be classified into a number of categories. ◦ Arithmetic operators ◦ Relational operators ◦ Logical operators ◦ Assignment operators ◦ Increment and decrement operators ◦ Conditional operators ◦ Bitwise operators ◦ Special operators 6
  • 7. Arithmetic operators  The arithmetic operators in C Operator meaning + Addition or unary plus - Subtraction or unary minus * Multiplication / Division % modulo division 7
  • 8. Arithmetic operators Note:, Integer division truncates remainder The % operator cannot be applied to a float or double. The precedence of arithmetic operators Unary + or - * / % + - 8
  • 9. Arithmetic expressions An arithmetic expression is a combination of variables, constants, and operators. For example, a*b-c  a*b-c (m+n)(x+y)  (m+n)*(x+y) ax2+bx+c  a*x*x+b*x+c 9
  • 10. Relational Operators Operator Meaning < less that <= less than or equal to > greater than >= greater than or equal to == equal to != not equal to 10 • The relational operators in C are :
  • 11. Relational Operators A relational expression yields a value of 1 or 0. 5 < 6 1 -34 + 8 > 23 - 5 0 if a=3, b=2, c =1; then a > b > c is ? the associativity of relational operators is left  right 11
  • 12. Relational Operators Relational operators are used to compare two values to form a condition. Math C Plain English = == equals [example: if(a==b) ] [ (a=b) means put the value of b into a ] < < less than  <= less than or equal to > > greater than  >= greater than or equal to  != not equal to
  • 13. Logical operators  C has the following three logical operators && meaning logical and || meaning logical or ! meaning logical not ( unary operator )  Expressions connected by && or || are evaluated left to right, and evaluation stops as soon as the truth or falsehood of the result is known. 13
  • 14. Assignment operators  The use of shorthand assignment operators has three advantages: 1.What appears on the left-hand side need not be repeated and therefore it becomes easier to write. 2.The statement is more concise and easier to read. 3.The statement is more efficient. 14
  • 15. Increment and decrement operators  C provides two unusual operators for incrementing and decrementing variables.  The increment operator ++ adds 1 to its operand, while the decrement operator -- subtracts 1.  The unusual aspect is that ++ and -- may be used either as prefix operators (before the variable, as in ++n), or postfix operators (after the variable: n++).  In both cases, the effect is to increment n. But the expression ++n increments n before its value is used, while n++ increments n after its value has been used. 15
  • 16.  The increment and decrement operators can be used in complex statements. Example: m=n++ -j +10;  Consider the expression m = - n++ ;  The precedence of ++ and – operators are the same as those of unary + and -.  The associatively of them is right to left.  m = - n++; is equivalent to m = - (n++) 16
  • 17. Conditional operator  a ternary operator pair “? : ” is available in C to construct conditional expressions of the form expr1 ? expr2 : expr3  the expression expr1 is evaluated first. If it is non- zero (true), then the expression expr2 is evaluated, and that is the value of the conditional expression. Otherwise expr3 is evaluated, and that is the value. Only one of expr2 and expr3 is evaluated. 17
  • 19.  z = (a > b) ? a : b; /* z = max(a, b) */ 19
  • 20. Special operators  The Comma Operator  The comma operator can be used to link the related expressions together.A comma-linked list of expressions is evaluated left to right and the value of right-most expression is the value of the combined expression. For example, the statement  value = (x=10, y=5, x+y);  first assigns the value 10 to x, then assigns 5 to y, and finally assigns 15 to value. Since comma operator has the lowest precedence of all operators, the parentheses are necessary. 20
  • 21. Type conversions in expressions  ImplicitType Conversion  C permits mixing of constants and variables of different types in an expression. C automatically converts any intermediate values to the proper type so that the expression can be evaluated without loosing any significance.This automatic conversion is known as implicit type conversion.  The rule of type conversion: the lower type is automatically converted to the higher type. 21
  • 22. Some Computational Problems  When expressions include real values, then it is important to take necessary precautions to guard against certain computational errors. For example, consider the following statements: ◦ a = 1.0 / 3.0; ◦ b = a * 3.0;  There is no guarantee that the value of b will equal 1.  Another problem is division by zero.  The third problem is to avoid overflow and underflow errors. 22
  • 23. Operator Precedence Which comes first? * / % + - < <= >= > == != = Answer:
  • 24. More Operator Precedence  Precedence of operators (from highest to lowest)  Parentheses ( … )  Unary operators !  Multiplicative operators * / %  Additive operators + -  Relational ordering < <= >= >  Relational equality == !=  Logical and &&  Logical or ||  Assignment =
  • 25. More Operator Precedence  Examples 5 != 6 || 7 <= 3 (5 !=6) || (7 <= 3) 5 * 15 + 4 == 13 && 12 < 19 || !false == 5 < 24
  • 26. Sorting Two Numbers int value1; int value2; int temp; Printf("Enter two integers: “); Scanf(“%d%d”, &value1,&value2; if(value1 > value2){ temp = value1; value1 = value2; value2 = temp; } Printf("The input in sorted order: %d%d“, value1 , value2;
  • 27. if-else, switch, while, for, do-while Control Statements
  • 28. Conditional Statements  So far statements of our programs execute sequentially one after another.  What happens when  we want to execute a statement depending on a condition?  e.g. If there is enough money in the bank account, give the money  we want to execute one statement when a condition holds and another statement when a condition does not hold?  e.g. If dollar is high, sell dollar. Otherwise, buy dollar.  we want to select from many statements according to one or more criteria (selection).  e.g. If dollar is high and euro is low, sell dollar and buy euro. If dollar is low and euro is high, sell euro and buy dollar. If both of them are high, sell both and buy YTL.  You achieve conditional execution with if-else statements
  • 29. Syntax if (<condition>) { <statement_true_1>; ... <statement_true_N>; } else { <statement_false_1>; ... <statement_false_N>; }  If condition is TRUE then statement_true_1 … statement_true_N are executed, if condition is FALSE statement_false_1 … statement_false_N are executed. if (<condition>) { <statement_true_1>; ... <statement_true_N>; }  else and statement_false’s are optional  if condition is FALSE then nothing will be executed and execution continues with the next statement in the program  <condition> must be in brackets
  • 30. Another Syntax (without { }) if (<condition>) <statement_true>; else <statement_false>; if (<condition>) <statement_true>; • Can be used when there is only one statement • Not suggested (we will see why)
  • 31. Flow diagram of if-else test condition true statements true next statement false false statements
  • 32. if-else example  Write a program that inputs two integer numbers and displays the maximum one.  Two solutions  using if and else together  using only if (no else)
  • 33. 33  The conditional operator (?:) can be used in place of an if…else statement. printf( grade >= 60 ? "Passed" : "Failed" ); – The first operand is a boolean expression that evaluates to true or false. – The second operand is the value if the expression is true – The third operand is the value if the expression is false. Conditional operator (?:)
  • 34. < less than number < 5 <= less than or equal number <= 0 > greater than num1 > num2 >= greater than or equal num1 >= num2 == equality check num1 == 0 != inequality check num1 != num2 Relational Operators  Relational operators are used to compare values:  They take two operands  operands can be literals, variables or expressions  Used for many types  numeric comparisons  string comparisons (alphabetical)
  • 35. Logical operators  Boolean expressions can be combined using logical operators: AND, OR, NOT  In C we use && || ! respectively A B A || B A && B true true true true true false true false false true true false false false false false A ! A true false false true
  • 36. Example • Range check: between 0 and 100 (includes 0 and 100), or not? If so, display a message saying that the number is in the range. If not, the message should say “out of the range”. • Solution 1: using logical AND operator if (num >= 0 && num <= 100) printf("number is in the range"); else printf("number is out of range"); • Solution 2: using logical AND and NOT operators if ( ! (num >= 0 && num <= 100) ) printf("number is out of range"); else printf("number is in the range"); • Solution 3: using logical OR operator if (num < 0 || num > 100) printf("number is out of range"); else printf("number is in the range");
  • 37. Operator Precedence - Revisited  Upper operator groups have precedence Operator Explanation Associativity + - ! plus and minus signs, logical NOT right-to-left * / % multiplication, division and modulus left-to-right + - addition, subtraction left-to-right < <= > >= inequality comparison operators left-to-right == != equal, not equal comparison left-to-right && logical and left-to-right || logical or left-to-right = += -= *= /= %= assignment operators right-to-left
  • 38. Nested if statements  if/else statements are inside other if/else statements  Method to select from multiple choices  Example: input a numeric grade and convert to letter grade 90 .. 100 A 80 .. 89 B 70 .. 79 C 60 .. 69 D 0 .. 59 F otherwise F
  • 39. 39  This may be written in C# as if ( grade >= 90 ) printf( "A" ); else if ( grade >= 80 ) printf( "B" ); else if ( grade >= 70 ) printf( "C" ); else if ( grade >= 60 ) printf( "D" ); else printf( "F" ); Nested if statements
  • 40. 40  Most C programmers prefer to use else if: if ( grade >= 90 ) printf( "A" ); else if ( grade >= 80 ) printf( "B" ); else if ( grade >= 70 ) printf( "C" ); else if ( grade >= 60 ) printf( "D" ); else printf( "F" ); Nested if statements (Cont.)
  • 41. Short-circuit Evaluation  Some subexpressions in Boolean expressions are not evaluated if the entire expression’s value is already known using the subexpression evaluated so far.  Rule: Evaluate the first (leftmost) boolean subexpression. If its value is enough to judge about the value of the entire expression, then stop there. Otherwise continue evaluation towards right. if (count != 0 && scores/count < 60) { printf("low average"); }  In this example, if the value of count is zero, then first subexpression becomes false and the second one is not evaluated.  In this way, we avoid “division by zero” error (that would cause to stop the execution of the program)  Alternative method to avoid division by zero without using short-circuit evaluation: if (count != 0) { if (scores/count < 60) { printf("low average"); } }
  • 42. Dangling Else Problem if ( x % 2 == 0) if ( x < 0 ) printf("{0} is an even, negative number %d“, x); else printf("{0} is an odd number%d“, x);  What does it display for x=4?  The problem is that it displays “odd number” message for positive even numbers and zero.  Reason is that, although indentation says the reverse, else belongs to second (inner) if  else belongs to the most recent if  Solution: use braces (see next slide)
  • 43. Solution to Dangling Else Problem if ( x % 2 == 0) { if ( x < 0 ) printf("{0} is an even, negative number &d“, x); } else { printf("{0} is an odd number %d“, x); }  Now else belongs to the first if  if – else matching rule  Each else belongs to the nearest if for which there is no else and in the same compound block
  • 44. switch statement  The switch multiple-selection statement performs different actions based on the value of an expression.  Each action is associated with the value of a constant integral expression or a constant string expression that the expression may assume.  Syntax  Switch( var or identifier)  { case 1:  statement;  break:  Case 2: statement;  break:  Case n:
  • 45. private void IncrementLetterGradeCounter( int grade ) { switch ( grade / 10 ) { case 9: // grade was in the 90s case 10: // grade was 100 ++aCount; break; // necessary to exit switch case 8: // grade was between 80 and 89 ++bCount; break; // exit switch case 7: // grade was between 70 and 79 ++cCount; break; // exit switch case 6: // grade was between 60 and 69 ++dCount; break; // exit switch default: // grade was less than 60 ++fCount; break; // exit switch } } // end method IncrementLetterGradeCounter
  • 46. Flow diagram of switch
  • 47. 47  The expression after each case can be only a constant integral expression or a constant string expression.  You can also use null and character constants which represent the integer values of characters.  The expression also can be a constant that contains a value which does not change for the entire application. switch statement
  • 48. Multiple Selection: The switch Statement value1 action 1 value2 action 2 value3 action 3 value4 action 4 multiway expression
  • 49. Multiple Selection: The switch Statement Syntax: switch (<selector expression>) { case <label1> : <sequence of statements>; break; case <label2> : <sequence of statements>; break; case <labeln> : <sequence of statements>; break; default : <sequence of statements>; }
  • 50. Multiple Selection: The switch Statement Meaning:  Evaluate selector expression.  The selector expression can only be: a bool, an integer, an enum constant, or a char.  Match case label.  Execute sequence of statements of matching label.  If break encountered, go to end of the switch statement.  Otherwise continue execution.
  • 51. Multiple Selection: The switch Statement action action action action case 1 case 2 case 3 default
  • 52. switch Statement: Example 1 • If you have a 95, what grade will you get? switch(int(score)/10){ case 10: case 9: printf("Grade = A“); case 8: printf("Grade = B“); case 7: printf("Grade = C“); case 6: printf("Grade = D“); default: printf("Grade = F“); }
  • 53. switch Statement: Example 2 switch(int(score)/10){ case 10: case 9: printf( "Grade = A“); break; case 8: printf( “Grade = B”); break; case 7: printf( "Grade = C“); break; case 6: printf( "Grade = D“); break; default: printf( "Grade = F“);; }
  • 54. switch Statement: Example 2 is equivalent to: if (score >= 90) printf("Grade = A“);; else if (score >= 80) printf("Grade = B“); else if (score >= 70) printf("Grade = C“); else if (score >= 60) printf("Grade = D“); else // score < 59 printf("Grade = F“);;
  • 55. switch Statement: Example 2 #include <stdio.h> int main() { char answer; printf( "Is 18CSS101J an easy course? (y/n):) “); scanf(“%c”, &answer); switch (answer){ case 'Y': case 'y': printf( "I think so too!" ); break; case 'N': case 'n': printf( "Are you kidding?" ); break; default: printf( "Is that a yes or no?“); } return 0; }
  • 56. switch Statement with Multiple Labels: Example 3 switch (watts) { case 25 : lifespan = 2500; break; case 40 : case 60 : lifespan = 1000; break; case 75 : lifespan = 750; break; default : lifespan = 0; } // end switch
  • 57. Points to Remember  The expression followed by each case label must be a constant expression.  No two case labels may have the same value.  Two case labels may be associated with the same statements.  The default label is not required.  There can be only one default label, and it is usually last.
  • 58. Flow diagram of while loop if (test) while (test) { { statement list; statement list; } } test Statement list Next statement true false test Statement list Next statement true false
  • 59. Sum Example (not in book)  What if we want to compute the sum of  100 values  an undetermined number of values  What we need is a program to be able to read as many values as we want and then compute the sum  This is possible with loops  Good solution is to use loops.  Code is developed on board.  This type of loops are called counting loops  number of iterations is known
  • 60. Another simple example  Calculate the sum of the integer numbers between 1 and 10 int sum = 0; // this program piece int i = 1; // calculates the sum of while (i <= 10) // integers between and { // including 1 and 10 sum = sum + i; i += 1; }
  • 61. Walkthrough of the example int sum = 0; int i = 1; while (i <= 10) { sum = sum + i; i = i + 1; } Console.Write(sum); i<=10 sum=sum+i; i=i+1; true Console.Write(sum); false 1i sum 0 2 1
  • 62. Walkthrough of the example int sum = 0; int i = 1; while (i <= 10) { sum = sum + i; i = i + 1; } Console.Write(sum); i<=10 sum=sum+i; i=i+1; true false 2i sum 1 3 3 Console.Write(sum);
  • 63. Walkthrough of the example int sum = 0; int i = 1; while (i <= 10) { sum = sum + i; i = i + 1; } Console.Write(sum); i<=10 sum=sum+i; i=i+1; true cout<<sum; false 3i sum 3 4 6 Console.Write(sum);
  • 64. Walkthrough of the example int sum = 0; int i = 1; while (i <= 10) { sum = sum + i; i = i + 1; } Console.Write(sum); i<=10 sum=sum+i; i=i+1; true cout<<sum; false 10i sum 45 11 55 Console.Write(sum);
  • 65. while loop syntax <initialization> while (<test>) { <statement1>; ... <statementN>; <update> }
  • 66. while loop sum example  Sum of numbers from 1..10 int sum = 0; int i = 1; while (i <= 10) { sum = sum + i; i = i + 1; } Printf(“%d”,sum); initialization body statements update test
  • 67. Counter-controlled loop example  Consider the following problem statement: A class of 10 students took a quiz. The grades (integers in the range 0 to 100) for this quiz are available to you. Determine the class average on the quiz.  The algorithm must input each grade, keep track of the total of all grades input, perform the averaging calculation and display the result.
  • 68. Counter-controlled loop code // initialization total = 0; // initialize the total gradeCounter = 1; // initialize the loop counter while ( gradeCounter <= 10 ) // test { printf( "Enter grade: " ); // prompt the user scanf(“%d”, &grade); // read grade total = total + grade; // add the grade to total gradeCounter = gradeCounter + 1; // update } // termination phase average = total / 10; // integer division yields integer result
  • 69. Sentinel-controlled loop example Consider the following problem: Develop a class-averaging application that processes grades for an arbitrary number of students each time it is run. In this example, no indication is given of how many grades the user will enter during the application’s execution.
  • 70. Sentinel-controlled algorithm initialize total to zero initialize counter to zero prompt the user to enter the first grade input the first grade (possibly the sentinel) while the user has not yet entered the sentinel add this grade into the running total add one to the grade counter prompt the user to enter the next grade input the next grade (possibly the sentinel) if the counter is not equal to zero set the average to the total divided by the counter display the average else display “No grades were entered”
  • 71. for loop syntax compared with while <initialization> while (<test>) { <statement1>; ... <statementN>; <update> } for (<initialization>; <test>; <update> ) { <statement1>; ... <statementN>; }
  • 72. Example  Calculate the sum of the integer numbers between 1 and 10 int sum = 0; // this program piece int i = 1; // calculates the sum of while (i <= 10) // integers between and { // including 1 and 10 sum = sum + i; i = i + 1; }
  • 73. Same example with for loop int sum = 0; int i = 1; while (i <= 10) { sum = sum + i; i = i + 1; } int sum = 0; for (int i=1; i <= 10; i=i+1) { sum = sum + i; }
  • 74. Scope of the counter variable in for for (int i=1; i <= 10; i=i+1)  If the initialization expression declares the control variable, the control variable will not exist outside the for statement.  This restriction is known as the variable’s scope.  Similarly, a local variable can be used only in the method that declares the variable and only from the point of declaration. int i; for (i=1; i <= 10; i=i+1)
  • 75. for loop syntax  Comma-separated lists that enable you to use multiple initialization expressions or multiple increment expressions: for ( int i = 2; i <= 20; total += i, i += 2 ) ; // empty statement
  • 76. Bad loops 1. for (int i = 10; i < 5; i=i+1) { printf("How many times do I print?"); } 2. for (int i = 10; i >= 1; i=i+1) { printf("How many times do I print?"); } 3. int i = 1; while (i < 20) { printf("How many times do I print?"); }
  • 77. Other Common Problems  Easy to iterate one more or one less times  Test each loop with the inputs that cause:  zero iterations of the loop body  one iteration of the loop body  maximum number of iterations  one less than the maximum number of iterations  Use the debugger and watch the variables.
  • 78. Developing Loops  Some loops are easy to develop, others are not  Sometimes the proper loop test and body are hard to design  Practice helps, but remember:  Good design comes from experience, experience comes from bad design
  • 79. Factorial  n! = 1x2x…xn is “n factorial”; used in math, statistics long factorial(long n) // pre: 0 <= n // post: returns n! (1 x 2 x … x n)  Similar to sum, but this time we will calculate a product within the loop. At the end we will return the final product.  The loop will iterate n times, multiplying by 1, 2, …, n  Suppose we use a variable called product to hold the result, then product is n! when the loop terminates. Then we will return it at the end.
  • 80. Factorial long Factorial(int num) { long product = 1; int count = 0; while (count < num) { count += 1; product *= count; } return product; }  Issues  Why did we use long? What happens if we use int instead?  What happens if we initialize count to 1?
  • 81. Downward-counting loop  Calculate n to the power of m: nm=nxnx…xn  Example: 25=2x2x2x2x2=32 int power = 1; int n, m; for (int i = m; i <= 1; i--) { power = power * n; }
  • 82. Exercise: Determining if a number is Prime  1 is NOT prime, 2 is prime, 3 is prime, 5 is prime, 17 is prime, … 137, 193?  We do not need to check even numbers other than 2 (2 is a special case)  To check 193, divide it by 3, 5, 7, 9, 11, 13  Note that 14x14 = 196, so 13 largest potential factor?  We can use modulus operator to check divisibility  Check odd numbers as potential divisors  Watch out for 2, it is a special case  How far should we go to check potential divisors?  up to and including Math.Sqrt(number) + 1  If there was a bigger factor, a smaller factor would exist. And this smaller one must have been checked before. So we do not need to go beyond this limit.  +1 is there to make sure that there will be no problems with precision  Write code as exercise at home
  • 83. Nested loops – Example  Write a function to display a perpendicular isosceles triangle of stars (perpendicular side length is parameter)  e.g. if side length is 6 , the output should look like * ** *** **** ***** ******  Exercise: write the same loops downward-counting this time.
  • 84. Exercise: Multiplication Table  On ith line print, i*1, i*2, i*3, ... , i*i  Total number of lines is an input. Display lines starting with 1. Please enter the number of lines in the multiplication table: 9 1 2 4 3 6 9 4 8 12 16 5 10 15 20 25 6 12 18 24 30 36 7 14 21 28 35 42 49 8 16 24 32 40 48 56 64 9 18 27 36 45 54 63 72 81
  • 85. The do-while loop  Similar to while loop, but the test is after the execution of the loop body  The while loop may never execute, do-while loop executes at least once <initialization> do { <statement1>; ... <statementN>; <update> } while (<condition>);  Example: Prompt for a number between 0 and 100, loop until such a number is entered (user should enter at least one number) do { printf(“enter number in range [0..100]"); Scanf(“%d”, &num); } while (num < 0 || num > 100 ); Don’t forget
  • 86. 86 break and continue • The continue statement skips the remaining statements in the loop body and tests whether to proceed with the next iteration of the loop. • In a for statement, the increment expression executes, then the application evaluates the loop-continuation test. Software Engineering Some programmers feel that break and continue statements violate structured programming, since the same effects are achievable with structured programming techniques.
  • 87. BREAK STATEMENT IN C Break statement is used to terminate the while loops, switch case loops and for loops from the subsequent execution. Syntax: break; 87
  • 88. 88 #include <stdio.h> int main() { int i; for(i=0;i<10;i++) { if(i==5) { printf("nComing out of for loop when i = 5"); break; } printf("%d ",i); } } OUTPUT 0 1 2 3 4 Coming out of for loop when i = 5
  • 89. CONTINUE STATEMENT IN C: Continue statement is used to continue the next iteration of for loop, while loop and do-while loops. So, the remaining statements are skipped within the loop for that particular iteration. Syntax : continue; 89
  • 90. 90 #include <stdio.h> int main() { int i; for(i=0;i<10;i++) { if(i==5 || i==6) { printf("nSkipping %d from display using " "continue statement n",i); continue; } printf("%d ",i); } } OUTPUT 0 1 2 3 4 Skipping 5 from display using continue statement Skipping 6 from display using continue statement 7 8 9
  • 91. GOTO STATEMENT IN C  goto statements is used to transfer the normal flow of a program to the specified label in the program.  Below is the syntax for goto statement in C.  { ……. go to label; ……. ……. LABEL: statements; }91
  • 92. 92 #include <stdio.h> int main() { int i; for(i=0;i<10;i++) { if(i==5) { printf("nWe are using goto statement when i = 5"); goto HAI; } printf("%d ",i); } HAI : printf("nNow, we are inside label name "hai" n"); } OUTPUT 0 1 2 3 4 We are using goto statement when i = 5 Now, we are inside label name “hai”
  • 94. Introduction Arrays Structures of related data items Static entity - same size throughout program A few types C-like, pointer-based arrays C++, arrays as objects
  • 95. Arrays  Array  Consecutive group of memory locations  Same name and type  To refer to an element, specify  Array name and position number  Format: arrayname[ position number ]  First element at position 0  n element array c: c[ 0 ], c[ 1 ]…c[ n - 1 ]  Array elements are like normal variables c[ 0 ] = 3; Printf(“%d”, c[ 0 ]);  Performing operations in subscript. If x = 3, c[ 5 – 2 ] == c[ 3 ] == c[ x ]
  • 96. Array in C  C Array is a collection of variables belongings to the same data type.You can store group of data of same data type in an array.  Array might be belonging to any of the data types  Array size must be a constant value.  Always, Contiguous (adjacent) memory locations are used to store array elements in memory.  It is a best practice to initialize an array to zero or null while declaring, if we don‟t assign any values to array. 96
  • 97. Arrays c[6] -45 6 0 72 1543 -89 0 62 -3 1 6453 78 Name of array (Note that all elements of this array have the same name, c) c[0] c[1] c[2] c[3] c[11] c[10] c[9] c[8] c[7] c[5] c[4] Position number of the element within array c
  • 98. Declaring Arrays  Declaring arrays - specify:  Name  Type of array  Number of elements  Examples int c[ 10 ]; float hi[ 3284 ];  Declaring multiple arrays of same type  Similar format as other variables  Example int b[ 100 ], x[ 27 ];
  • 99. Examples Using Arrays  Initializers int n[ 5 ] = { 1, 2, 3, 4, 5 };  If not enough initializers, rightmost elements become 0  If too many initializers, a syntax error is generated int n[ 5 ] = { 0 }  Sets all the elements to 0  If size omitted, the initializers determine it int n[] = { 1, 2, 3, 4, 5 };  5 initializers, therefore n is a 5 element array
  • 100. Examples of Array  int a[10]; // integer array  char b[10]; // character array i.e. string 100
  • 101. Initializing Arrays  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; 101
  • 102.  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 in previous slide −  double salary = balance[9];  The above statement will take the 10th element from the array and assign the value to salary variable. 102
  • 103. Types of Arrays  There are 2 types of C arrays.They are,  One dimensional array  Multi dimensional array  Two dimensional array  Three dimensional array  four dimensional array etc… 103
  • 104. ONE DIMENSIONAL ARRAY IN C:  Array declaration Syntax :  data-type arr_name[array_size];  int age [5];  Array initialization syntax:  data_type arr_name [arr_size]=(value1, value2, value3,….)  int age[5]={0, 1, 2, 3, 4};  Array accessing syntax:  arr_name[index];  age[0]; /*0 is accessed*/ age[1]; /*1 is accessed*/ age[2]; /*2 is accessed*/ 104
  • 105. Character array example  char str[10]; char str[10]={„H‟,„a‟,„i‟}; (or) char str[0] =„H‟; char str[1] =„a‟; char str[2] =„i;  str[0]; /*H is accessed*/ str[1]; /*a is accessed*/ str[2]; /*i is accessed*/ 105
  • 106. EXAMPLE PROGRAM FOR ONE DIMENSIONAL ARRAY IN C #include<stdio.h> int main() { int i; int arr[5] = {10,20,30,40,50}; // declaring and Initializing array in C //To initialize all array elements to 0, use int arr[5]={0}; /* Above array can be initialized as below also arr[0] = 10; arr[1] = 20; arr[2] = 30; arr[3] = 40; arr[4] = 50; */ for (i=0;i<5;i++) { // Accessing each variable printf("value of arr[%d] is %d n", i, arr[i]); } } OUTPUT: value of arr[0] is 10 value of arr[1] is 20 value of arr[2] is 30 value of arr[3] is 40 value of arr[4] is 50 106