150 likes | 376 Views
Introduction to Loops. Venkatesh Ramamoorthy 14-Feb-2005. Exercise. Write a simple C++ program that finds the sum of 10 numbers in the following way: Input each number, one by one Prompt for entering the first number Enter the first number into a variable x 1
E N D
Introduction to Loops Venkatesh Ramamoorthy 14-Feb-2005
Exercise • Write a simple C++ program that finds the sum of 10 numbers in the following way: • Input each number, one by one • Prompt for entering the first number • Enter the first number into a variable x1 • Prompt for entering the second number • Enter the second number into a variable x2 • …. • Add up the ten numbers entered as: sum = x1 + x2 + … + x10 • Display “The sum is: ” followed by the sum computed above
More on the problem • What if you had to compute the sum of 100 numbers? • Certainly you wouldn’t want to have 100 variables and 100 different prompts, would you?
Analysis • Sum = x1 + x2 + … + x10 • Alternatively,
How do you read that? • Do you say • “Sigma i = 1 through 10”, xi? • “Summation i = 1 through 10” on xi? • Can you also say • Conceptualize an “accumulator” having the name “sum” • For i = 1 through 10 • Compute: sum = sum + xi • Do you think this will accumulate the total of numbers x1,…x10 into “Sum”?
The for-loop for (index = 1; index <= 10; index = index + 1) { cout << “Enter number : ” ; cin >> x ; sum = sum + x ; } cout << “The sum is : ” << sum ;
The initialization step • What did “sum” initially contain, before we started accumulating the variables into it? • Garbage! • Therefore, always initialize sum to be equal to zero!!
The for-loop – revised sum = 0 ; for (index = 1; index <= 10; index = index + 1) { cout << “Enter number : ” ; cin >> x ; sum = sum + x ; } cout << “The sum is : ” << sum ;
Can you generalize this? • With only one change, can you compute the sum of N numbers, where N is another user input?
What is “Factorial”? • The factorial of n is defined as follows: N! = 1.2.3.4...N, N > 0 0!=1 • Example: 3! = 1.2.3 = 6 4! = 1.2.3.4 = 24
What does the following for-loop try to do? result = 1 ; for (index = 1; index <= 10; index = index + 1) { result = result * index ; } cout << “The result is : ” << result ;
Can you generalize this? • What does the following code do? cout << “Enter N : ” ; cin >> N ; result = 1 ; for (index = 1; index <= N; index = index + 1) { result = result * index ; } cout << “The result is : ” << result ;
Something’s missing! • What happens if N = 0? • Therefore, what remedial action would you take? • Where, in the code?
Factorial using While-loops • Input the value of N • result = 1 • index = 1 • while (index <= N) { result = result * index index = index + 1 }