C++ program to print a hollow square shape using for loops, if else and asterisks

C++ program to print a hollow square shape using for loops, if else and asterisks
Di Posting Oleh : Simple Learning
Kategori : C++ shapes hollow square cplusplus square shape in c++ square shape in c++ using for loop

Brief Explanation of Code:
  • Program takes input form user one is height and other is width of square and print respective size of hollow square on console
  • There is one main for loop in a program which runs equal to height of square. Other 3 loops runs for width in side main loop
  • There is one if , else if and else statement in the program each contain a for
C++ Code
Scroll Down to See Image View
  1. #include<iostream>
  2. using namespace std;
  3. main()
  4. {
  5.     int squareHeight, squareWidth;
  6.     cout<< "Enter Height:  ";
  7.     cin>>  squareHeight;
  8.     cout<< "Enter Widht:   ";
  9.     cin>>  squareWidth;
  10.   for(int width=1; width<=squareHeight; width++)
  11.     {
  12.    if(width <= 1)
  13.    for(int width=1; width<=squareWidth; width++)
  14.             {
  15.                 cout<< "*";
  16.             }
  17.         else if(width<squareHeight)
  18.         {
  19.             cout<< endl;
  20. for(int width2=1; width2<=squareWidth; width2++)
  21.       {
  22.       if(width2==1 || width2==squareWidth)
  23.                     cout<< "*";
  24.                 else
  25.                     cout<< " ";
  26.             } //end of for  variable width2
  27.         }// end of else if
  28.         else
  29.         {
  30.             cout<< endl;
  31. for(int width3=1; width3<=squareWidth; width3++)
  32.    {
  33.                 cout<<"*";
  34.             }//end of for having variable width3
  35.         }// end of else
  36.     }// end of first for loop
  37. }// end of main function
 Image View of Code: (click on images for large view)
square shape in c++ using for loop c++ code
square shape c++ code
square shape in c++ using for loop c++ code


 Sample Outputs:(click on images to view large)
sample output square shape in c++ using for loop c++ code
sample output square shape in c++ using for loop c++ code


With Different Input

sample output square shape in c++ using for loop c++ code

For more shape Programs Visit Here
C++ Shape Programs

0 Response to "C++ program to print a hollow square shape using for loops, if else and asterisks"

Post a Comment