C++ exercises and solutions: series of numbers


C++ arrays: series of numbers

A two-dimensional array stores values in rows and columns. By using two-dimensional array, write C++ program to display a table of numbers as shown below:


12 34 5 
67  9 10
1112 1314 15
1617 1819 20
2122 2324 25
 

Solution:


#include<iostream>
#include<conio.h>
using namespace std;
int main()
    {
    
     int tArr[5][5];
     int i,j;

     for(i=0;i<5;i++) //assign values to the two-dimensional array
        for(j=0;j<=5;j++){
           if(i==0) tArr[i][j]=j+1; //fill the first row
           if(i>0 && j==0)

              tArr[i][j]=tArr[i-1][4]+1; //fetching the value of the last cell in the previous row
           else
             tArr[i][j]=tArr[i][j-1]+1; //fill subsequent cells
             }    
           
     for(i=0;i<5;i++){ //print the array
        for(j=0;j<5;j++)
            cout<<tArr[i][j]<<"\t";
        cout<<endl;  
       }
     getch();
     return 0;
 
    }


Comments

Kostandin comment

 Kostandin

Can someone Help me please i have this exercise but different

View coments from other users
User inputs an integer N from the range from 1 to 30. Write a program to display the numbers from 1 to N*N in a table with N*N size in the following pattern
Input
3

Output
1 4 7
2 5 8
3 6 9

^^^^^^ if someone can solve it for me please send it to my email vllahukostandin@gmail.com


2018-04-06
Evan F comment

 Evan F

this seems simpler

#include <iostream>

using namespace std;

int main(int argc, const char * argv[]) {

int arr[5][5]={0};

int num=1;

//fill 2D array with integers
for(int i=0;i<5;i++){
for(int j=0;j<5;j++){

arr[i][j]=num;

num++;

}
}

//print array
for(int i=0;i<5;i++){
for(int j=0;j<5;j++){

cout<<arr[i][j]<<"\t";

}
cout<<"\n";
}

return 0;
}


2017-08-30
Mariano comment

 Mariano

I would replace

for(i=0;i<5;i++) //assign values to the two-dimensional array
for(j=0;j<=5;j++){
if(i==0) tArr[i][j]=j+1; //fill the first row
if(i>0 && j==0)

tArr[i][j]=tArr[i-1][4]+1; //fetching the value of the last cell in the previous row
else
tArr[i][j]=tArr[i][j-1]+1; //fill subsequent cells
}

With this:

for(i=0;i<5;i++) //assign values to the two-dimensional array
for(j=0;j<=5;j++){
tArr[i][j]= (j+1) + (i*5);
}


2016-12-07



This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.