In this article, we will write a C Program to print cube of a number upto an integer. For example, if the user enters a number 2 then program should print the cube of each number from 1 till the entered number. The output should look like this:
Enter an integer: 2
Cube of 1 is 1
Cube of 2 is 8
C Program to display cube of a number upto a given integer
The explanation of the program is provided at the end of this code.
#include <stdio.h>
int main() {
//n: is the number till which the cube of every number is printed
//i: is the loop counter variable
int n, i;
// Prompt the user to enter an integer
printf("Enter an integer: ");
scanf("%d", &n);
// Loop to calculate and print cube of every number from 1 to n
for(i = 1; i <= n; i++) {
printf("Cube of %d is %d\n", i, i * i * i);
}
return 0;
}
Output:
Enter an integer: 7
Cube of 1 is 1
Cube of 2 is 8
Cube of 3 is 27
Cube of 4 is 64
Cube of 5 is 125
Cube of 6 is 216
Cube of 7 is 343
Explanation of the program:
- C header files: In this program, we have included only one header file
<stdio.h>
, which is required for using theprintf
andscanf
functions. - Main Function: The main functions contains the following statements.
- Variable Declaration: Here, we have two variables, n and i. The variable n is to hold the user entered number and i is the loop counter variable.
- User Input: The program prompts the user to enter an integer using
printf
. Thescanf
function reads the input and stores it in the variablen
. - Loop to Calculate Cubes: A
for
loop iterates from1
ton
. Inside the loop, the cube of the current numberi
is calculated asi * i * i
and printed usingprintf
. - Return Statement: The
return 0
statement represents the successful execution of the program.
Leave a Reply