cs:c_language:while_cycle_1
Return to Home page
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_cycle_1?do=diff&rev2%5B0%5D=&rev2%5B1%5D=1551188114&difftype=sidebyside
no way to compare when less than two revisions
Differences
This shows you the differences between two versions of the page.
— | cs:c_language:while_cycle_1 [2024/04/08 22:35] (current) – created - external edit 127.0.0.1 | ||
---|---|---|---|
Line 1: | Line 1: | ||
+ | ====== while cycle (Example 1) ====== | ||
+ | **Concepts: | ||
+ | //While// cycle, //if// instruction, | ||
+ | **Text:**\\ | ||
+ | Implement a C program that: | ||
+ | * acquires 5 number from the keybord | ||
+ | * computes how many even and odd numbers are inserted | ||
+ | * prints the results of this computation | ||
+ | |||
+ | **Solution: | ||
+ | <file C while_cycle_1.c> | ||
+ | /* Insert 5 numbers using the keyboard and count how many even and odd numbers have been inserted */ | ||
+ | |||
+ | #include < | ||
+ | #define NUMBERS 5 | ||
+ | |||
+ | int main(){ | ||
+ | int n; | ||
+ | int x; | ||
+ | int n_even, n_odd; | ||
+ | |||
+ | n=0; | ||
+ | n_even=0; | ||
+ | n_odd=0; | ||
+ | |||
+ | while(n< | ||
+ | printf(" | ||
+ | scanf(" | ||
+ | |||
+ | if (x%2 == 0) { | ||
+ | printf(" | ||
+ | n_even = n_even+1; | ||
+ | }else{ | ||
+ | printf(" | ||
+ | n_odd = n_odd+1; | ||
+ | } | ||
+ | |||
+ | n = n+1; | ||
+ | } | ||
+ | |||
+ | printf(" | ||
+ | |||
+ | return 0; | ||
+ | } | ||
+ | </ | ||
+ | |||
+ | **Comments: | ||
+ | The program executes 5 times the block of code inside the //while// cycle that: | ||
+ | * asks the user to insert a number | ||
+ | <code c> | ||
+ | scanf(" | ||
+ | </ | ||
+ | * checks if the number is even //if (x%2 == 0)// or odd (branch //else// of the //if// instruction) | ||
+ | <code c> | ||
+ | if (x%2 == 0) { | ||
+ | /* Code executed if x is even */ | ||
+ | |||
+ | }else{ | ||
+ | /* Code executed if x is odd */ | ||
+ | } | ||
+ | </ | ||
+ | * in the case of an even, it increments the variable //n_even//, otherwise, in the case of an odd number, it increments the variable //n_odd// | ||
+ | * at the ends of the //while// cycle the program prints the results | ||
+ | <code c> | ||
+ | printf(" | ||
+ | </ |
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_cycle_1?do=diff&rev2%5B0%5D=&rev2%5B1%5D=1551188114&difftype=sidebyside
/web/htdocs/www.skenz.it/home/data/pages/cs/c_language/while_cycle_1.txt · Last modified: 2024/04/08 22:35 by 127.0.0.1