C Programming Week4
C Programming Week4
1
15/09/17
Example Code with the while Construct Example Code with the for Construct
scanf(“%d”, &n); scanf(“%d”, &n);
value = 1; value = 1;
printf (“current value is %d \n”, value); for (count = 0; count <= n; count = count+1){
counter = 0; if (count == 0) printf(“value is %d \n”,1);
while (counter <= n){ else{
value = 2 * value; value = 2 * value;
printf (“current value is %d \n”, value); printf(value is %d \n”, value);
counter = counter + 1; }
} }
SD, PSK, NSN, DK, TAG – CS&E, IIT M 7
• PSK,
SD, Observe:
NSN, DK, TAG – a mistake
CS&E, IIT M in the earlier program is gone8
Computing the Sum of the First 20 Odd Numbers Calculating Compound Interest a = p(1 + r)n
#include<stdio.h>
int i, j, sum; #include<math.h>
Set j to the first odd number
sum = 0; main( ){ String constants used to align
i : Loop control variable
for (j = 1, i = 1; i <= 20; i = i+1){ int yr; heading and output data in a table
Termination condition
sum += j; double amt, principal = 1000.0, rate = .05;
Increment sum by the ith odd number
j += 2; Set j to the next odd number
printf(“%4s%10s\n”, “year”, “Amount”);
} for (yr = 1; yr < = 10; yr++) {
amt = principal * pow(1.0 + rate, yr);
printf(“%4d%10.2f\n”, yr, amt);
SD, PSK, NSN, DK, TAG – CS&E, IIT M 9
} NSN, DK, TAG – CS&E, IIT M
SD, PSK, 10
2
15/09/17
SD, PSK, NSN, DK, TAG – CS&E, IIT M 13 SD, PSK, NSN, DK, TAG – CS&E, IIT M 14
http://en.wikipedia.org/wiki/Newton's_method
SD, PSK, NSN, DK, TAG – CS&E, IIT M 17 SD, PSK, NSN, DK, TAG – CS&E, IIT M 18
3
15/09/17
Exercises
• Write a program that reads in the entries of a 3x3
matrix, and prints it out in the form of a matrix.
The entries could be floating point too.
• Write a program that reads in orders of two
matrices and decides whether two such matrices
can be multiplied. Print out the decision.
• Write a program that reads in two matrices, and
multiplies them. Your output should be the two
matrices and the resulting product matrix.