Output in a for loop

How do you arrange the outputs in a for loop?

Page 1 of 1

3 Replies - 2061 Views - Last Post: 01 October 2007 - 06:54 AM Rate Topic: -----

#1 Strafas   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 01-October 07

Output in a for loop

Post icon  Posted 01 October 2007 - 06:25 AM

Hi
How do you arrange the output for a multiplication table so that it will appear in a neater form with defined columns like this

1 2 3 4 5
2 4 6 8 10

instead of

1 2 3 4 5 6
2 4 6 8 10 12
3 6 9 12 15 18

I've seen some post about clout but i can't seem to get it to work. And i have no idea if i should put it in the for loop
or outside the for loop.

here's my code

#include <stdio.h>
#include <iomanip>


int main()
{
  int i,j;
  
for(i=1; i<=12; i++)

{
	printf(" %d",i);

		for(j=2; j<=12; j++)
			printf(" %d",j*i);
				printf("\n");
						
}

	  fflush(stdin);
	  printf("\n\n\nPress the ENTER key to continue.");
	  getchar();
  
  return 0;
}




Is This A Good Question/Topic? 0
  • +

Replies To: Output in a for loop

#2 quim   User is offline

  • D.I.C Head
  • member icon

Reputation: 18
  • View blog
  • Posts: 182
  • Joined: 11-December 05

Re: Output in a for loop

Posted 01 October 2007 - 06:42 AM

you can use this function
// create a tabular output setw()
cout << setw(5) << " ";


the setw() function is defined in the <iomanip> header file i have only tried it on C++, so i am not sure if it works the same way on C.
also by default it will right justify your out put.
to left justify:
//in C++ it is in the <iostream>
// probably in C it is in <stdio.h>
cout << left << setw(6) << " ";

Was This Post Helpful? 0
  • +
  • -

#3 no2pencil   User is offline

  • Professor Snuggly Pants
  • member icon

Reputation: 6703
  • View blog
  • Posts: 31,084
  • Joined: 10-May 07

Re: Output in a for loop

Posted 01 October 2007 - 06:45 AM

  i2=0;							  // init our counter
  for(j=2; j<=12; j++) {
	printf(" %d",j*i);
	if(i2=5) {				  // check our counter
	  printf("\n");		   // produce the results
	  i2=0;			   // re-init the counter
	}
	i++;					  // inc the counter
  }								// until the end of the for loop



I would add an if to check the value of the output, to add the extra space if needed.

This post has been edited by no2pencil: 01 October 2007 - 06:51 AM

Was This Post Helpful? 0
  • +
  • -

#4 Strafas   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 01-October 07

Re: Output in a for loop

Posted 01 October 2007 - 06:54 AM

Thank you :D
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1