0% found this document useful (0 votes)
21 views63 pages

Loops

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 63

Computer Fundamentals

and C Programming
Dr. Kunwar Pal
CSED
NITJ

1
The Switch Case Control
Structure
switch ( integer expression )
{
case constant 1 :
do this ;
case constant 2 :
do this ;
case constant 3 :
do this ;
default :
do this ;
}

2
Example
main( )
{
int i = 2 ;
switch ( i )
{
case 1 :
printf ( "I am in case 1 \n" ) ;
case 2 :
printf ( "I am in case 2 \n" ) ;
case 3 :
printf ( "I am in case 3 \n" ) ;
default :
printf ( "I am in default \n" ) ;
}
}

3
Example
main( )
{
int i = 2 ;
switch ( i )
{
case 1 :
printf ( "I am in case 1 \n" ) ;
break ;
case 2 :
printf ( "I am in case 2 \n" ) ;
break ;
case 3 :
printf ( "I am in case 3 \n" ) ;
break ;
default :
printf ( "I am in default \n" ) ;
}
}

4
The Tips and Traps
(a) The earlier program that used switch may give you the wrong impression
that you can use only cases arranged in ascending order, 1, 2, 3 and default. You
can in fact put the cases in any order you please. Here is an example of
scrambled case order:
main( )
{
int i = 22 ;
switch ( i )
{
case 121 :
printf ( "I am in case 121 \n" ) ;
break ;
case 7 :
printf ( "I am in case 7 \n" ) ;
break ;
case 22 :
printf ( "I am in case 22 \n" ) ;
break ;
default :
printf ( "I am in default \n" ) ;
}
}

5
The Tips and Traps
(b) You are also allowed to use char values in case
and switch as shown in the following program:
main()
{
char c = 'x' ;
switch ( c )
{
case 'v' :
printf ( "I am in case v \n" ) ;
break ;
case 'a' :
printf ( "I am in case a \n" ) ;
break ;
case 'x' :
printf ( "I am in case x \n" ) ;
break ;
default :
printf ( "I am in default \n" ) ;
}
}

6
The Tips and Traps
At times we may want to execute a common set of statements for multiple
cases. How this can be done is shown in the following example.
main( )
{
char ch ;
printf ( "Enter any of the alphabet a, b, or c " ) ;
scanf ( "%c", &ch ) ;
switch ( ch )
{
case 'a' :
case 'A' :
printf ( "a as in ashar" ) ;
break ;
case 'b' :
case 'B' :
printf ( "b as in brain" ) ;
break ;
case 'c' :
case 'C' :
printf ( "c as in cookie" ) ;
break ;
default :
printf ( "wish you knew what are alphabets" ) ;
}
}

7
The Tips and Traps
Even if there are multiple statements to be executed in each case there is no
need to enclose them within a pair of braces (unlike if, and else).
Every statement in a switch must belong to some case or the other. If a
statement doesn’t belong to any case the compiler won’t report an error.
However, the statement would never get executed. For example, in the following
program the printf( ) never goes to work.
main( )
{
int i, j ;
printf ( "Enter value of i" ) ;
scanf ( "%d”, &i ) ;
switch ( i )
{
printf ( "Hello" ) ;
case 1 :
j = 10 ;
break ;
case 2 :
j = 20 ;
break ;
}
}

8
The Tips and Traps
If we have no default case, then the program simply falls through the
entire switch and continues with the next instruction (if any,) that follows
the closing brace of switch.
Is switch a replacement for if? Yes and no. Yes, because it offers a better
way of writing programs as compared to if, and no because in certain
situations we are left with no choice but to use if. The disadvantage of
switch is that one cannot have a case in a switch which looks like:
case i <= 20 :
All that we can have after the case is an int constant or a char constant or
an expression that evaluates to one of these constants. Even a float is not
allowed.
We can check the value of any expression in a switch. Thus the following
switch statements are legal.
switch ( i + j * k )
switch ( 23 + 45 % 4 * k )
switch ( a < 4 && b > 7 )
Expressions can also be used in cases provided they are constant
expressions. Thus case 3 + 7 is correct, however, case a + b is incorrect.

9
The Tips and Traps
The break statement when used in a switch takes the
control outside the switch. However, use of continue will
not take the control to the beginning of switch as one is
likely to believe.
In principle, a switch may occur within another, but in
practice it is rarely done. Such statements would be called
nested switch statements.
The switch statement is very useful while writing menu
driven programs. This aspect of switch is discussed in the
exercise at the end of this chapter.

10
LOOPS

11
INTRODUCTION  Statements in a program are
executed one after the other
◦ ex: statement 1;
◦ statement 2;
◦ :
◦ statement n;
Sometimes, the user want to execute a set of
statements repeatedly.

12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
It is important to note that the initialization, testing and incrementation part of a for
loop can be replaced by any valid expression. Thus the following for loops are
perfectly ok.

❑ for ( i = 10 ; i ; i -- )
printf ( "%d", i ) ;
❑ for ( i < 4 ; j = 5 ; j = 0 )
printf ( "%d", i ) ;
❑ for ( i = 1; i <=10 ; printf ( "%d",i++ )) ;
❑ for ( scanf ( "%d", &i ) ; i <= 10 ; i++ )
printf ( "%d", i )

27
Points
main( )
{ int i ;
for ( i = 1 ; i <= 10 ; )
{
printf ( "%d\n", i ) ; i = i + 1 ;
}
}

Here, the incrementation is done within the body of the for loop and not in the for
statement. Note that inspite of this the semicolon after the condition is necessary

28
main( )
{
◦ int i = 1 ; for ( ; i <= 10 ; )
◦ {
◦ printf ( "%d\n", i ) ; i = i + 1 ;
◦ }
}
Here, neither the initialisation, nor the incrementation is done in the for statement,
but still the two semicolons are necessary.

29
30
1
12
123
1234
12345

31
#include <stdio.h>
int main() {
int i, j, rows;
printf("Enter the number of rows: ");
scanf("%d", &rows);
for (i = 1; i <= rows; ++i) {
for (j = 1; j <= i; ++j) {
printf("%d ", j);
}
printf("\n");
}
return 0;
}

32
* ****
* ***
* **
* *
*

33
#include <stdio.h>
int main() {
int i, j, rows;
printf("Enter the number of rows: ");
scanf("%d", &rows);
for (i = rows; i >= 1; --i) {
for (j = 1; j <= i; ++j) {
printf("* ");
}
printf("\n");
}
return 0;
}

34
35
Arrays
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.
All arrays consist of contiguous memory locations. The lowest
address corresponds to the first element and the highest
address to the last element.

36
Array Declaration
Syntax
type arrayName [arraySize ];
Example
double balance[10];
int arr[5];
char name[10];

37
Array Initialization
Examples
int num[6] = { 2, 4, 12, 5, 45, 5 } ;
int n[ ] = { 2, 4, 12, 5, 45, 5 } ;
float press[ ] = { 12.3, 34.2 -23.4, -11.3 } ;
Till the array elements are not given any specific values, they are supposed to contain
garbage values.
int B[20] = {2, 4, 8, 16, 32};
● Unspecified elements are guaranteed to be zero
int C[4] = {2, 4, 8, 16, 32};
● Error — compiler detects too many initial values
int E[5] = {1};
● Dynamically allocated array (automatic only). Zeroth element initialized to 1; all other
elements initialized to 0.
▪ int E[5] = {0};
▪ All elements initialize to zero

38
Memory Organization for an
array
Suppose we have declared and initializes an
array as
int score[7]={5,2,8,0,1,9,4};

39
Entering Data into array
void main()
{ Assigning values to
int marks[5], i; array
for ( i = 0 ; i <= 4 ; i++ )
{ marks[0]=50;
printf ( "\nEnter marks " ) ; marks[1]=60;
scanf ( "%d", &marks[i] ) ; marks[2]=55;
}
marks[3]=45;
marks[4]=55;
}

Reading data from an


array
for ( i = 0 ; i <= 29 ; i++ )
sum = sum + marks[i] ;
avg = sum / 30 ;
printf ( "\nAverage marks = %d", avg ) ;

40
Bounds Checking
In C there is no check to see if the subscript
used for an array exceeds the size of the array.

main( )
{
int num[40], i ;
for ( i = 0 ; i <= 100 ; i++ )
num[i] = i ;
}

41
Two Dimensional Array
The two dimensional array is also called a matrix.
main( )
{
int stud[4][2] ; //declaration
int i, j ;
for ( i = 0 ; i <= 3 ; i++ )
{
printf ( "\n Enter roll no. and marks" ) ;
scanf ( "%d %d", &stud[i][0], &stud[i][1] ) ;
}
for ( i = 0 ; i <= 3 ; i++ )
printf ( "\n%d %d", stud[i][0], stud[i][1] ) ;
}

42
Initialising a 2-Dimensional
Array
int stud[4][2] = {
{ 1234, 56 },
{ 1212, 33 },
{ 1434, 80 },
{ 1312, 78 }
};

int stud[4][2] = { 1234, 56, 1212, 33, 1434, 80, 1312, 78 } ;

It is important to remember that while initializing a 2-D array it is


necessary to mention the second (column) dimension, whereas the
first dimension (row) is optional.
int arr[2][3] = { 12, 34, 23, 45, 56, 45 } ;
int arr[ ][3] = { 12, 34, 23, 45, 56, 45 } ;
are perfectly acceptable,
whereas,
int arr[2][ ] = { 12, 34, 23, 45, 56, 45 } ;
int arr[ ][ ] = { 12, 34, 23, 45, 56, 45 } ;
would never work.
43
Memory Map of a
2-Dimensional Array

44
Pointer Notation
Consider the declaration,
int i = 3 ;
This declaration tells the C compiler to:
(a) Reserve space in memory to hold the integer value.
(b) Associate the name i with this memory location.
(c) Store the value 3 at this location.

45
What are Pointers?
• A pointer is a variable whose value is the address of another variable,
i.e., direct address of the memory location.
• Like any variable or constant, you must declare a pointer before using it
to store any variable address.
Pointer variable declaration:
type *var-name;
Here, type is the pointer's base type; it must be a valid C data type and
varname is the name of the pointer variable. The asterisk * used to declare a
pointer is the same asterisk used for multiplication.
Examples: some of the valid pointer declarations:
int *ip; /* pointer to an integer */
double *dp; /* pointer to a double */
float *fp; /* pointer to a float */
char *ch /* pointer to a character */
46
How to Use
Three things need to do
Pointers?
(1) We define a pointer variable,
(2) Assign the address of a variable to a pointer, and
(3) Finally access the value at the address available in the pointer variable.
This is done by using unary operator *. Which says the value at the address.
main( ) output:
{
int i = 3 ; Address of i = 65524
printf ( "\nAddress of i = %u", &i ) ; Value of i = 3
printf ( "\nValue of i = %d", i ) ;
}

main( ) output
{
int i = 3 ; Address of i = 65524
printf ( "\nAddress of i = %u", &i ) ; Value of i = 3
printf ( "\nValue of i = %d", i ) ; Value of i = 3
printf ( "\nValue of i = %d", *( &i ) ) ;
}
47
How to Use Pointers?
The expression &i gives the address of the variable i. This address can be
collected in a variable, by saying,
j = &i ;
But remember that j is not an ordinary variable like any other integer variable.
It is a variable that contains the address of other variable (i in this case).

j is a variable that contains the address of i, it is declared as,


int *j ;

48
How to Use Pointers?
main( ) The output of the above program would
{ be:
int i = 3 ; Address of i = 65524
int *j ; Address of i = 65524
j = &i ; Address of j = 65522
printf ( "\nAddress of i = %u", &i ) ; Value of j = 65524
printf ( "\nAddress of i = %u", j ) ; Value of i = 3
printf ( "\nAddress of j = %u", &j ) ; Value of i = 3
printf ( "\nValue of j = %u", j ) ; Value of i = 3
printf ( "\nValue of i = %d", i ) ;
printf ( "\nValue of i = %d", *( &i ) ) ;
printf ( "\nValue of i = %d", *j ) ;
}

49
Pointer to Pointer or Double
pointer
• A pointer to a pointer is a form of multiple indirection, or a chain of pointers.
• When we define a pointer to a pointer, the first pointer contains the address of
the second pointer, which points to the location that contains the actual value as
shown below.
int i=3;
int *j=&i;
int **k=&j;

50
Example
main( ) The output of the above program would be:
{ Address of i = 65524
int i = 3, *j, **k ; Address of i = 65524
j = &i ; Address of i = 65524
k = &j ; Address of j = 65522
printf ( "\nAddress of i = %u", &i ) ; Address of j = 65522
printf ( "\nAddress of i = %u", j ) ; Address of k = 65520
printf ( "\nAddress of i = %u", *k ) ; Value of j = 65524
printf ( "\nAddress of j = %u", &j ) ; Value of k = 65522
printf ( "\nAddress of j = %u", k ) ; Value of i = 3
printf ( "\nAddress of k = %u", &k ) ; Value of i = 3
printf ( "\nValue of j = %u", j ) ; Value of i = 3
printf ( "\nValue of k = %u", k ) ; Value of i = 3
printf ( "\nValue of i = %d", i ) ;
printf ( "\nValue of i = %d", * ( &i ) ) ;
printf ( "\nValue of i = %d", *j ) ;
printf ( "\nValue of i = %d", **k ) ;
}

51
NULL Pointers
• It is always a good practice to assign a NULL value to a pointer variable in case
you do not have an exact address to be assigned.
• This is done at the time of variable declaration.
• A pointer that is assigned NULL is called a null pointer.
• The NULL pointer is a constant with a value of zero defined in several standard
libraries.
#include <stdio.h> Output
int main ()
{ The value of ptr is 0
int *ptr = NULL;
printf("The value of ptr is : %x\n", ptr );
return 0;
}

52
Operations on pointers (Pointers
arithmetic )
• There are four arithmetic operators that can be used in pointers: ++, --, +, -
• A pointer in C is an address, which is a numeric value. Therefore, you can
perform arithmetic operations on a pointer just as you can on a numeric value.
Incrementing a Pointer
#include <stdio.h> Output
int main ()
{ Address of var[0] = bf882b30
int var[] = {10, 100, 200}; Value of var[0] = 10
int i, *ptr; Address of var[1] = bf882b34
/* let us have array address in pointer */ Value of var[1] = 100
ptr = var; Address of var[2] = bf882b38
for ( i = 0; i < 3; i++) Value of var[2] = 200
{
printf("Address of var[%d] = %x\n", i, ptr );
printf("Value of var[%d] = %d\n", i, *ptr );
/* move to the next location */
ptr++;
}
return 0;
}
53
Operations on pointers (Pointers
arithmetic )
Decrementing a Pointer

#include <stdio.h> Address of var[3] =


const int MAX = 3; bfedbcd8
int main () Value of var[3] = 200
{ int var[] = {10, 100, 200}; Address of var[2] =
int i, *ptr; bfedbcd4
ptr = &var[MAX-1]; Value of var[2] = 100
for ( i = MAX; i > 0; i--) Address of var[1] =
{ bfedbcd0
printf("Address of var[%d] = %x\n", i, ptr ); Value of var[1] = 10
printf("Value of var[%d] = %d\n", i, *ptr );
ptr--;
}
return 0;
}

54
Operations on pointers (Pointers
arithmetic)
• Addition of a number to a pointer. For example,
int i = 4, *j, *k ;
j = &i ;
j=j+1;
j=j+9;
k=j+3;

• Subtraction of a number from a pointer. For example,


int i = 4, *j, *k ;
j = &i ;
j=j-2;
j=j-5;
k=j-6;

55
Operations on pointers (Pointers
arithmetic )
Subtraction of one pointer from another.
• One pointer variable can be subtracted from another provided both variables point to
elements of the same array.
• The resulting value indicates the number of bytes separating the corresponding array
elements.

main( )
{
int arr[ ] = { 10, 20, 30, 45, 67, 56, 74 } ;
int *i, *j ;
i = &arr[1] ;
j = &arr[5] ;
printf ( "%d %d", j - i, *j - *i ) ;
}

56
Comparison of two pointer variables
Pointer variables can be compared provided both variables point to
objects of the same data type.
Such comparisons can be useful when both pointer variables point
to elements of the same array.
The comparison can test for either equality or inequality. Moreover,
a pointer variable can be compared with zero (usually expressed as
NULL).
main( )
{
int arr[ ] = { 10, 20, 36, 72, 45, 36 } ;
int *j, *k ;
j = &arr [ 4 ] ;
k = ( arr + 4 ) ;
if ( j == k )
printf ( "The two pointers point to the same location" ) ;
else
printf ( "The two pointers do not point to the same location" ) ;
}

57
Operation do not work with
pointer
Do not attempt the following operations on pointers... they
would never work out.
(a) Addition of two pointers
(b) Multiplication of a pointer with a constant
(c) Division of a pointer with a constant

58
Array of pointers
• There may be a situation when we want to maintain an array, which can store
pointers to an int or char or any other data type available.
• Following is the declaration of an array of pointers to an integer:
int *ptr[MAX];
• Each element in ptr holds a pointer to an int value.

#include <stdio.h> Value of var[0] = 10


const int MAX = 3; Value of var[1] = 100
int main () Value of var[2] = 200
{
int var[] = {10, 100, 200};
int i, *ptr[MAX];
for ( i = 0; i < MAX; i++)
{
ptr[i] = &var[i]; /* assign the address of integer. */
}
for ( i = 0; i < MAX; i++)
{
printf("Value of var[%d] = %d\n", i, *ptr[i] );
}
return 0;
}
59
Pointer and Array
Array elements are always stored in contiguous memory locations.
A pointer when incremented always points to an immediately next location of its type.
Suppose we have an array num[ ] = { 24, 34, 12, 44, 56, 17 }

main( ) output
{ element no. 0 address = 65512 value=24
int num[ ] = { 24, 34, 12, 44, 56, 17 } ; element no. 1 address = 65514 value=34
int i ; element no. 2 address = 65516 value=12
for ( i = 0 ; i <= 5 ; i++ ) element no. 3 address = 65518 value=44
{ element no. 4 address = 65520 value=56
printf ( "\nelement no. %d ", i ) ; element no. 5 address = 65522 value=17
printf ( "address = %u", &num[i] ) ;
printf ( “value = %d", num[i] ) ;
}
}

60
Pointer and Array
Accessing elements of the array elements using pointers.
main( )
{
int num[ ] = { 24, 34, 12, 44, 56, 17 } ;
int i, *j ;
j = &num[0] ; /* assign address of zeroth element */
for ( i = 0 ; i <= 5 ; i++ )
{
printf ( "\naddress = %u ", j ) ;
printf ( "element = %d", *j ) ;
j++ ; /* increment pointer to point to next location */
}
}
The output of this program would be:
address = 65512 element = 24
address = 65514 element = 34
address = 65516 element = 12
address = 65518 element = 44
address = 65520 element = 56
address = 65522 element = 17
61
The real thing
int num[ ] = { 24, 34, 12, 44, 56, 17 } ;

• num, is an integer pointer that point the base address of this integer array
so *num will give 24, which can be accessed equivalently as *(num+0)
and num[0]
• Similarly, (num+1) will increment the pointer by one location and thus
*(num+1) give 34, which can be accessed equivalently as *(num+1) and
num[1]
• Generalize one is (num+i) to point the address of ith location in an array,
where *(num+i) or num[i] are used to access the value at the address of ith
position and can also be written as *( i + num ), i[num].

62
Example
/* Accessing array elements in different ways */
main( )
{
int num[ ] = { 24, 34, 12, 44, 56, 17 } ;
int i ;
for ( i = 0 ; i <= 5 ; i++ )
{
printf ( "\naddress = %u ", &num[i] ) ;
printf ( "element = %d %d ", num[i], *( num + i ) ) ;
printf ( "%d %d", *( i + num ), i[num] ) ;
}
}
Output
address = 65512 element = 24 24 24 24
address = 65514 element = 34 34 34 34
address = 65516 element = 12 12 12 12
address = 65518 element = 44 44 44 44
address = 65520 element = 56 56 56 56
address = 65522 element = 17 17 17 17

63

You might also like