Finding Square & Cube of the Given Numbers Using For Loop


Explanation

This program is used to find the square and cube of a number entered by the user. The program accepts one number and calculates its square by multiplying the number two times and calculates its cube by multiplying the number three times.

  • Step 1: Declare an integer variable no.
  • Step 2: Accept a number from the user.
  • Step 3: Calculate the square using no * no.
  • Step 4: Calculate the cube using no * no * no.
  • Step 5: Display the square and cube values.

Example Program



#include <stdio.h>
#include <conio.h>


main()
{


    int no;


    clrscr();


    printf("\n Enter any no");

    scanf("%d", &no);


    printf("\n Square is %d * %d = %d", no, no, no * no);


    printf("\n Cube is %d * %d * %d = %d", no, no, no, no * no * no);


    getch();


}


Output

Enter any no 5

Square is 5 * 5 = 25

Cube is 5 * 5 * 5 = 125

Practice Exercises

Task 1: Write a C program using the for loop to accept 5 numbers from the user and display the square and cube of each number.

Goal: Learn how to use the for loop and arithmetic operators to calculate square and cube values of multiple numbers.

💡 Hint: Use variables k and no. Run the loop from 1 to 5. Calculate square using no * no and cube using no * no * no.
💡 Show Solution


#include <stdio.h>
#include <conio.h>


main()

{


    int k, no;


    clrscr();


    for
    (k = 1; k <= 5; k = k + 1)

    {


        printf("\n Enter any no");


        scanf("%d", &no);


        printf("\n Square is %d * %d = %d", no, no, no * no);


        printf("\n Cube is %d * %d * %d = %d", no, no, no, no * no * no);


    }


    getch();


}


Output
Enter any no 2

Square is 2 * 2 = 4

Cube is 2 * 2 * 2 = 8

Enter any no 3

Square is 3 * 3 = 9

Cube is 3 * 3 * 3 = 27

Enter any no 5

Square is 5 * 5 = 25

Cube is 5 * 5 * 5 = 125

Enter any no 7

Square is 7 * 7 = 49

Cube is 7 * 7 * 7 = 343

Enter any no 10

Square is 10 * 10 = 100

Cube is 10 * 10 * 10 = 1000
Explanation: The program uses a for loop to accept 5 numbers from the user. For each number, it calculates the square by multiplying the number two times and calculates the cube by multiplying the number three times. The results are displayed after each input.