简体   繁体   中英

Some values are printing extra times the i (i = 0; i < 10; i++) that i don't want . While using for loop in C

I want an output that prints cube of odd numbers printing in a triangular order up to base number 10, like this. 1 27 27 125 125 125 343 343 343 343 .....

but my program prints 1 27 27 27 125 125 125 125 125 343 343 343 343 343 343 343 .....

it prints extra values.

I tried whatever possible that I learned, and also adding extra for loops...

#include<stdio.h>
#include<conio.h>
void main()
{
    clrscr();
    int a;
    int i,j;
    a=1;
    for(i=0;i<10;i++)
    {

        for(j=0;j<i;j++)
        {
            if(i%2!=0)
            {
                a=i*i*i;
                printf("%d  ",a);
            }

        }
        printf("\n");
     }
    getch();
}

This is what I want...

1 27 27 125 125 125 343 343 343 343

No errors by the compiler, only those extra values printing on the Output screen.

this is ok?

#include<stdio.h>
#include<conio.h>

void main()
{
    int a = 1;

    for (int i = 1; i < 10; i+=2)
    {
        for (int j = 0; j < i - i/2; j++)
        {
                a = i * i * i;
                printf("%d  ", a);
        }
        printf("\n");
    }
    getchar();
}

1 27 27 125 125 125 343 343 343 343 729 729 729 729 729

This solution will give you an easy to understand way to do the printing. The trick consists in using enough variables to update, the number of times you have to print at each line, and the computations to do de cubes:

#include <stdio.h>

int main()
{
    int a = 1, line;
    for (line = 0; line < 10; line++) {
            int cube = a*a*a, item_in_line;
            char *sep = "";  /* no separator at the beginning */
            for (item_in_line = 0; 
                 item_in_line <= line; 
                 item_in_line++) {
                    printf("%s%d", sep, cube);
                    sep = ", ";  /* from now on, we print commas */
            }
            printf("\n");
            a += 2; /* get next number to cube */
    }
}

This will print:

1
27, 27
125, 125, 125
343, 343, 343, 343
729, 729, 729, 729, 729
1331, 1331, 1331, 1331, 1331, 1331
2197, 2197, 2197, 2197, 2197, 2197, 2197
3375, 3375, 3375, 3375, 3375, 3375, 3375, 3375
4913, 4913, 4913, 4913, 4913, 4913, 4913, 4913, 4913
6859, 6859, 6859, 6859, 6859, 6859, 6859, 6859, 6859, 6859

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM