How to write a C Program to Calculate Cube of a Number using Functions with an example?

C Program to Calculate Cube of a Number

#include<stdio.h>

void main ()
{
int i,cube;
scanf("%d",&i);

for(int i=1;i<=5;i++){
        cube=i*i*i;
    printf("\nnumber is %d and  cube of the %d is :%d",i,i,cube);
}

}

C Program to Calculate Cube of a Number

C program that calculates and prints the cubes of numbers from 1 to 5.

Let’s go through the code step by step:

  1. The code begins with the inclusion of the standard input-output library stdio.h, which provides functions like scanf and printf for reading input and printing output, respectively.
  2. The main() function is defined, which serves as the entry point of the program. It has a return type of void, indicating that it does not return any value.
  3. Inside the main() function, two variables are declared: i and cube. The i variable will be used to store the input number, while the cube variable will store the calculated cube of each number.
  4. The scanf function is used to read an integer value from the user and store it in the i variable. The %d format specifier is used to indicate that an integer should be read.
  5. Next, a for loop is used to iterate over the numbers from 1 to 5. The loop variable i is initialized to 1, and the loop continues as long as i is less than or equal to 5. After each iteration, i is incremented by 1.
  6. Inside the loop, the cube of the current value of i is calculated by multiplying i by itself twice (i.e., i*i*i), and the result is stored in the cube variable.
  7. The printf function is used to display the current value of i, along with its corresponding cube. The format string "\nnumber is %d and cube of the %d is :%d" specifies the output format, where %d is a placeholder for integers. The first %d is replaced by the current value of i, the second %d is also replaced by the current value of i, and the %d following the colon : is replaced by the value of cube.
  8. Finally, the program execution ends, and control returns to the operating system.

Overall, this program takes an input number from the user, calculates the cube of numbers from 1 to 5, and prints the result for each number.

BEECROWD Problems Solution

2 thoughts on “C Program to Calculate Cube of a Number || practice coding”

Leave a Comment