Last time, I showed you how to create a simple addition program using C language. Now, we will still be adding numbers but I put something new in it. Yes, we will still add integers/numbers but it is now in the users decision how many integers he will add.
We will still use int as our data identifier because we are still inputting integers. The new command we're going to put into the code is the for loop statement. This statement will control how many inputs a user want. From the name itself, loop, it means infinity. For loop is a repetitive statement, the program will not stop/end until the argument inside the loop is met. This statement is useful when you have to make repetitive programs because this will excuse you from doing the same code again and again.
The program you see below is an example of adding numbers but inputs can be manipulated by the user. Check out the codes below.
1:
2:
3:
4: #include <stdio.h>
5: #include <conio.h>
6:
7: int main()
8: {
9: int a, b = 0, c = 1, sum = 0;
10:
11: printf("How many numbers you want to add?: ");
12: scanf("%d", &a);
13:
14: for(sum = sum + b;c <= a;c++)
15: {
16: printf("\nEnter a number: ");
17: scanf("%d",&b);
18: sum = sum + b;
19: }
20:
21: printf("\nThe sum is: %d", sum);
22: getch();
23: }
When the program runs, first it will ask the user how many numbers he want to add then variable a will be the storage for that input. After entering how many numbers the user want to add, the program will then jump to the next step which is entering the numbers you want to add. For example, you entered five (5) then the program will then get five (5) inputs from the user. The for loop statement will carry the looping operation. If variable c satisfies variable a, which is the storage for how many times the loop would ask the user to enter a number, the loop will stop and print the sum of the numbers. If it does not satisfy, the loop will continue to ask the user the same question again and again until it satisfies variable a. After the looping process, the result will then be shown. Then, you can terminate the program. You can check out the sample output below.
Hope you learned something from this post. Feel free to leave a comment below. Thanks!
|
No comments:
Post a Comment
Please do leave a comment. It's gonna be a friendly conversation between programmers. Hope you do find our blog helpful. Thank you!