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.
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.
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.
main.c
FileOpen your preferred text editor and create a new file named main.c
in the ~/project/
directory.
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;
// ...
}
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
}
// ...
}
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;
}
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:
n
, sum
and value
.n
.n
integers.sum
variable during each iteration.sum
of 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;
}