User Tools

Site Tools


cs:c_language:while_do-while_for_loops_1
Return to Home page

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

cs:c_language:while_do-while_for_loops_1 [2019/02/26 14:35]
cs:c_language:while_do-while_for_loops_1 [2019/02/26 14:35] (current)
Line 1: Line 1:
 +====== While, do-while and for loops (Example 1) ======
 +**Concepts:​**\\
 +A simple example on the use of the loop constructs: ''​while'',​ ''​do-while''​ e ''​for''​
  
 +**Text:**\\
 +Realize a program that:
 +  * prints as output the numbers between ''​0''​ and ''​n''​
 +  * only ''​n>​0''​ must be taken into account
 +
 +**Solution (while):​**\\
 +<file C while_1.c>​
 +/*
 +  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;
 +}
 +</​file>​
 +
 +**Solution (do-while):​**\\
 +<file C do-while_1.c>​
 +/*
 +  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;
 +}
 +</​file>​
 +
 +**Soluzione (for):**\\
 +<file C for_1.c>
 +/*
 +  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;
 +}
 +</​file>​

If you found any error, or if you want to partecipate to the editing of this wiki, please contact: admin [at] skenz.it

You can reuse, distribute or modify the content of this page, but you must cite in any document (or webpage) this url: https://www.skenz.it/cs/c_language/while_do-while_for_loops_1?do=diff&rev2%5B0%5D=&rev2%5B1%5D=1551188114&difftype=sidebyside
/web/htdocs/www.skenz.it/home/data/pages/cs/c_language/while_do-while_for_loops_1.txt ยท Last modified: 2019/02/26 14:35 (external edit)

Privacy Policy