-
Nested While
Hello there :)
I am stuck on how to use nest while!! This is the question:
Write a program that reads in two integers m and n, and prints out an m-by-n rectangle of
asterisks.
(a) Use two nested while loops.
(b) Use two nested for loops.
I did the for loops okay but cannot figure out how the while works.
Code:
#include <stdio.h>
int main()
{
int m, n;
int i=0;
int j=0;
printf("Input value for m and n: \n"); //prompts
scanf("%d %d", &m, &n); //inputs
while(i <= m) // Size of m
{
i++;
printf("*");
}
while(j < n)
{
j++;
printf("*");
}
return 0;
}
What am i doing wrong?
-
It's probably easier to start with just giving height. Then from that, start with one star. For each iteration space--; and stars += 2; since for each level 2 stars is added and one space char at each side disappears. Make a print_stars(int s); and print_space(int s); function.
Then loop that until height. In the loop body:
print_space
print_stars
print_space
update, stars and space vars
-
Ok. I will try to figure out the things you said as actually am new to C programming.
-
The idea is to break down the problem, into smaller problems. You could potentially implement these loops inside your loop instead of using functions but you would end up writing similar code three times instead of once then calling that code.
Edit: in this case with my example twice actually. :) You could however create a generic char printing function that prints a char, x amount of times, example: print_char(char c, int times);
-
I got that working ;)
Code:
#include <stdio.h>
int main()
{
int m, n;
int i=0;
int j=0;
printf("Input value for m(rows) and n(columns): \n"); //prompts
scanf("%d %d", &m, &n); //inputs
j=1; // Initialize to 1
while(j <= m) // Size of m
{
i=1;
while(i<=n)
{
printf("*");
i++;
}
printf("\n");
j++;
}
return 0;
}