Write a program that prints the sum of all numbers from 1 to 100.
Program in C
C
#include <stdio.h>
int main() {
int sum = 0;
int i;
for (i = 1; i <= 100; i++) {
sum += i;
}
printf("The sum of all numbers from 1 to 100 is: %d\n", sum);
return 0;
}
Explanation:
- In this program, we declare an integer variable sum and initialize it to 0.
- The for loop runs from 1 to 100, and in each iteration, it adds the value of i to the sum variable using the += operator.
- After the loop, we use printf to display the final value of sum.
Output:
Output
The sum of all numbers from 1 to 100 is: 5050
Program in Java
Java
public class SumHundred {
public static void main(String[] args) {
int sum = 0;
int i;
for (i = 1; i <= 100; i++) {
sum += i;
}
System.out.println("The sum of all numbers from 1 to 100 is: " + sum);
}
}
Explanation:
- The public class SumHundred defines a class named SumHundred, which is the entry point for the Java program.
- The public static void main(String[] args) method is the main method, which serves as the starting point for the execution of the program.
- int sum = 0; declares and initializes an integer variable sum to 0, which will store the sum of numbers.
- int i; declares an integer variable i which will be used as a loop counter in the for loop.
- for (i = 1; i <= 100; i++) is a for loop that starts with i being 1, executes the loop body as long as i is less than or equal to 100, and increments i by 1 in each iteration.
- Inside the loop body, sum += i; adds the value of i to the sum variable, effectively summing up all the numbers from 1 to 100.
- System.out.println(“The sum of all numbers from 1 to 100 is: ” + sum); prints the result to the console, concatenating the sum value with the given string.
Output
The sum of all numbers from 1 to 100 is: 5050