Download lec02-07

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Programming and Data Structure
Sudeshna Sarkar
Lecture 7
1
17.1.2001
Sudeshna Sarkar, IIT Kharagpur
Compute 10!
What is 1*2*3*4*5*6*7*8*9*10 (ten factorial) ?
x = 1*2*3*4*5*6*7*8*9*10;
x=1;
x=x*2;
x=x*3;
x=x*4;
...
x=x*10;
2
x=1;
x=x*i;
x=x*i;
x=x*i;
...
x=x*i;
i=2;
i=i+1;
i=i+1;
i=i+1;
i=i+1;
17.1.2001
x=1;
i=2;
while (i<=10) {
x=x*i;
i=i+1;
}
Sudeshna Sarkar, IIT Kharagpur
Tracing the loop
x=1;
i=2;
/*A*/
/*B*/
while (i<=9) {
x=x*i;
i=i+1;
}
printf(“%d”,x);
/*C*/
/*D*/
/*E*/
/*F*/
/*G*/
3
#
A
B
C
D
E
C
D
E
C
D
E
...
E
C
G
i
x i<9?
?
1
2
1
2
1
T
2
2
3
2
3
2
T
3
6
4
6
4
6
T
4
24
5 24
... ...
10 362880
10 362880 F
(print 362880)
17.1.2001
Sudeshna Sarkar, IIT Kharagpur
Double your money

Suppose your Rs 10000 is earning interest at 1% per
month. How many months until you double your
money ?
my_money=10000.0;
n=0;
while (my_money < 20000.0) {
my_money = my_money*1.01;
n++;
}
printf (“My money will double in %d months.\n”,n);
4
17.1.2001
Sudeshna Sarkar, IIT Kharagpur
Maximum of inputs
printf (“Enter positive numbers to max, end with -1.0\n”);
max = 0.0;
count = 0;
scanf(“%f”, &next);
Exercise: Modify
while (next != 1.0) {
this function to find
if (next > max)
the average and standard
max = next;
deviation of inputs
count++;
scanf(“%f”, &next);
}
printf (“The maximum number is %f\n”, max) ;
5
17.1.2001
Sudeshna Sarkar, IIT Kharagpur
Printing a 2-D Figure

How would you print the following diagram?
*****
*****
*****
6
repeat 3 times
print a row of 5 stars
17.1.2001
repeat 5 times
print *
Sudeshna Sarkar, IIT Kharagpur
Nested Loops
row=1;
#define ROWS 3
while (row <= ROWS) {
#define COLS 5
/* print a row of 5 *’s */
...
col=1;
row=1;
while (col <= COLS) {
while (row <= ROWS) {
printf (“* “);
/* print a row of 5 *’s */
col++;
...
}
row++;
printf(“\n”);
}
row++;
}
7
17.1.2001
outer
loop
inner
loop
Sudeshna Sarkar, IIT Kharagpur
do-while statement
do statement while (expression)
main ()
{
int digit=0;
do
printf(“%d\n”,digit++);
while (digit <= 9) ;
}
8
17.1.2001
statement
F
expression
T
Sudeshna Sarkar, IIT Kharagpur
int main () {
char echo ;
do {
scanf (“%c”, &echo);
printf (“%c”,echo);
} while (echo != ‘\n’) ;
}
9
17.1.2001
Sudeshna Sarkar, IIT Kharagpur
for loop
for ( expression1; expression2; expression3)
statement
expression1 (init) : initialize parameters
expression2 (test): test condition, loop continues if
satisfied
expression3 (reinit): used to alter the value of the
parameters after each iteration
statement (body): body of the loop
10
17.1.2001
Sudeshna Sarkar, IIT Kharagpur
for ( expression1; expression2; expression3)
statement
expression1
(init)
expression1;
while (expression2) {
statement
expression3;
}
expression2
(test)
F
T
statement
(body)
expression3
(reinit)
11
17.1.2001
Sudeshna Sarkar, IIT Kharagpur
Counting in for loops
/* Print n asterisks*/
for (count=1; count <= n; count=count+1) {
printf(“*”);
}
for (count=0; count < n; count=count+1) {
printf(“*”);
}
12
17.1.2001
Sudeshna Sarkar, IIT Kharagpur
2-D Figure
Print
*****
*****
*****
13
#define ROWS 3
#define COLS 5
....
for (row=1; row<=ROWS; row++) {
for (col=1; col<=COLS; col++) {
printf(“*”);
}
printf(“\n”);
}
17.1.2001
Sudeshna Sarkar, IIT Kharagpur
Another 2-D Figure
Print
*
**
***
****
*****
14
#define ROWS 5
....
int row, col;
for (row=1; row<=ROWS; row++) {
for (col=1; col<=row; col++) {
printf(“* ”);
}
printf(“\n”);
}
17.1.2001
Sudeshna Sarkar, IIT Kharagpur
Exercise
Print
*****
****
***
**
*
15
17.1.2001
Sudeshna Sarkar, IIT Kharagpur
Exercise : solution
Print
*****
****
***
**
*
16
#define ROWS 5
....
int row, col;
for (row=0; row<ROWS; row++) {
for (col=1; col<=row; col++)
printf(" ");
for (col=1; col<=ROWS-row; col++)
printf("* ");
printf ("\n");
}
17.1.2001
Sudeshna Sarkar, IIT Kharagpur
Examples : for loop
for (i=0; i<10; i++)
printf (“%d “,i);
output:
0123456789
17
for (i=0; i<= 10; i++)
printf (“%d “,i);
letter = ‘a’;
for (c=0; c < 26; c++)
printf (“%c “, letter+c);
17.1.2001
Sudeshna Sarkar, IIT Kharagpur
Nested for Loop
main ()
{
int multiplicand, multiplier;
for (multiplicand=0; multiplicand<10; multiplicand++) {
for (multiplier=0; multiplier<10; multiplier++) {
printf(“%d\t”, multiplier*multilicand);
}
printf(“\n”);
}
}
18
17.1.2001
Sudeshna Sarkar, IIT Kharagpur
main ()
{
int sum=0;
int input, inner, outer;
printf(“Input an integer : “);
scanf (“%d”, &input) ;
for (outer=1; outer <= input; outer++)
for (inner=0; inner < outer; inner++)
sum += inner;
printf (“The result is %d\n”, sum) ;
}
19
17.1.2001
Sudeshna Sarkar, IIT Kharagpur
Some Loop Pitfalls
while (sum <= NUM) ;
sum = sum+2;
for (i=0; i<=NUM; i++);
sum = sum+i;
for (i=1; i!=10; i=i+2)
sum = sum+i;
double x;
for (x=0.0; x<10.0; x=x+0.2)
printf(“%.18f”, x);
20
17.1.2001
Sudeshna Sarkar, IIT Kharagpur
Doubles and floats
What you expect:
0.000000000000000000
0.200000000000000000
0.400000000000000000
.. .. ..
9.000000000000000000
9.200000000000000000
9.400000000000000000
9.600000000000000000
9.800000000000000000
21
17.1.2001
What you may get:
0.000000000000000000
0.200000000000000000
0.400000000000000000
.. .. ..
8.999999999999999999
9.199999999999999999
9.399999999999999999
9.59999999999999999
9.799999999999999999
Sudeshna Sarkar, IIT Kharagpur
Use ints as loop counters
int i;
double x;
for (i=0; i<50; i=i+1)
{
x = (double)i/5.0;
printf (“%.18f”, x);
}
22
17.1.2001
Sudeshna Sarkar, IIT Kharagpur
Iteration Summary

General Pattern :







23
initialize
test
do stuff
update
go back to re-test, re-do stuff, re-update, ...
while and for are equally general in C
use for when initialize/test/update are simple,
especially when counting.
17.1.2001
Sudeshna Sarkar, IIT Kharagpur
Event Driven Programming

General Pattern :


Program starts, sets itself up.
Waits for some event or command to happen



24
mouse click, key click, timer, menu selection etc.
Program performs operation (“handles” the
command)
Program goes back to waiting.
17.1.2001
Sudeshna Sarkar, IIT Kharagpur
Simple Command Interpreter


Read in “commands” and execute them.
Input - single characters




Pseudocode for main loop:




25
a - execute command Add by calling Add()
s - execute command Sub by calling Sub()
q - quit
get next command
if a, execute command Add()
if b, execute command Sub()
if q, signal quit
17.1.2001
Sudeshna Sarkar, IIT Kharagpur
Command Interpreter
Loop Control
repeat until quit signal
use variable “done” to indicate when done
set done to false
while not done
body statements
if quit command, set done to true
26
17.1.2001
Sudeshna Sarkar, IIT Kharagpur
Command Interpreter program
switch (command) {
case ‘A’:
case ‘a’: Add();
break;
case ‘S’:
case ‘s’: Sub();
break;
case ‘Q’:
case ‘q’: done=TRUE;
}
#define FALSE 0
#define TRUE 1
int main (void)
{
char command;
int done = FALSE;
while (!done) {
printf (“Input command:”);
scanf(“%c”,&command);
}
}
27
17.1.2001
Sudeshna Sarkar, IIT Kharagpur
Exercise a

Write a C program which accepts as input a single
integer k, then writes a pattern consisting of a
single 1 on the first line, two 2s on the 2nd line,
three 3s on the 3rd line, until it writes k
occurrences of k on the last line.
For example, if the input is 4, the output should be:
1
22
333
4444
28
17.1.2001
Sudeshna Sarkar, IIT Kharagpur
Exercise b

Write a C program which accepts as input a single
integer k, then generates the following pattern of k
lines:
For example, if the input is 5, the output should be:
1
222
33333
4444444
555555555
29
17.1.2001
Sudeshna Sarkar, IIT Kharagpur
Test if a number is prime
prime = 1;
for (i=2; i<num; i++)
{
if (num%i == 0)
prime=0;
}
if (prime == 1)
printf (“%d” is a prime number\n”);
30
17.1.2001
Sudeshna Sarkar, IIT Kharagpur
Test if a number is prime
prime = 1;
limit = sqrt ((double)num);
for (i=2; i<limit; i++)
{
if (num%i == 0) {
prime=0;
break;
}
}
if (prime == 1)
printf (“%d” is a prime number\n”);
31
17.1.2001
Sudeshna Sarkar, IIT Kharagpur
Break and continue

These two statements are used in loop
control

“break” exits the innermost current loop (for,
while, do-while) and to exit from a switch
Control will be transferred out of the loop

“continue” starts the next iteration of the
loop (for, while, do-while)

32
used to bypass the remainder of the current pass
through a loop
17.1.2001
Sudeshna Sarkar, IIT Kharagpur
do {
scanf (“%f”, &x);
if (x<0) {
printf(“Error, neg x”);
break;
}
...
/*process non-neg x */
} while (x<=100);
33
for (count=0;count<n;count++)
{
...
while ((c=getchar()) != ‘\n’)
{
if (c==‘*’) break;
...
}
}
17.1.2001
Sudeshna Sarkar, IIT Kharagpur
do {
scanf (“%f”, &x);
if (x<0) {
printf(“Neg value forx”);
continue;
}
...
/*process non-neg x */
} while (x<=100);
34
17.1.2001
Sudeshna Sarkar, IIT Kharagpur
Ex: Write a loop that will calculate the sum of
an AP series upto n terms
Sum= a + (a+d) +(a+2d) + . . . + (a+ (n-1)d)
sum = a;
for (i=1; i<n; i++)
{
sum = sum +a+ i*d;
}
printf (‘%d”, sum);
35
sum = a;
term = a;
for (i=1; i<n; i++)
{
term = term + d;
sum = sum + term;
}
printf (‘%d”, sum);
17.1.2001
Sudeshna Sarkar, IIT Kharagpur
Exercise c

36
Write a C program that takes as input a
positive integer n, and prints all prime
numbers between 2 and n.
17.1.2001
Sudeshna Sarkar, IIT Kharagpur
Exercise d

Write a C program that calculates the sum
of the first n odd numbers:
1 + 3 + 5 + . . . + 2*n-1
37
17.1.2001
Sudeshna Sarkar, IIT Kharagpur
The sine of x can be calculated approximately
by summin the first n terms of the infinite series:
sin x = x - x3 /3! + x5 /5! – x7 /7! + . . .
where x is expressed in radians (p radians = 180
degrees).
Write a C program that will read in a value for x and will
calculate its sine.
 (i) sum the first n terms
 (ii)continue adding successive terms till the value of
the next term becomes smaller (in magnitude) than
10-5
38
17.1.2001
Sudeshna Sarkar, IIT Kharagpur
scanf (“%f”, &x);
x = x*PI/180.0;
sineval = x;
term = x;
for (i=1; i<n; i++)
{
term = (-1)*term*x*x/(2*i*(2*i+1));
sineval = sineval + term;
}
39
17.1.2001
Sudeshna Sarkar, IIT Kharagpur
scanf (“%f”, &x);
x = x*PI/180.0;
sineval = x;
term = x;
for (i=1; term<0.00001; i++)
{
term = (-1)*term*x*x/(2*i*(2*i+1));
sineval = sineval + term;
}
printf (“The value of sine is %f to %d
terms\n”,sineval, i);
40
17.1.2001
Sudeshna Sarkar, IIT Kharagpur
Related documents