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:
- The code begins with the inclusion of the standard input-output library
stdio.h
, which provides functions likescanf
andprintf
for reading input and printing output, respectively. - The
main()
function is defined, which serves as the entry point of the program. It has a return type ofvoid
, indicating that it does not return any value. - Inside the
main()
function, two variables are declared:i
andcube
. Thei
variable will be used to store the input number, while thecube
variable will store the calculated cube of each number. - The
scanf
function is used to read an integer value from the user and store it in thei
variable. The%d
format specifier is used to indicate that an integer should be read. - Next, a
for
loop is used to iterate over the numbers from 1 to 5. The loop variablei
is initialized to 1, and the loop continues as long asi
is less than or equal to 5. After each iteration,i
is incremented by 1. - Inside the loop, the cube of the current value of
i
is calculated by multiplyingi
by itself twice (i.e.,i*i*i
), and the result is stored in thecube
variable. - The
printf
function is used to display the current value ofi
, 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 ofi
, the second%d
is also replaced by the current value ofi
, and the%d
following the colon:
is replaced by the value ofcube
. - 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.
Your article helped me a lot, is there any more related content? Thanks!
click here and earn money https://www.binance.com/activity/referral-entry/CPA/together-v4?hl=en&ref=CPA_00JRQQICQ6&utm_source=fee_page