"The best way to cheer yourself up is to try to cheer somebody else up." Mark Twain

Sunday, March 28, 2010

Write a function int ALTERSUM( int B[][5] , int N, int M) in c++ to find and return the sum of elements from all alternate elements of a two-dimensional array starting from B[0][0].

Hint: If the following is the content of the array

4 5 1
2 8 7
9 6 3
The function should add elements B[0][0], B[0][2], B[1][1], B[2][0], B[2][2]

CBSE 2010


#include<iostream.h>
#include<conio.h>

#define x 10
#define y 5

int ALTERSUM(int B[][5], int M, int N)
{
int flag = 0, sum = 0;
for(int i = 0 ; i < M ; i++)
for(int j = 0 ; j < N ; j++)
{
if(flag == 0)
{ 
   sum = sum + B[i][j];
   flag = 1;
}
else
   flag = 0;
}

return sum;
}

void main()
{
int arr[x][y], r, c, i , j;

cout << "\n How many rows(<10)? " ;
cin >> r;

cout << "\n How many cols(< 5)?";
cin >> c;
/* Input elements */
for( i = 0 ; i < r ; i++)
for(j = 0 ; j< c ; j++)
{
cout << "\n Enter elements :";
cin >> arr[i][j];
}

/* display matrix */
for(i = 0; i < r  ; i++)
for(j = 0; j < c ; j ++)
    cout << arr[i][j] << " ";
cout<< endl;

int sum = ALTERSUM(arr, r, c);
cout << "\n The Sum of alternate elements = " << sum;

getch();
}


Saturday, March 27, 2010

Write a function in C++ to print the product of each column of a two dimensional integer array passed as the argument of the function.

                                                    CBSE 2008

Explain : If the two dimensional array contains

         1     2     4
         3     5     6
         4     3     2
         2     1     5

The output should appear as :

Product of Column 1 = 24
Product of Column 2 = 30
Product of Column 3 = 240
                                                                                             
#include<iostream.h>
#include<conio.h>
#define r 10
# define c 10
void ProCol(int a[][], int m , int n) 
// n represents column
// m represents row
{
int pro[n], i, j ;
for(i = 0; i  <  n ; i++)
{
pro[i] = 1;
for(j = 0 ; j  <  m ; j ++)
{
pro[i] = pro[i] * a[j][i];
}
cout << "\n Product of Column 1 : " <<  pro[i];
}
}

void main()
{
int arr[r][c];

int row, col, i, j;

// Input dimension ~
cout <<  "\n Enter row & Column :";
cin >>  row >>  col ;

// Input elements for the array ~
for( i = 0; i <  row ; i++)
for ( j = 0 ; j <  col ; j++)
{
cout << "\n Enter the element for position : "   << i+1 << " , " <<  j+1 ;
cin >>  arr[i][j];
}

// Display the array
for( i = 0;  i < row ; i++ )
{
for( j =0 ; j < col ; j ++)
    cout   <<  arr[i][j]   <<  "  ";
cout  <<   endl;
}

// Calling the function
ProCol(arr, row, col);

getch();

}
C makes it easy to shoot yourself in the foot; C++ makes it harder, but when you do it blows your whole leg off.
Now Playing: Ballade Pour Adeline

About Me

My photo
I m an IT lecturer of a college. I love social-work. I want to do something beneficial for society before dying , that can promote our society, to some extent.