Introduction
This lab will guide you on how to write a program in C that sums up N input numbers. We will use a loop to get the sum of all input numbers and display the result.
Getting Started
Before we begin, make sure you have installed a C Compiler on your machine. We will be using GCC for this lab. If you do not have GCC installed, please refer to the official GCC website for installation instructions.
Creating the main.c File
Open your preferred text editor and create a new file named main.c in the ~/project/ directory.
Initializing Variables
In this step, we shall initialize our variables. We need three variables; n, sum and value.
#include <stdio.h>
int main() {
int n, sum = 0, value;
// ...
}
Getting User Input
We shall prompt the user to enter the number of integers they want to add, n. Then, we will ask the user to enter all n integers to add.
#include <stdio.h>
int main() {
int n, sum = 0, value;
printf("Enter the number of integers you want to add: ");
scanf("%d", &n);
printf("Enter %d integers\n", n);
for (int i = 0; i < n; i++) {
printf("Enter the number %d: ", (i + 1));
scanf("%d", &value);
sum += value; // Add value to sum
}
// ...
}
Displaying the Result
Finally, we shall display the sum of all entered integers using the printf function.
#include <stdio.h>
int main() {
int n, sum = 0, value;
printf("Enter the number of integers you want to add: ");
scanf("%d", &n);
printf("Enter %d integers\n", n);
for (int i = 0; i < n; i++) {
printf("Enter the number %d: ", (i + 1));
scanf("%d", &value);
sum += value; // Add value to sum
}
printf("Sum of entered numbers = %d\n", sum);
return 0;
}
Summary
We have successfully written a C program that sums up N input integers and displays the result. In summary, we have covered the following steps:
- Initialized variables
n,sumandvalue. - Prompted the user to input the number of integers they want to add,
n. - Prompted the user to enter all
nintegers. - Added all the input integers to the
sumvariable during each iteration. - Displayed the
sumof all entered integers.
Copy the final code below into your main.c file:
#include <stdio.h>
int main() {
int n, sum = 0, value;
printf("Enter the number of integers you want to add: ");
scanf("%d", &n);
printf("Enter %d integers\n", n);
for (int i = 0; i < n; i++) {
printf("Enter the number %d: ", (i + 1));
scanf("%d", &value);
sum += value; // Add value to sum
}
printf("Sum of entered numbers = %d\n", sum);
return 0;
}



