Write a program that prints the numbers from 1 to 10.
Program in C
C
#include <stdio.h>
int main() {
int i;
for (i = 1; i <= 10; i++) {
printf("%d\n", i);
}
return 0;
}
Explanation:
- In this program, we declare an integer variable i to use as the loop counter.
- The for loop runs from 1 to 10 (inclusive) with i starting at 1 and incrementing by 1 in each iteration.
- Inside the loop, we use printf to print the value of i, followed by a newline character (\n) to move to the next line.
- Finally, the program returns 0 to indicate successful execution.
Output:
Output
1
2
3
4
5
6
7
8
9
10
Program in Java
Java
public class NumberPrinting {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
System.out.println(i);
}
}
}
Explanation:
- public class NumberPrinting: This line declares a public class named NumberPrinting.
- public static void main(String[] args): This is the main method that serves as the entry point of the program.
- for (int i = 1; i <= 10; i++) { … }: This is a for loop that initializes the loop counter i to 1, executes the loop body as long as i is less than or equal to 10, and increments i by 1 in each iteration.
- System.out.println(i);: This line prints the value of i followed by a newline character.
Output
1
2
3
4
5
6
7
8
9
10