Lesson 19: C Programming Examples

11 comments

I’ve based this lesson on a single program example. This part of C programming tutorial has dual purpose: firstly to teach you how to apply previously learned C/C++ knowledge, second: to show you how pointers, arrays, functions and matrixes can be combined together in one single program.


Example:

Maximal number of rows and columns matrix can have is predefined. Write your own main program which reads given number of matrix’s rows and columns, and additionally reads matrix’s given elements. Main program prints:


  1. Matrix’s elements sum (calls upon a function that calculates elements sum)

  2. Maximal value in every row of a matrix (calls upon a function that finds the biggest element in a flow)



Matrix mat is declared in a way of two dimensional array (2D array):


float mat[MAXROW][MAXCOL];

Variables nrRow and nrCol store matrix’s dimensions provided by user. The image below shows you this in a visual way. Click on the image to enlarge it.





Memory of a computer allocates MAXROW * MAXCOL * sizeof(float) byte. Matrix’s rows follow one after another, in a way where every next row is placed right after the previous one; and so on. Picture below describes this perfectly. Click on the image to enlarge it.





Generally speaking, for mat[i][j] – number of elements from the beginning of an array is: i * MAXCOL + j


#include <stdio.h>
#define MAXROW 100
#define MAXCOL 100


float max( int len, float *p ) {
// OR: float max( int len, float p[] )

float res;
int i;

printf("\nIn function max :");

printf("\nRow’s beginning address
in memory : %ld", p);

res = p[0];
for( i=1; i<len; i++ )
if( p[i] > res )
res = p[i];
return res;
}


float sumEl(int nrRow,int nrCol,
int maxCol,float *mat) {


int i, j;

float sum;

printf("\nIn function sumEl:");
printf("\nMatrix’s beginning address
in memory: %ld", mat);
printf("\nBegin. of 2nd row’s addr.
in mem.: %ld", &mat[maxCol]);

printf("\nBegin. of 3rd row’s addr.
in mem.: %ld", &mat[2* maxCol]);


sum = 0.0;
for( i=0; i<nrRow; i++ )
for( j=0; j<nrCol; j++ )
sum += mat[i*maxCol + j];
// or: sum += *(mat + i*maxCol + j)

return sum;
}


int main(void) {

int row, col, i, j;
float add, maxRow, mat[MAXROW][MAXCOL];

printf("\nInput nr. of rows and columns:");
scanf("%d %d", &row, &col );

printf("\nIn function main");
printf("\nMatrix’s beginning address
in memory: %ld", mat);

printf("\nBegin. of 2nd row’s
addr.: %ld\n\n", &mat[1][0]);

printf("\nBegin. of 3rd row’s
addr.: %ld\n\n", &mat[2][0]);

for( i=0; i<row; i++ )
for( j=0; j<col; j++ ) {
printf("Input element[%d,%d]:",i,j);
scanf("%f", &mat[i][j] );
}



//calculates elements sum in matrix

add=sumEl(row,col,MAXCOL,(float *) mat);
printf("\n\nSum of matrix
elements is %f", add );




//prints maximal value of every mat. row

for(i=0;i<row;i++) {
maxRow = max(col, &mat[i][0]);
// or: max(col, mat+i*MAXCOL)
printf("\nBiggest element in
row %d is %f\n",i,maxRow);

}
}




Example of program’s execution:


Input nr. of rows and columns: 3 2

In function main :

Matrix’s beginning address in memory : 1205032
Begin. of 2nd row’s addr. : 1205432
Begin. of 3rd row’s addr. : 1205832


3rd:


1205432 = 125032 + 1 * MAXCOL * sizeof(float)
= 125032 + 400;
1205832 = 125032 + 2 * MAXCOL * sizeof(float)
= 125032 + 800;




Input element [0,0]: 2
Input element [0,1]: 3
Input element [1,0]: 4
Input element [1,1]: 3
Input element [2,0]: 1
Input element [2,1]: 5



In function sumEl:
Matrix’s beginning address in memory: 1205032
Begin. of 2nd row’s addr. in mem.: 1205432
Begin. of 3rd row’s addr. in mem.: 1205832


Sum of matrix elements is 18.000000
In function max:
Row’s beginning address in memory: 1205032
Biggest element in row 0 is 3.000000



In function max:
Row’s beginning address in memory: 1205432
Biggest element in row 1 is 4.000000


In function max:
Row’s beginning address in memory: 1205832
Biggest element in row 2 is 5.000000





Example:

Write your own C function which returns flow of matrix row’s maximal values.



void maxFlow(float *mat,int nrRow,int nrCol,
int maxCol,float *flow) {


//OR: void maxFlow(float mat[], int nrRow,
int nrCol,int maxCol,float flow[])


int i, j;
for (i = 0; i < nrRow; i++) {
flow[i] = mat[i * maxCol];
for(j = 1; j < nrCol; j++)
if (mat[i*maxCol+j] > flow[i])
flow[i]=mat[i*maxCol+j];
}
}









Continue reading full article...

Lesson 18: Pointers and Stacks in C

3 comments

Today's lesson goes more into details about pointers and their usage as function's arguments. Additional tutorial about stacks in C and C++ is provided. Be sure to read this lesson carefully in order to understand it, since pointers are most important part of C programming language.



Transferring Argument’s Address into a Function (
call by reference)


Write your own function that changes polar coordinates into Cartesian coordinates, and show how this function is called upon from main program.


#include <math.h>

void cart(float r, float fi, float *x, float *y) {

*x = r*cos(fi); // x address:1244956,value:1245052
//*x address:1245052,value:1.755165

*y = r*sin(fi); // y address:1244960,value:1245048
//*y address:1245048,value:0.958851

}


Main program slice:

float x, y;            // x address:1245052,value:?
// y address:1245048,value:?

float fi = 0.5, r = 2; //fi address:1245044,value:0.5
// r address:1245040,value:2

cart(r, fi, &x, &y);

printf("x=%f y=%f",x,y);

// x address:1245052, value:1.755165
// y address:1245048, value:0.958851




Question
:


What would happen if the function looked like this?


void cart(float r, float fi, float *x, float *y) {

x = 10000;
*x = r * sin(fi);
*y = r * cos(fi);

}



Important:

Function is able to return single value through its “return” order. In order to return more values (in this case x & y), we can return them through arguments (Call by Reference).




Example
:


Write your own function that returns numerator and denominator of a fraction. This fraction is a sum of two fractions, whose two numerators and two denominators are given by user. Function also shortens the fraction if possible, before returning values. Augends numerators and denominators are integers.

(Fraction example: 5/9, Numerator: 5, Denominator: 9)


void addFractions(int nrator1,int denom1,
int nrator2,int denom2,
int *nratorSum,int *denomSum) {


int min, i;

*nratorSum = nrator1*denom2+denom1*nrator2;
*denomSum = denom1*denom2;

min=(*nratorSum<*denomSum) ? *nratorSum : *denomSum;

//testing if numerator and denominator
//are multiples:

if((*nratorSum % min == 0)&&(*denomSum % min==0)){
*nratorSum /= min;
*denomSum /= min;

} else {

//tests if numerator and denominator are

//dividable with same number

i = min / 2;
while ( i >= 2) {

if ((*nratorSum%i == 0)&&(*denomSum%i == 0))

*nratorSum /= i;
*denomSum /= i;

--i;
}
}
}


Main program’s slice (calls function addFractions):

int nrator1, denom1, nrator2, denom2,
int nratorSum, denomSum;

...

addFractions(nrator1, denom1, nrator2,
denom2, &nratorSum, &denomSum);




Function that finds biggest element in real number’s array

Why is flow’s length “length” transferred as function’s argument?

float max(int length, float *p) {

// OR: float max(int length, float p[]) {

float res; int i;

res = p[0];
for (i = 1; i < length; i++)
if (p[i] > res)
res = p[i];
return res;

}

Same problem - solved using pointer’s arithmetic:

float max(int length, float *p) {

float res;
int i;


res = *p;
p++;
for (i = 1; i < length; i++, p++)
if (*p > res)
res = *p;
return res;

}




Important:

Pointer p stores address of the first array element. However, if we shift pointer p inside the function, address of the first array’s element won’t be changed, neither will influent our main program (that calls the function).




Example:

Exam’s results are transferred into a function in a way of array composed of integers (integers represent grades). This array (flow), is consisted of grades 1, 2, 3, 4 and 5. Number of array’s elements is nrGrades. Write your own function that returns most common grade.


int commonGrade(int *flow, int nrGrades) {

int grade[5] = {0}, commonGrade = 0, i;


for(i = 0; i < nrGrades; i++){

grade[flow[i] -1]++;


}


for(i = 1; i < 5; i++){

if(grade[i] > grade[commonGrade]) {


commonGrade = i;

}
}

return commonGrade + 1;
}




Example:

Write your own function that shifts array p (given, integer type) for a number of places. Array p is consisted of N number of elements, and will be shifted left for negative value, or shifted right for positive value (adjustment < N). Empty places are filled with zeroes.


Example of shifting:

shift = 2 and array[10 40 50 60 12]:
Before shifting: [10 40 50 60 12]

Shifted array: [ 0 0 10 40 50]



Solution:

void shiftArray(int *p, int N, int shift) {

int i;


// if shifting right


if (shift > 0 && shift < N) {


for (i = N - 1 - shift; i >= 0; i --)

p[i + shift] = p[i];

for (i = shift - 1; i >= 0; i --)

p[i] = 0;
}


// if shifting left

else if (shift < 0 && -shift < N) {

shift = -shift;

for (i = 0; i <= N - 1 - shift; i++)
p[i] = p[i + shift];
for (i = N - shift; i < N; i++)
p[i] = 0;
}
}




Stack Data Storage with Function call


Every new element is stored on top of the stack. However, compilers often tend to assign
lower address to stack’s top, then to stack’s bottom. This results data being stored downwards (from bottom of the stack to lower memory addresses).



Following data is stored to a stack (from higher addresses to lower ones):

- function’s arguments (highest address is assigned to ultimately-right
placed argument)

- returning address
- local variables (highest address is assigned to first declared variable)




Important:

While transferring data to a stack, frames of the stack will be ignored in this tutorial (processor registers). However, some compilers also tend to store these to a stack.



For how many bytes does the stack maximally increase, while executing this block:

...
...
y = f1(10);
...


if the following functions are defined:

long f2(float a, float b) {

return a + b;


}



int f1(char x) {

int i = 4, y;
y = x + 1;

return i * f2(x, y);

}



f1 call: f2 call: STACK’S TOP
(lower addresses)
returning address 2
10 (float) ^
11 (float) / \
11 (int) 11 (int) / \
4 (int) 4 (int) / __ \
returning address 1 returning address 1
10 (char) 10 (char) STACK’S BOTTOM
(higher addresses)






Returning address is data type
long.

By calling function f2, stack has increased to its maximal size:

    
sizeof(char)
+ sizeof(returning address 1)
+ 2 * sizeof(int)
+ 2 * sizeof(float)
+ sizeof(returning address 2)

--------------

= 25 byte















Technorati Tags:
, , , , , ,


Continue reading full article...

Lesson 17: Pointers in C

1 comments

After three days of waiting, C++ Maniac brings you another interesting lesson. This one is labeled no. 17, and I think moment has come when I can proudly say we have crossed a half-way of my complete C Tutorial; at least first part of it, “C Programming In General”. This Lesson is about Pointers and their useful implementation in Your future C programs. Let’s start…



Important:

Examples are translated using Microsoft Visual C++ compiler.



Example:

What will be printed after execution of a following program block?

int a = 5; //a address:1245052, value:5


int *b; //a address:1245052, value:5
//b address:1245048, value:?


b = &a; //a address:1245052, value:5
//b address:1245048, value:1245052

*b = 6; //a address:1245052, value:6
//b address:1245048, value:1245052


printf("a = %d *b = %d\n", a, *b);
printf("a = %d b = %ld\n", a, b);
printf("&a = %ld &b = %ld\n", &a, &b);



Result:

a = 6 *b = 6
a = 6 b = 1245052
&a = 1245052 &b = 1245048



Important:

Value that is pointed by variable b is on the same address (b = &a) as the value assigned to variable a.

What would happen if we left out this line: b = &a; ?



Result:

Before assigning value to it, pointer b points to undefined address. This makes it possible for program to store value 6 to an address previously reserved for some other variable or code. This would result in an unexpected behavior or cause an error in program’s execution (because of unauthorized access to memory’s section).



Typical Mistakes:

scanf(“%d", n);
printf(“%d", &n);



Connection between Pointers and Arrays:


Any declared array’s name can also be used as a pointer. Any pointer can also be used as an array.


What will be printed as a result of following program block?

int x[] = {0, 1, 2}; //x[0] address:1245044, value:0
//x[1] address:1245048, value:1
//x[2] address:1245052, value:2


printf("&x[0] = %ld x[0] = %d\n", &x[0], x[0]); // 1
printf("&x[1] = %ld x[1] = %d\n", &x[1], x[1]); // 2
printf("&x[2] = %ld x[2] = %d\n", &x[2], x[2]); // 3




Result:

&x[0] = 1245044 x[0] = 0
&x[1] = 1245048 x[1] = 1
&x[2] = 1245052 x[2] = 2



Important:

Printings in an upper block could’ve been substituted with following lines:

printf("x = %ld *x = %d\n", x, *x);                   // 1
printf("(x + 1) = %ld *(x+1) = %d\n", x + 1, *(x+1)); // 2
printf("(x + 2) = %ld *(x+2) = %d\n", x + 2, *(x+2)); // 3


because these following lines are equivalent:

*x      <=>  x[0]     x    <=>  &x[0]
*(x+1) <=> x[1] x+1 <=> &x[1]
*(x+2) <=> x[2] x+2 <=> &x[2]




Array’s name (in upper example: x) represents pointer to null member of an array. Notation x + 1 represents pointer to first member of an array, whose distance from null member is: 1 * sizeof(int). In a same way, x + 2 represents pointer to second member of an array, whose distance from null member is:
2 * sizeof(int)
.




Array’s Name as Pointer’s Constant:


When compiling this program block:

int a[10], b[10];
a = b;

error is reported. Array’s name (a) is representing pointer’s constant in this example, and because of that we aren’t able to modify this pointer’s value.





Connection between Pointers and Array’s:


Assigning array’s address to pointer (which is equivalent to assigning address of first array’s element to pointer) can be executed in two ways:

int *p, a[10];
p = a; // first solution
p = &a[0]; // second solution




Pointer’s Arithmetic:


What will be printed after execution of a following C program block?

int x[] = {1, 2, 3, 4};   //x[0] address:1245040, value:1
//x[1] address:1245044, value:2
//x[2] address:1245048, value:3
//x[3] address:1245052, value:4



int *p = &x[2]; //p address:1245036, value:1245048


int *q = &x[1]; //q address:1245032, value:1245044


int *r = ++q;
//r address:1245028, value:1245048
//q address:1245032, value:1245048



printf("(p + 1) = %d *(p + 1) = %d\n", (p + 1), *(p + 1));
printf("(p - 1) = %d *(p - 1) = %d\n", (p - 1), *(p - 1));
printf("q = %d *q = %d\n", q, *q);
printf("r = %d *r = %d\n", r, *r);



Result:

(p + 1) = 1245052 *(p + 1) = 4
(p - 1) = 1245044 *(p - 1) = 2
q = 1245048 *q = 3
r = 1245048 *r = 3






Technorati Tags:
, , , , , ,

Continue reading full article...

Lesson 16: Functions in C

5 comments

Functions are essential part of code in C and C++ language, so be sure to carefully read this lesson. You’ll notice there’s nothing to be afraid of – they are really easy to understand, and sometimes, can lighten up our program code significantly. In a way, they remind us of our main program. Functions usually return value that we use in our main block, but sometimes they return nothing. Either way, they do their task: like printing on screen or calculating equations. C++ Maniac presents you another interesting tutorial!


Example:


Write your own function that calculates arithmetic middle of three real numbers. Write additional main program that stores given three numbers and calls on your previous function, and then prints calculated arithmetic middle.


#include <stdio.h>

float arit_midd( float a, float b, float c ){


float ar;
ar = (a + b + c) / 3;
return ar; // How many values “return” may return?

}


int main(void) {

float x, y, z, midd;
printf("\nInput three real numbers : ");
scanf("%f %f %f", &x, &y, &z );
midd = arit_midd(x,y,z);
printf("\nArithmetic middle : %f", midd);

}




Example:

What will be printed after execution of a program that calls on a function?


void twotimes(int x) {

printf ("\nF:Argument before change took place %d",x);
x *= 2;
printf ("\nF:Argument after tempering with it %d",x);

}


int main(void) {

int number=10;
printf ("\nM:Number before function-call %d",number);
twotimes(number);
printf("\nM:Number after function-call is %d",number);

}


Result on-screen:

M:Number before function-call 10
F:Argument before change took place 10
F:Argument after tempering with it 20
M:Number after function-call 10



Change inside a function wasn’t saved after execution and return to main program! Why?

int twotimes(int x){

printf ("\nF:Argument before change took place %d",x);
x *= 2;
printf ("\nF:Argument after tempering with it %d",x);
return x;

}


int main(void) {

int number=10;
printf ("\nM:Number before function-call %d",number);
broj = twotimes(number);
printf("\nM:Number after function-call %d",number);

}




Result on-screen:

M:Number before function-call 10
F:Argument before change took place 10
F:Argument after tempering with it 20
M:Number after function-call 20




Example:

Compose a function that calculates value of a sinus func. as sum of n elements. Function’s argument is given in radians. Func. sinus is defined as:






#include <stdio.h>
#include <math.h>



//realization with use of no additional functions


float sinus(float x, int n){

int i, forsign;
float sum, element, fakt, xpot;
sum = 0.0;
xpot = x;
fakt = 1.0;
forsign = 1;

for( i=1; i<=n; i++ ) {

element = forsign * xpot / fakt;
forsign *= -1;
xpot *= x*x;
fakt *= (2*i) * (2*i+1);
sum += element;

}

return sum;

}


//realization with help of additional functions


long fakt( int n ){

int i;
long f=1;
for( i=1; i<=n; i++ ) {
f *= i; }
return f;

}



float sinus(float x, int n){

int i, forsign;
float sum, element; sum = 0.0; forsign = 1;
for( i=1; i<=n; i++ ) {

element = forsign * pow(x,2*i-1) / fakt(2*i-1);
forsign *= -1;
sum += element;

}

return sum;

}








Technorati Tags:
, , , , , ,

Continue reading full article...

Lesson 15: Matrixes and 2D Arrays

5 comments

There was a slight pause in my C++ Maniac programming tutorial, due to me answering some of your C & C++ lesson-related questions. You can find some explanations on previous programming materials in my sidebar now, along with other new C & C++ stuff. It seems to me finally, after all troubleshoots are answered (or are they?!), we can bravely continue. This 15th lesson is about matrixes and two-dimensional C++ arrays. Although this one may look significantly more complicated, if you read through it carefully, you will conquer programming matrixes with no problem – I promise you that.




Declaration of a 2D array in C language:

int x[3][2] - matrix 3X2 (3 rows, 2 columns), elements: integers
char myascii[2][4] - array of characters (2 rows & 4 columns)
float sequence[MAXROW][MAXCOL] - MAXROW X MAXCOL matrix




Example of declaration with initialization:

int array[3][3] = {1, 2, 3, 4, 5};
array[0][0] = 1

array[0][1] = 2
array[0][2] = 3
array[1][0] = 4
array[1][1] = 5
array[1][2] = 0 // even though nowhere stated
array[2][0] = 0
array[2][1] = 0
array[2][2] = 0





char cmaniac[7] = {'C', 'M', 'A', 'N', 'I', 'A', 'C'}


/* array of characters */






int y[3][4] = { {1, 2, 3},

{4, 5, 6},
{7, 8, 9} };






y[0][0]= 1 y[0][1]= 2 y[0][2]= 3 y[0][3]= 0

y[1][0]= 4 y[1][1]= 5 y[1][2]= 6 y[1][3]= 0
y[2][0]= 7 y[2][1]= 8 y[2][2]= 9 y[2][3]= 0





Declaration of multidimensional array:

int x[3][2][4] 3D array of integer numbers
float x[3][2][4][1] 4D array of real numbers





Example:

Write your own C program that reads through real matrix, 10x10 dimensioned and finds the smallest element in main diagonal and smallest element in secondary diagonal.



#include <stdio.h>

#define NR_ROW 10

#define NR_COL 10


int main(void) {


int i, j;

float mat[NR_ROW][NR_COL], min_maindg, min_secdg;


printf("Input matrix elements :");
for (i = 0; i < NR_ROW; i++) {
for (j = 0; j < NR_COL; j++) {


printf("\nInput element [%d][%d] : ", i, j);

scanf("%f", &mat[i][j]);


}

}

min_maindg = mat[0][0];


//min el. is mat(0,0), this is why loop starts from 1

for (i = 1; i < NR_ROW; i++) {

if (mat[i][i] < min_maindg) {

min_maindg = mat[i][i];


}

}

min_secdg = mat[0][NR_COL -1];

for (i = 1; i < NR_ROW; i++) {


if (mat[i][NR_COL-i-1] < min_secdg) {


min_secdg = mat[i][NR_COL-i-1];


}

}

printf("\nSmallest el. in main diagonal is: %f",
min_maindg);

printf("\nSmallest el. in second diagonal is: %f",
min_secdg);

}




Shorter version – single run through the matrix:


#include <stdio.h>

#define NR_ROW 10

#define NR_COL 10


int main(void) {


int i, j;

float mat[NR_ROW][NR_COL], min_maindg, min_secdg;

printf("\nInput matrix elements :\n");
for (i = 0; i < NR_ROW; i++) {
for (j = 0; j < NR_COL; j++) {

printf("\nInput element [%d][%d] : ", i, j);

scanf("%f", &mat[i][j]);

if (i == 0 && j == 0) {

min_maindg = mat[i][j];


}

if (i == 0 && j == NR_COL - 1) {

min_secdg = mat[i][j];


}

if (i == j) {
if (mat[i][j] < min_maindg) {

min_maindg = mat[i][j];

}
}
if (i == NR_COL - 1 - j) {
if (mat[i][j] < min_secdg) {

min_secdg = mat[i][j];

}
}
}
}
printf("\nSmallest element in main diagonal is : %f",
min_maindg);

printf("\nSmallest element in second diagonal is : %f",
min_secdg);

}




Example:

Write your own C program that transposes matrix. Program stores given matrix dimensions and every single matrix element must be given. Transposed matrix is the one with rows and columns switched.



#include <stdio.h>

#define MAX_ROW 50

#define MAX_COL 50


int main(void) {

int i, j, m, n, temp;

int mat[MAX_ROW][MAX_COL];



// variable dim is set to smaller value of defined
// maximal number of rows and columns


int dim = (MAX_ROW < MAX_COL)? MAX_ROW : MAX_COL;



// storing matrix size

do {

printf("Input number of rows < %d :", dim);
scanf("%d", &m);
printf("Input number of columns < %d:", dim);
scanf("%d", &n);

} while (m < 1 || m > dim || n < 1 || n > dim);



// storing matrix elements

printf("\nInput of matrix elements :\n");
for (i = 0; i < m; i++) {

for (j = 0; j < n; j++) {


printf("Input element [%d][%d] : ", i, j);

scanf("%d", &mat[i][j]);

}
}



// printing matrix before transposing

printf("\n\nMatrix before transposing:\n");
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {

printf("%3d", mat[i][j]);


}

printf("\n");
}




// transposing

for ( i=0; i<m; ++i ) {
// looping must start from i+1 !!
for ( j=i+1; j<n; ++j ) {

temp = mat[i][j];

mat[i][j] = mat[j][i];
mat[j][i] = temp;
}
}



// print after transposing
// number of rows becomes number of columns ...

printf("\nMatrix after transposing:\n");
for (i = 0; i < n; i++) {
for (j = 0; j < m; j++) {

printf("%3d", mat[i][j]);

}
printf("\n");
}
} // main





Example of program’s execution:


Input number of rows < 50: 3
Input number of columns < 50: 2

Input of matrix elements :
Input element [0][0] : 1
Input element [0][1] : 2
Input element [1][0] : 3
Input element [1][1] : 4
Input element [2][0] : 5
Input element [2][1] : 6


Matrix before transposing:

1 2
3 4
5 6


Matrix after transposing:

1 3 5
2 4 6





Example:

Write your own C program that stores real matrix whose dimensions are 10x10, and finds the sum of elements from every column and product of elements from every row. Program prints the smallest sum (including parent column’s index), and biggest product (including parent row’s index). Sums and products should be stored in one-dimensional arrays.



#include <stdio.h>

#define NR_ROW 10

#define NR_COL 10


int main(void) {

int i, j;

int min_sum_ind, max_prod_ind;

float mat[NR_ROW][NR_COL];
float sum[NR_COL], prod[NR_ROW];


/*1.variant of input and calculating sums & products*/


for (i = 0; i < NR_ROW; i++) {
for (j = 0; j < NR_COL; j++) {

printf("\nInput element[%d][%d] : ", i, j);

scanf("%f", &mat[i][j]);
}
}

for (j = 0; j < NR_COL; j++) {

sum[j] = 0;

for (i = 0; i < NR_ROW; i++) {

sum[j] += mat[i][j];


}

}

for (i = 0; i < NR_ROW; i++) {

prod[i] = 1;


for (j = 0; j < NR_COL; j++) {


prod[i] *= mat[i][j];

}
}

/*end of input, and sums & products calculation*/



/* finding column’s index for smallest sum */

min_sum_ind = 0;
for (j = 1; j < NR_COL; j++) {
if (sum[j] < sum[min_sum_ind]) {

min_sum_ind = j;

}
}


/* finding row’s index for biggest product */

max_prod_ind = 0;
for (i = 1; i < NR_ROW; i++) {
if (prod[i] > prod[max_prod_ind]) {

max_prod_ind = i;

}
}

printf("\nSmallest sum: %f, parent index: %d\n",
sum[min_sum_ind], min_sum_ind);
printf("\nBiggest product: %f, parent index: %d\n",
prod[max_prod_ind], max_prod_ind);
}




Shorter variant for storing elements and calculating sums & products:

/*2.variant of input and calculating sums & products*/

for (i = 0; i < NR_ROW; i++) {


prod[i] = 1;

for (j = 0; j < NR_COL; j++) {

printf("\nInput element [%d][%d] : ", i, j);

scanf("%f", &mat[i][j]);
prod[i] *= mat[i][j];
if (i == 0) {

sum[j] = 0;


}

sum[j] += mat[i][j];

}
}


/* end of input, and sums & products calculation */






Technorati Tags:
, , , , , ,

Continue reading full article...

German Flag Spanish Flag French Flag Italian Flag Portuguese Flag Japanese Flag Korean Flag Chinese Flag British Flag


This Website is optimized for Firefox. Users browsing with Internet Explorer may encounter problems while viewing pages.


C++ Maniac



Learn C



Additional



#include



Learn Converting



Appendix


Links




Daily Lessons for programming in Visual Studio, using C code.