Вы находитесь на странице: 1из 43

TA ZC142 Computer Programming Lecture 5 Date: 23/01/2013

Last Lecture

Switch case statement


Repetition Control Structure for statement while statement do-while statement

Todays Agenda

Continue loops
Do-While Loop

Arrays Derived Data Types


1-D Array 2-D Array Memory organization Programming Exercises

Control Structure

Sequential Control Structure Its a sequential flow of execution of instructions. Selection Control Structure This control structure chooses among alternative program statements.

Repetition Control Structure


This control structure repeats a group of program statements till it satisfies some condition.

Basics of loops
1. 2.

3.

4.

5.

6.

7.
8.

Initialization of a condition variable. Execution of the loop statements. Test for a specified value of the condition variable. Updating the condition variable. C provides three constructs for loop operations The for statement The while statement The do while statement

While

while (test) { loop_body; }

test T loop_body

Loop body can contain block of statements. Executes loop body as long as test evaluates to TRUE (non-zero). Note: Test is evaluated before executing loop body.

Introducing while loop


sum = 0; for (i = 1; i <= 10; i++) sum + = i; sum = 0; i = 0; while (i <= 10) sum += i++;

While loop example


x = 0; while (x < 10) { printf(%d , x); x = x + 1; } char c = Y;

while( c == Y)
{ printf(Inside Loop\n); printf(Do you want to continue inside loop? (Y/N)); c = getchar(); }

Infinite Loops

The following loop will never terminate: Why??? x = 0; while (x < 10) printf(%d , x); Loop body does not change condition, so test never fails. This is a common programming error that can be difficult to find.

Nested Loops

The statement of for is again a for statement Loop body can (of course) be another loop. /* print a multiplication table */ Loop for (m1 = 1; m1 <= 10; m1++) Statement { for (m2 = 1; m2 <= 10; m2++) { printf(%d\t, m1*m2); } printf(\n); }
Braces arent necessary, but they make the code easier to read.

int main() { int n = 100; // number int i, prime = TRUE; for(j=2;j<=n;j++) { for(i=2;i<sqrt(j);i++) if(j%i == 0) { prime = FALSE; break; } if(prime == TRUE) printf("%d is prime\n",n); else printf("%d is not prime\n",n); } }

#define TRUE 1 #define FALSE 0

Arrays
Derived Data Type

Arrays

An array is fixed size sequenced collection of elements of the same data type addressable by index or subscript. It can be used to represent a list of homogenous values Examples: List of marks of students List of employee id no.s in an organization

One Dimensional Arrays

List of items given one variable name using only one subscript Declaration: type variable_name[size]; Here size indicates the maximum number of elements The subscript value start from 0 to size-1 Example: int number[10]; float number[10]; char grade[10];

Initialization

Compile time initialization int num[5]={0,0,0,0,0}; float num[5]={0.0,10.5,11,-13.25}; int num[]={1,2,3,4,5}; is it correct?
Consider the following initialization int num[4]={10,20,30,40,50};
Invalid Statement

Run time initialization


for(i=0; i<10; i++) {/* Reading array elements */ scanf(%d,&nums[i]); } int sum[10]; for(i=0; i<10; i++) { if(i%2 == 0) sum[i]=1; else sum[i]=0; }

All even indexed elements of sum are initialized by 1 and all odd indexed elements of sum are initialized by 0

#include<stdio.h> Read the marks and #include<stdlib.h> calculate the average #define N 10 int main() { float marks[N],sum,ave; int count,no; printf("enter size of array\n"); scanf("%d",&no); if(no > N) { printf("size of array entered by you is exceeding the maximum size\n"); exit(0); } for(sum=0.0,count=0;count<no;count++) { scanf("%f",&marks[count]); sum = sum + marks[count]; } printf("sverage = %f",sum/no); return(0); }

/* Calculate and display the deviation */ for(i=0;i<no; i++) { deviation = marks[i]-average; printf(marks=%d deviation=%d,marks[i],deviation); }

Problems with arrays!!!- No Bound Checking!!!

There is no check in C compiler to see if the subscript used for an array exceeds the size of the array. Data entered with a subscript exceeding the array size will
simply be placed in memory outside the array limit and lead to unpredictable results. Its a programmers responsibility to take care.

Exercise on Arrays

Write a program to find a number in an integer array. Also find the number of times it occurs in the array.

Write a program to find maximum in an array. Also print the index at which it occurs. Write a program copy the elements of one array into another array in reverse order.

Exercise on Arrays

Write a program to count the number of students belonging to each of the following groups of marks: 0-9,10-19,20-29,..,9091,100. Assume there are 50 students. Declare an array to store the frequency of marks in each group.

Do while loop

Do-While
loop_body

do { loop_body; }while (test);

test

Loop body can contain block of statements. Executes loop body as long as test evaluates to TRUE (non-zero). Note: Test is evaluated after executing loop body.

int i = 1,sum = 0; do { sum = sum + i; i = i+2; printf(%d %d \n,i,sum); } while(sum < 40 || i < 10); printf(%d %d \n,i,sum);

OUTPUT i sum

3 1
5 4 7 9 9 16 1125

11

25

Write a program to find total marks in 5 subjects for 50 students. Find the average marks. Find the number of students above average ,below average and at average. Find the maximum total marks. Use arrays.

Write a program to copy the elements of one array into another array in reverse order. Write a program to count the number of students belonging to each of the following groups of marks: 0-9,10-19,20-29,..,9091,100. Assume there are 50 students. Declare an array to store the frequency of marks in each group.

Write

a multiplication table from (1 X 1) to (10 X 10) using do-while loop.

int main() #define MAX1 10 { int m1,m2,product; #define MAX2 5 m2 = 1; do { m1 = 1; do { product = m1 * m2; printf("%d X %d = %d\n",m2,m1,product); m1 = m1 + 1; } while(m1 <= MAX1); printf("-------------------------\n"); m2 = m2+1; } while(m2 <=MAX2); }

Continue statement
continue; sum = 0; for(i=0;i<=1000;i++) { scanf(%f,&x); if(x<0) continue; sum += x; }

Two Dimension Array

Two dimensional arrays also called as matrix Declaration: type variable_name[size1][size2];


size1 >Number of rows in matrix size2 > Number of columns in matrix Examples: int number[4][3]; /* 12 elements */ float number[3][2]; /* 6 elements */ char name[10][20]; /* 200 chars */

Initialization of a 2-D Array


int a[2][3]={1,2,3,4,5,6}; int a[2][3]={{1,2,3}, {4,5,6}}; int a[][3]={{1,2,3}, {4,5,6}} ; How values will be assigned in each case?? Following initializations are not allowed int a[3][]={2,4,6,8,10,12}; int a[][]={2,4,6,8,10,12}; Note: If the first bracket pair is empty, then compiler take the size from the number of inner brace pairs

Memory Map for 2-D Arrays


Kept in memory as a linear sequence of variables. Two methods for storing Row major Column major Example: int a[3][3]; Row major storage: a[0][0], a[0][1], a[0][2], a[1][0], a[1][1], a[1][2], a[2][0], a[2][1], a[2][2] Column major storage: a[0][0], a[1][0], a[2][0], a[0][1], a[1][1], a[2][1], a[0][2], a[1][2], a[2][2]

Accessing Two Dimensional Array

int a[3][4]={1,2,3,4,5,6,7,8,9,10,11,12}; for(i=0;i<3;i++) Output { 1 2 3 4 for(j=0;j<4;j++) 5 6 7 8 { 9 10 11 12 printf(%-4d,a[i][j]); } printf(\n); } Run time initialization of an array can be done in similar way by changing printf() to scanf()inside j loop.

Working with two dimensional Arrays

Matrix Addition and Subtraction

Let A[m][n] and B[p][q] are two matrices. Precondition: m equals to p and n equals to q

Matrix Addition

Algorithm Steps: 1. Read two matrices A and B and initialize C matrix to zero 2. Repeat (3) for i=0 to m-1 3. Repeat (3.a) for j=0 to n-1 3.a) C[i][j] = A[i][j] + B[i][j] 4. Display C matrix.

Write a program to find total marks of 5 students in 3 subjects and store the total marks of each student in a one dimensional array. Also find the highest marks in each subject and store in another array.

Matrix Multiplication: M1xM2

2. 3. 4. 5. 6. 7.

Pre condition: Number of columns in M1 should be equal to number of rows in M2 Algorithm Steps: 1. Read two matrices M1[m][n] and M2[n][r] and initialize another matrix M3[m][r] for storing result. Repeat for i=0 to m-1 Repeat for j=0 to r-1 M3[i][j] = 0 Repeat for k=0 to n-1 M3[i][j] += M1[i][k] * M2[k][j] 3. Print matrix M3.

Write a program to read a matrix of characters. Dimensions are taken from the user. (a) Convert a lower case alphabet into upper case alphabet. if there is a character other than alphabet replace that character with $. Display the final matrix with all the upper case alphabets and $.

(b) Find the vowels in a the resultant matrix. Print number of vowels i in each row. Also print the vowel along with its index. V

Write a program to find transpose of a matrix

Any Doubts or Questions?

Вам также может понравиться