Hi everyone,
I'm struggling with the following problem and would appreciate your help very much:
As I don't know how to use multidimensional arrays (matrices), this problem should be solved using only loops, ie for(), while() loops etc. So I tried and tried, but all I managed up until now is to "draw" only the first segment of the zigzag line:Write a program that reads in two natural numbers, m and n (m<n) and prints a zigzag graph composed of a series of two asterisks (**). The graph should start at the upper-left corner, and descend into line below so that asterisks in that line would be indented by two places, and when the graph reaches the bottom (m-th row), it should go upwards in the same fashion, and so on, until the n-th "column" is filled.
For example, if the input is m=3 and n=21, the output should be:
or, if m=7 and n=33, the output should be:Code:** ** ** ** ** ** ** ** ** ** *
Code:** ** ** ** ** ** ** ** ** ** ** ** ** * ** ** **
All this program does is, for example if m=6 and n=24, it prints only the first segment:Code:#include <stdio.h> int main(void){ unsigned int m, n, i, j; printf("Enter m:"); scanf("%d",&m); printf("Enter n:"); scanf("%d",&n); if(m>=n) {printf("n should be strictly larger than m!\n"); return;} for(i=1;i<=m;i++){ for(j=1;j<=n;j++){ if(j%2==0 && j==2*i) printf("*"); if(j%2!=0 && j==((2*i)-1)) printf("*"); else printf(" "); } printf("\n");} return 0;}
which is not nearly the desired solution. Then I tried calculating the length of "gaps" between two asterisks in an arbitrary row, for example in the case when m=5 and n=21,Code:** ** ** ** ** **
and ended up with the formula sp=4*(m-i)-2, where sp is the number of spaces between two **'s in i-th row, but that didn't seem to be too useful...Code:i=1 **<-----14----->** i=2 **<---10--->** ** i=3 **<--6->** * i=4 **-2** i=5 **
(E.g. in the above case, number of gaps between ** and ** in the second row, if total number of rows=5, is 4*(5-2)-2=10)
Thank you very much for taking your time to read this, and if you have any idea how to solve this problem, I would be deeply grateful.