Home > front end >  How do I print x number of integers per line and only display the odd numbers in those lines?
How do I print x number of integers per line and only display the odd numbers in those lines?

Time:12-19

So far I can display the correct amount of integers per line, but I need to show only the odd numbers in the sequence. This is what I have so far: Edited code:

 for ( counter = 1; counter <= max;   counter)
                    {
                       
                        if( counter % 2 != 0 )  
                        {    
                            Console.Write(counter "");

                           int printcounter = counter;
                           
                     
                            if (printcounter % 4 == 0)
                                {
                                  Console.WriteLine();
                                  }
                                else
                                {
                                    Console.Write('\t');
                                }
                            printcounter  ;
                           
                        }
                        Console.WriteLine();
                    }

The output I'm getting

1

3

5

7

9

The output I'm trying to get:

1 3 5 7

9 11 13 15

CodePudding user response:

Declare your printCounter variable BEFORE the loop so that it persists and correctly tracks the number of things you've printed:

  public static void Main (string[] args) { 
    int max = 21;
    int printCounter = 0;
    for (int counter = 1; counter <= max; counter  )
    {        
        if(counter % 2 != 0 )  
        {    
            Console.Write(counter   "\t");
            printCounter  ;
            if (printCounter % 4 == 0)
            {
              Console.WriteLine();
            }
        }
    }
  }

CodePudding user response:

You almost got it… try it like below…

int max = 100;
int printCount = 0;
for (int counter = 1; counter <= max;   counter) {
  if (counter % 2 != 0) {
    Console.Write(counter   " ");
    if (  printCount % 4 == 0) {
      Console.WriteLine("");
    }
  }
}
Console.ReadKey();

Note: the line…

if (  printCount % 4 == 0) {

is shorthand for ….

printCount  ;
if (printCount % 4 == 0) {

You only want to increment printCount when you print a number.

CodePudding user response:

You can get the same result with this code. Very short and clear.

for (int counter = 1; counter <= max; counter  )
{
    if (counter % 2 != 0)
        Console.WriteLine(counter "\n");
}

  •  Tags:  
  • c#
  • Related