Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C# Multiplication Table logic

I’m making a c# program that shows the multiplication table, by using my code I can print only complete table, how can I print random table as below.

my code bit:

using System;  
public class Exer
{  
    public static void Main() 
{
   int j,n;
   
    Console.Write("\n\n");
    Console.Write("Display the multiplication table:\n");
    Console.Write("-----------------------------------");
    Console.Write("\n\n");   

   Console.Write("Input the number (Table to be calculated) : ");
   n= Convert.ToInt32(Console.ReadLine());   
   Console.Write("\n");
   for(j=1;j<=10;j++)
   {
     Console.Write("{0} X {1} = {2} \n",n,j,n*j);
   }
  }
}

Expected Output:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

1 x 2 = 2
2 x 2 = 4
3 x 2 = 6
1 x 4 = 4
2 x 4 = 8
3 x 4 = 12
1 x 6 = 6
2 x 6 = 12
3 x 6 = 18
1 x 8 = 8
2 x 8 = 16
3 x 8 = 24
1 x 10 = 10
2 x 10 = 20
3 x 10 = 30

enter image description here

>Solution :

The tables in your picture are NOT random, though. There is a definite pattern. The function, DisplayMath(), is receiving an integer parameter; 3, 4, and 5 in the picture.

The output in the pictures is most likely produced by two NESTED for loops.

The integer parameter is controlling the INNER for loop, which goes from 1 to the parameter, incrementing by 1.

The OUTER loop goes from 2 to 10, incrementing by 2.

Possible code:

public static void Main() {
    DisplayMath(4);
}

public static void DisplayMath(int x) {
    for(int y=2; y<=10; y=y+2) {
        for(int z=1; z<=x; z++) {
            Console.WriteLine("{0} X {1} = {2}",z,y,z*y);
        }
    }
}

Output:

1 X 2 = 2
2 X 2 = 4
3 X 2 = 6
4 X 2 = 8
1 X 4 = 4
2 X 4 = 8
3 X 4 = 12
4 X 4 = 16
1 X 6 = 6
2 X 6 = 12
3 X 6 = 18
4 X 6 = 24
1 X 8 = 8
2 X 8 = 16
3 X 8 = 24
4 X 8 = 32
1 X 10 = 10
2 X 10 = 20
3 X 10 = 30
4 X 10 = 40
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading