I’m trying to create an output of sequential asterisks using for-loops. The idea is to use inputs by the user to determine the number of rows and the increase of asterisks between each row. I can’t make the program print asterisks beyond the first row and when I have been able to it’s been the same amount of asterisks.
What am I doing wrong? I know there’s some other issues, I’d like to try them on on my own so my question is specifically about the output.
Only one row:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int arg1, arg2, x, y, z;
scanf("%d, %d", &arg1, &arg2);
arg1 = atoi(argv[1]);
z = arg2 = atoi(argv[2]);
x = 0;
if (argc < 2 || argc > 3)
{
printf("Wrong number of arguments, input 2 arguments.n");
}
else
{
for (y = 1; y <= arg1; y ++)
{
for (; arg2 > 0; arg2 --)
{
printf("*");
}
arg2 = arg2 + arg2;
printf("n");
}
printf("Total: %dn", x);
return 0;
}
}
ubuntu@lab1:~$ gcc p4.c -o p4
ubuntu@lab1:~$ ./p4 4 5
*****
Total: 0
ubuntu@lab1:~$
Intended example output:
$ gcc p4.c
$ ./a.out 3 2
**
****
******
Totalt: 12
$ ./a.out 0 25
Totalt: 0
$ ./a.out 4 4
****
********
************
****************
Totalt: 40
$ ./a.out
Usage: ./a.out rows growth
$
2
Answers
For starters this if statement
must precede these statements
that must be moved into the else part.
Otherwise the program can invoke undefined behavior.
And moreover the condition is incorrect. It must look at least like
The variable x is not changed within the program. So its output does not make a sense
After the inner for loop
the variable
arg2
is equal to0
.So this statement
keeps the value of
arg2
equal to0
.The program can look for example the following way
If to pass to the program the values
4
and5
then the program output will look likeWithin this for loop
the variable
j
declared as having the typelong long int
instead of justint
because the prodxct ofn * m
can be a big number that can not fit in an object of the typeint
.Have a look at this:
Output