Give an algorithm that given natural numbers a and b as inpu

Give an algorithm that, given natural numbers a and b as input, prints out all ordered pairs in {1, 2, ..., a} x {1, 2, ..., b}. Example: if your function takes as input a = 3 and b = 2, it should print \"(1, 1), (1, 2), (2, 1), (2, 2), (3, 1), (3, 2).\" (don\'t worry about minor details such as printing the parentheses and commas; just worry about getting the right numbers in the right order).

Solution

Algorithm:

1.Start the method,let say printPair(int a,int b)
2.Define 2 arrays of size a and b,let say arrayA[a] and arrayB[b] respectively
3.Fill the elements of arrayA[a] from 1 to a
4.Fill the elements of arrayB[b] from 1 to b
5.Use nested for loops
1.Outer loop from i=1 to a
2.Inner loop from j=1 to b
3.Print (arrayA[i],arrayB[j])
6.end of the method

Implementation of the Algorithm in c++,just for the refrence:

//start of the code,this code has been tested on gcc compiler
#include <iostream>

using namespace std;
void printPair(int a,int b){ //method printPair definition
int arrayA[a],arrayB[b]; //two array declaration
for(int i=1;i<=a;i++) //fill the elements of arrayA
arrayA[i]=i;
for(int i=1;i<=b;i++) //fill the elements of arrayB
arrayB[i]=i;
  
for(int i=1;i<=a;i++) //nested loops,outer loop
{
for(int j=1;j<=b;j++) //inner loop
cout<<\"(\"<<arrayA[i]<<\",\"<<arrayB[j]<<\")\"<<\" ,\"; //printing of pairs
}

}

//end of printPair method

int main() //main function
{
  
printPair(3,2); //calling printPair function with a=3 and b=2
  
return 0;
}

//end of code

********OUTPUT********
  
(1,1) ,(1,2) ,(2,1) ,(2,2) ,(3,1) ,(3,2)

********OUTPUT********

Please let me know in case of any doubt,Thanks.

 Give an algorithm that, given natural numbers a and b as input, prints out all ordered pairs in {1, 2, ..., a} x {1, 2, ..., b}. Example: if your function take

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site