How to print a cube program in C?
2 min readSep 14, 2023
To print a cube program in C, you can use the following steps:
- Declare an integer variable to store the number whose cube you want to print.
- Prompt the user to enter the number. You can use the
printf()
function for this. - Read the number from the user input using the
scanf()
function. - Calculate the cube of the number and store it in another integer variable.
- Display the cube of the number to the user using the
printf()
function.
Here is an example of a C program to print a cube:
C
#include <stdio.h>
int main() {
int num, cube; // Prompt the user to enter the number.
printf("Enter a number: ");
scanf("%d", &num); // Calculate the cube of the number.
cube = num * num * num; // Display the cube of the number to the user.
printf("The cube of %d is %d.\n", num, cube); return 0;
}
Output:
Enter a number: 5
The cube of 5 is 125.
You can also use a function to calculate the cube of a number. This can be useful if you need to calculate the cube of a number multiple times in your program.
Here is an example of a C function to calculate the cube of a number:
C
int cube(int num) {
return num * num * num;
}
You can then use this function to print the cube of a number as follows:
C
#include <stdio.h>
int cube(int num) {
return num * num * num;
}int main() {
int num, cube; // Prompt the user to enter the number.
printf("Enter a number: ");
scanf("%d", &num); // Calculate the cube of the number using the cube() function.
cube = cube(num); // Display the cube of the number to the user.
printf("The cube of %d is %d.\n", num, cube); return 0;
}
Output:
Enter a number: 5
The cube of 5 is 125.