Академический Документы
Профессиональный Документы
Культура Документы
Note:
The prototype of pow() function is: double pow(double, int) or float pow(float, int)
Solution:
Using for Using while Using do-while
#include<stdio.h> #include<stdio.h> #include<stdio.h>
int main(void) int main(void) int main(void)
{ { {
int ev, sum=0, count=0; int ev,sum,count; int ev,sum,count;
ev=2; ev=2;
for(ev=2; ev<=100; ev += 2) sum=0; sum=0;
{ count=0; count=0;
sum += ev;
count++; while(ev<=100) do
} { {
sum = sum + ev; sum += ev;
printf("%d numbers were ++count; ++count;
added.\n",count); ev = ev+2; ev = ev+2;
} } while(ev<=100);
printf("Sum of the even
numbers is %d\n", sum); printf("%d numbers were printf("%d numbers were
added.\n",count); added.\n",count);
return(0);
} printf("Sum of the even printf("Sum of the even
numbers is %d\n", sum); numbers is %d\n", sum);
return(0); return(0);
} }
Output:
Chapter 5 – Appendix 5/18/2008 Page 3 of 6
3) Write a program that calculate grade average for 10 students ?
Solution:
Using for Using while Using do-while
#include<stdio.h> #include<stdio.h> #include<stdio.h>
Output:
Chapter 5 – Appendix 5/18/2008 Page 4 of 6
4) Write a program that calculate grade average until entering -1 to exit the loop ?
Note 1: Do not use for if you use scanf to update the loop control variable.
Note 2: If you use the loop as a counter, it will be much better to use for and not while.
Solution:
Using while Using do-while
#include<stdio.h> #include<stdio.h>
int main(void) int main(void)
{ {
int counter, total, grade; int total; // sum of grades
double average; int counter; // number of grades entered
total=0; int grade; // one grade
counter=0; double average;
Output:
Chapter 5 – Appendix 5/18/2008 Page 5 of 6
5) Write nests of loops that cause the following output to be displayed:
Inner loop
123456
1 *
**
Outer loop
2
3 ***
****
4 *****
5 ******
6
Solution:
Using for Using for and while Using while Using do-while
(nested loop) (nested loop) (nested loop) (nested loop)
#include<stdio.h> #include<stdio.h> #include<stdio.h> #include<stdio.h>
Output:
Chapter 5 – Appendix 5/18/2008 Page 6 of 6
6) Write nests of loops that cause the following output to be displayed:
0
0 1
0 1 2
0 1 2 3
0 1 2 3 4
0 1 2 3
0 1 2
0 1
0
Solution:
#include<stdio.h>
int main(void)
{
int outer,inner,k,m=0;
for(outer=0;outer<=8;outer++)
{
if(outer<=4)
k=outer;
else
{
m+=2;
k=outer-m;
}
for(inner=0;inner<=k;inner++)
printf("%2d",inner);
printf("\n");
}
return(0);
}
Output: