hi,
there, im doing a small program and the output should be as below

@
**
@@@
****
@@@@@

Ive coded it, but it gives different answers..please help.the code is as below.

#include <stdio.h>
int main()
{

    int i,j,k,m,a,y;
    for(k=1;k<=3;k++){
        for(j=1;j<=5;j++){
            for(i=1;i<=j;i++){
                printf("@");
            }
            printf("\n");

            for(i=1;i<=j+1;i+=1){
                printf("*");
            }

            printf("\n");
        }
    }
    return 0;
}

Recommended Answers

All 3 Replies

first off try to use code tags for now on

second, ur code is kind of confusing heres a loop that will work and read a little better, i assume you can use an if statement.

for(i = 1; i <= 5; i++){
for(j = i; j > 0; j--){
if( ( i % 2 ) = 0 ) printf("*"); // if i is even print *
else printf("@");// if not print @
}
printf("\n");
}

Your program runs fine. Just make this small change and it will run.

In your program it is:

for(k=1;k<=3;k++){
for(j=1;j<=5;j++){
for(i=1;i<=j;i++){

Change this thing as :

for(k=1;k<=3;k++){
for(j=1;j<=5;j+=2){   //Only change required...
for(i=1;i<=j;i++){

In your code once a loop is finished the next set of runs for the innermost first loop is equal to the previous loop run value of innermost second loop. Due to this it was printing same number of '@' and '*'.By this small change it will run fine.

int i, j, k, m, a, y;
            
            for (i = 1; i <= 5; i++)
            {
                if (i % 2 != 0)
                {
                    for (j = 1; j <= i; j++)
                    {
                        printf("@");
                    }
                    printf("\n");
                }
                else
                {
                    for (k = 1; k <= i; k++)
                    {
                        printf("*");
                    }
                    printf("\n");
                }
            }
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.