Home > Software engineering >  Numbers are printed too far down
Numbers are printed too far down

Time:10-17

i want to print the square numbers next to the numbers from 1 - 10. I used \t but it looks like \t\v.

printf("n \t\t n*n \t\t s(n) \t\t q(n)");
printf("\n");
int i;
i = 0;

while(i<=10)
{
printf("%d\n",i);
i  ;
}

for(i=1; i<=10;i  )
{
printf("\n\t\t%d", i*i);
}

Can't find a solution and i just started coding in C last week.

n        n*n         s(n)        q(n)
1
2
3        
4        1
5        4
6        9
7        16
8        25
9        36
10       49
         64
         81
         100

CodePudding user response:

Let's logically follow the code you have provided.

printf("n \t\t n*n \t\t s(n) \t\t q(n)");
printf("\n");

Will print

n                n*n             s(n)            q(n)

Now, after the first while loop you will print each number from i to i=10 in a new line, leading to:

0
1
2
...
10

This makes sense. Lastly, you are using another for loop with another printf() call to print n*n, again, in a new line for each entry.

            1
            4
            9
            ...
            100

You have to notice that printf() will always print ONE line and as soon as you are jumping to the next line with \n there is no way of going back to the previously printed line (at least when printing to the console).

The easiest fix would be to only use one for loop that prints and calculates all of the necessary values for a specific i. The print statement could look similar to:

printf("%d \t\t %d \t\t %d \t\t %d", value1, value2, value3, value4);

CodePudding user response:

#include <stdio.h>

int main()

{
 
   for(int i=1;i<=10;i  )
 
   printf("%d\t%d\n",i,i*i);

   return 0;

}

CodePudding user response:

#include <stdio.h>

int main() {
printf("n \t\t n*n \t\t s(n) \t\t q(n)");
printf("\n");
int i;
i = 0;

while(i<=10)
{
    printf("%d \t\t %d \n",i,i*i);
    i  ;
 }
 return 0;
 }

I hope this would be helpful to you..

  • Related