Professional Documents
Culture Documents
Selection structure:
Used to choose among alternative courses of action
Pseudocode:
If student’s grade is greater than or equal to 60
Print “Passed”
If condition true
Print statement executed and program goes on to next statement
If false, print statement is ignored and the program goes onto the next
statement
Indenting makes programs easier to read
C ignores whitespace characters
Pseudocode statement in C:
if ( grade >= 60 )
printf( "Passed\n" );
C code corresponds closely to the pseudocode
Diamond symbol (decision symbol)
Indicates decision is to be made
Contains an expression that can be true or false
Test the condition, follow appropriate path
A decision can be made on
any expression.
zero - false
nonzero - true
true Example:
grade >= print “Passed”
60 3 - 4 is true
false
if
Only performs an action if the condition is true
if/else
Specifies an action to be performed both when the condition is true and when it
is false
Psuedocode:
If student’s grade is greater than or equal to 60
Print “Passed”
else
Print “Failed”
Note spacing/indentation conventions
C code:
if ( grade >= 60 )
printf( "Passed\n");
else
printf( "Failed\n");
Ternary conditional operator (?:)
Takes three arguments (condition, value if true, value if false)
Our pseudocode could be written:
printf( "%s\n", grade >= 60 ? "Passed" :
"Failed" );
Or it could have been written:
grade >= 60 ? printf( “Passed\n” ) :
printf( “Failed\n” );
false true
grade >= 60
The C language has an unusual operator, useful for making two-
way decisions. This operator is a combination of ? And : and takes
three operands. This operator is popularly known as conditional
operator.
The general form of conditional operator is :
conditional expression ? expression1 : expression2
The conditional expression is evaluated first. If the result is
nonzero, expression1 is evaluated and is returned as the value of
the conditional expression. Otherwise, expression2 is evaluated and
its value is returned.
Salary = 300 for x = 40
4.5x + 150 for x> 40
Can be written as :
Salary=(x<40) ? (4*x+100):(x>40)?(4.5x+150):300;
When a series of decisions are involved, we may have to use more than
one if……….else statement in nested form.
False True
Test condition1
?
statement-3 False True
Test condition 2
?
statement-2 statement-1
statement -
x
Next
statement
Shivani Varshney/RCET/Programming with C
else if ladder
This is used when multipath decisions are involved. A multipath decision is
a chain of ifs in which the statement associated with each else is an if.
if(condition 1)
statement –1;
else if(condition 2)
statement – 2;
else if(condition 3)
statement – 3;
else if(condition n)
statement – n;
else
default - statement;
Shivani Varshney/RCET/Programming with C
Statement – x;
Entry
True false
condition1
false
statement-1 true condition 2
statement-3 false
true
condition n
statement-n Default
statement
statement -
x
Next
Shivani Varshney/RCET/Programming with C
Switch Case Construct
switch
Useful when a variable or expression is tested for all the values it can assume and
different actions are taken
Format
Series of case labels and an optional default case
switch ( value ){
case '1':
actions
case '2':
actions
default:
actions
}
break; exits from structure
true
case a case a action(s) break
false
true
case b case b action(s) break
false
.
.
.
true
case z case z action(s) break
false
default action(s)
True
false
Test condition
True
Counter-controlled repetition
Definite repetition: know how many times loop will execute
Control variable used to count repetitions
Sentinel-controlled repetition
Indefinite repetition
Example:
int counter = 1; //
initialization
while ( counter <= 10 ) { // repetition
condition
printf( "%d\n", counter );
++counter; // increment
}
The statement
int counter = 1;
Names counter
Declares it to be an integer
Reserves space for it in memory
Shivani Varshney/RCET/Programming with C
Sets it to an initial value of 1
The for Repetition Structure
Example:
No
for( int counter = 1; counter <= 10;
semicolon
counter++ ) (;) after last
expression
printf( "%d\n", counter );
Prints the integers from one to ten
Shivani Varshney/RCET/Programming with C
The for Repetition Structure
Arithmetic expressions
Initialization, loop-continuation, and increment can contain
arithmetic expressions. If x equals 2 and y equals 10
for ( j = x; j <= 4 * x * y; j += y /
x )
is equivalent to
for ( j = 2; j <= 80; j += 5 )
Notes about the for structure:
"Increment" may be negative (decrement)
If the loop continuation condition is initially false
The body of the for structure is not performed
Control proceeds with the next statement after the for structure
Control variable
Often printed or used inside for body, but not necessary
Shivani Varshney/RCET/Programming with C
1 /* Fig. 4.5: fig04_05.c
2 Summation with for */
3 #include <stdio.h>
4 Initialize
5 int main() variables
6 {
7 int sum = 0, number;
8
for repetition
9 for ( number = 2; number <= 100; number += 2 )
10 sum += number; structure
11
12 printf( "Sum is %d\n", sum );
13
14 return 0;
15 }
Sum is 2550
Program Output
1 2 3 4 5 6 7 8 9 10
Program Output
C supports the goto statement to branch unconditionally from one
point to another in the program.
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.
The label can be anywhere in the program either before or after the
goto label: statement.
If the label is before the statement goto label; a loop will be formed
and some statement 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.
Shivani Varshney/RCET/Programming with C
Break Statement
/* Count spaces */
#include <stdio.h>
int main(void)
{
char s[80], *str;
int space;
printf("Enter a string: ");
gets(s);
str = s;
for(space=0; *str; str++) {
if(*str != ' ') continue;
space++;
}
printf(''%d spaces\n", space);
return 0;
}
Arrays
Structures of related data items
Static entity – same size throughout program
Dynamic data structures discussed in Chapter 12
Initializers
int n[ 5 ] = { 1, 2, 3, 4, 5 };
If not enough initializers, rightmost elements become 0
int n[ 5 ] = { 0 }
All elements 0
If too many a syntax error is produced syntax error
C arrays have no bounds checking
If size omitted, initializers determine it
int n[ ] = { 1, 2, 3, 4, 5 };
5 initializers, therefore 5 element array
Function prototype
void modifyArray( int b[], int
arraySize );
Parameter names optional in prototype
int b[] could be written int []
int arraySize could be simply int
Sorting data
Important computing application
Virtually every organization must sort some data
Bubble sort (sinking sort)
Several passes through the array
Successive pairs of elements are compared
If increasing order (or identical ), no change
If decreasing order, elements exchanged
Repeat
Example:
original: 3 4 2 6 7
pass 1: 3 2 4 6 7
pass 2: 2 3 4 6 7
Small elements "bubble" to the top
Mean – average
Median – number in middle of sorted list
1, 2, 3, 4, 5
3 is the median
Mode – number that occurs most often
1, 1, 1, 2, 3, 3, 4, 5
1 is the mode
********
Median
********
The unsorted array of responses is
7 8 9 8 7 8 9 8 9 7 8 9 5 9 8 7 8 7 8
6 7 8 9 3 9 8 7 8 7 7 8 9 8 9 8 9 7 8 9
6 7 8 7 8 7 9 8 9 2 7 8 9 8 9 8 9 7 5 3
5 6 7 2 5 3 9 4 6 4 7 8 9 6 8 7 8 9 7 8
7 4 4 2 5 3 8 7 5 6 4 5 6 1 6 5 7 8 7
1 1 2 2
5 0 5 0 5
1 1 *
2 3 ***
3 4 ****
4 5 *****
5 8 ********
6 9 *********
7 23 ***********************
8 27 ***************************
9 19 *******************
The mode is the most frequent value.
For this run the mode is 8 which occurred 27 times.
Binary search
For sorted arrays
Compares middle element with key
If equal, match found
If key < middle, looks in first half of array
If key > middle, looks in last half
Repeat
Column subscript
Array
name Row subscript
1 2
Initialization 3 4
int b[ 2 ][ 2 ] = { { 1, 2 }, { 3, 4 } };
Initializers grouped by row in braces
If not enough, unspecified elements set to zero 1 0
3 4
int b[ 2 ][ 2 ] = { { 1 }, { 3, 4 } };
Referencing elements
Specify row, then column
printf( "%d", b[ 0 ][ 1 ] );
Lowest grade: 68
Highest grade: 96
The average grade for student 0 is 76.00
The average grade for student 1 is 87.50
The average grade for student 2 is 81.75
Character arrays
String “first” is really a static array of characters
Character arrays can be initialized using string literals
Row 0 a[ 0 ][ 0 ] a[ 0 ][ 1 ] a[ 0 ][ 2 ] a[ 0 ][ 3 ]
Row 1 a[ 1 ][ 0 ] a[ 1 ][ 1 ] a[ 1 ][ 2 ] a[ 1 ][ 3 ]
Row 2
a[ 2 ][ 0 ] a[ 2 ][ 1 ] a[ 2 ][ 2 ] a[ 2 ][ 3 ]
Column subscript
Array
name Row subscript
1 2
Initialization
3 4
int b[ 2 ][ 2 ] = { { 1, 2 }, { 3, 4 } };
Initializers grouped by row in braces
If not enough, unspecified elements set to zero 1 0
int b[ 2 ][ 2 ] = { { 1 }, { 3, 4 } };3 4
Referencing elements
Specify row, then column
printf( "%d", b[ 0 ][ 1 ] );
Lowest grade: 68
Highest grade: 96
The average grade for student 0 is 76.00
The average grade for student 1 is 87.50
The average grade for student 2 is 81.75
x=&i;
y=&j;
&k;
printf(“Original value in x = %u”,x);
printf(“Original value in y = %u”,y);
printf(“Original value in z = %u”,z);
main()
{
int a[ ]={15,17,23,43,22},i=0,*j;
j=&a[0];
while(i<5)
{
printf(“\nAddress = %u”,&a[i]);
printf(“\nElement = %d”,*j);
i++;
j++;
}
}
main()
{
int a[ ]={15,17,23,43,22},i=0;
while(i<5)
{
printf(“\nAddress = %u”,&a[i]);
printf(“Element = %d ”,a[i]);
printf(“%d “,*(a+i));
printf(“%d “,*(i+a));
printf(“%d “,i[a]);
i++;
}
}
main()
{
int arr[5][2] = {
{11,12},
{21,22},
{31,32},
{41,42},
{51,52}
};
int i,j;
for(i=0;i<=4;i++)
for(j=0;j<=1;j++)
printf(“%d ”,*(*(a+i)+j));
}
Shivani Varshney/RCET/Programming with C
Array of Pointers
main()
{
int *arr[5],i;
printf(“Enter 5 nos:\n”);
for(i=0;i<5;i++)
scanf(“%d”,(arr+i));
printf(“Entered nos.\n”);
for(i=0;i<5;i++)
printf(“%d ”,*(arr+i));
}