Concepts:
A simple example on the use of the loop constructs: while
, do-while
e for
Text:
Realize a program that:
0
and n
n>0
must be taken into account
Solution (while):
/* Realize a program that prints as output numbers between 0 and n (with n>0). */ #include <stdio.h> int main() { unsigned int i, n; printf("Number of elements: "); scanf("%d", &n); i=0; while(i<=n){ printf("%3d\n", i); i++; } return 0; }
Solution (do-while):
/* Realize a program that prints as output numbers between 0 and n (with n>0). */ #include <stdio.h> int main() { unsigned int i, n; printf("Number of elements: "); scanf("%d", &n); i=0; do{ printf("%3d\n", i); i++; }while(i<=n); return 0; }
Soluzione (for):
/* Realize a program that prints as output numbers between 0 and n (with n>0). */ #include <stdio.h> int main() { unsigned int i=0, n; printf("Number of elements: "); scanf("%d", &n); for(i=0;i<=n;i++){ /* This instruction can be equivalently written as for(;i<=n;i++), but only because the i variable has been initialized before */ printf("%3d\n", i); } return 0; }