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

6 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...

C++ Intermezzo

0 comments

Before I continue lecturing and post my 15th Lesson, I’ll give you a slight C++ break. This will be in order to provide you with some additional explanations to previous chapters. This decision is based on comments and questions you've submitted to some of my C and C++ topics (yes I read your posts :) You can see there are some fresh lectures regarding C Numerical Systems and Numeric System Conversions, while further explanations and examples regarding Numeric Data Storage and #include library references will also be provided soon. Remember, some of these chapters aren't necessary for you to obtain C & C++ knowledge, but are great material to understand computer’s logic and “behind curtains” view, of how things work inside the machine. This topic is also a great chance for you to post more questions and proposals for my future in-depth C++ articles. Sorry if the site is gonna look a little messy these days… It’s because I’m adding tons of new C++ stuff ;)

Comments section is temporarly moderated, but feel free to post your questions, It just takes some time for them to show up (after I approve them by hand).



Technorati Tags: , , , , , , , , , , ,

Continue reading full article...

Hex 2 Binary 2 Octal

6 comments

General Method for Transforming Numbers - Number we want to transform uses base X: we would like to transform this number into new one, that uses Y base. In this case we will use method of continuous dividing and multiplying (dividing numbers left of comma (,) with Y and multiplying numbers on the right side of comma, by Y - rational numbers). This method is best understood looking at these examples:


Octal System:

Base: 8
Digits: 0, 1, 2, 3, 4, 5, 6, 7
Example: 27 (decimal) = 33 8 (octal)



Hexadecimal (hex) System:

Base: 16
Digits: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F
Example: 27 (decimal) = 1B 16 (hex)



Binary System:

Base: 2
Digits: 0, 1
Example: 27 (decimal) = 11011 2 (binary)




Transforming Binary, Hex and Octal - Quickly



Binary Hex Binary Octal

0000 0 000 0
0001 1 001 1
0010 2 010 2
0011 3 011 3
0100 4 100 4
0101 5 101 5
0110 6 110 6
0111 7 111 7
1000 8
1001 9
1010 A
1011 B
1100 C
1101 D
1110 E
1111 F





Example

Transform -6F,A 16 into binary number


-6F,A 16  =  -  0110  1111  ,  1010  2  =  - 1101111 , 101 2




Example

Transform 11,000011001 2 into hex number

11,000011001 2   =      11  ,  0000  1100  1  2
= 0011 , 0000 1100 1000 2

= 3 , 0 C 8 16

=
3 , 0C8 16



Example

Transform 37,24 8 into binary number


37,24 8 = 011 111 , 010 100 2 = 11111 , 0101 2




Example

Transform 1111011,10011101 2 into octal number

1111011,10011101 2   =        1  111  011  ,  100  111  01  2
= 001 111 011 , 100 111 010 2

= 1 7 3 , 4 7 2 16

=
173 , 472 16





Technorati Tags:
, , , , , , , , , , ,


Continue reading full article...

Hexadecimal 2 Decimal

0 comments

Number we want to transform uses base X: we would like to transform this number into new one, that uses Y base. In this case we will use method of continuous dividing and multiplying (dividing numbers left of comma (,) with Y and multiplying numbers on the right side of comma, by Y - rational numbers). This method is best understood looking at these examples, where X = 16 (source is hex base, B1=16) and Y = 10 (destination is decimal base, B2=10).



Hexadecimal (hex) System:

Base: 16
Digits: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F
Example: 27 (decimal) = 1B 16 (hex)



Decimal System:


Base: 10
Digits: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9



Hex 2 Decimal




Example

Transform 9EC,570A3 (hex) into decimal number

9EC, 570A3 16 = 9*162 + 14*161 + 12*160 + 5*16-1 + 7*16-2 + 0*16-3 + 10*16-4 + 3*16-5

= 2304 + 224 +12 + 0,3125 + 0,02734375 + 0,0001525878... + 0,00000286102...

= 2540 , 33999919891357421875






Technorati Tags:
, , , , , , , , , , ,


Continue reading full article...

Binary 2 Decimal

1 comments

Number we want to transform uses base X: we would like to transform this number into new one, that uses Y base. In this case we will use method of continuous dividing and multiplying (dividing numbers left of comma (,) with Y and multiplying numbers on the right side of comma, by Y - rational numbers). This method is best understood looking at these examples, where X = 2, and Y = 10 (binary and decimal base, B1=2, B2=10):


Binary System:

Base: 2
Digits: 0, 1
Example: 27 (decimal) = 11011 2 (binary)


Decimal System:

Base: 10
Digits: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9



Binary 2 Decimal




Example

Transform 110101 (binary) into decimal number


110101 2 = 1*25 + 1*24 + 0*23 + 1*22 + 0*21 + 1*20
= 1*25 + 1*24 + 1*22 + 1*20

= 1*32 + 1*16 + 1*4 + 1*1

=
53 10




Example

Transform -11,101 (binary) into decimal number


-11,101 2 = - (1*21 + 1*20 + 1*2-1 + 0*2-2 + 1*2-3)
= - (1*21 + 1*20 + 1*2-1 + 1*2-3)

= - (1*2 + 1*1 + 1*0,5 + 1*0,125)

=
- 3 , 625





Technorati Tags: , , , , , , , , , , ,

Continue reading full article...

Decimal 2 Hexadecimal

1 comments

Number we want to transform uses base X: we would like to transform this number into new one, that uses Y base. In this case we will use method of continuous dividing and multiplying (dividing numbers left of comma (,) with Y and multiplying numbers on the right side of comma, by Y - rational numbers). This method is best understood looking at these examples, where X equals 10 and Y equals 16 (hex base, B=16)


Decimal System:

Base: 10
Digits: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9


Hexadecimal (hex) System:

Base: 16
Digits: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F
Example: 27 (decimal) = 1B 16 (hex)





Decimal 2 Hex




Example

Transform 2540,34 (decimal) into hex number-result ~ 9EC, 570A316


a) left from”,

2540 : 16 = 158 , remaining 12 => C        160        last digit
158 : 16 = 9 , remaining 14 =>
E 161
9 : 16 = 0 , remaining 9 =>
9 162 first digit

end of procedure => 9EC 16


b) right from “,

0,34 * 16 = 5,44 5 => 5 16-1 first digit after zero
0,44 * 16 = 7,04 7 =>
7 16-2
0,04 * 16 = 0,64 0 => 0 16-3
0,64 * 16 = 10,24 10 => A 16-4
0,24 * 16 = 3,84 3 => 3 16-5


procedure could be continued => 0, 570A3… 16



Final result ~ 9EC , 570A316




Technorati Tags:
, , , , , , , , , , ,




Continue reading full article...

Decimal 2 Binary

1 comments

Number we want to transform uses base X: we would like to transform this number into new one, that uses Y base. In this case we will use method of continuous dividing and multiplying (dividing numbers left of comma (,) with Y and multiplying numbers on the right side of comma, by Y - rational numbers). This method is best understood looking at these examples where X equals 10 (decimal base, B=10), and Y eqauls 2 (binary base, B=2)


Decimal System:


Base: 10
Digits: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9


Binary System:

Base: 2
Digits: 0, 1
Example: 27 (decimal) = 11011 2 (binary)




Decimal 2 Binary




Example


Transform 29 (decimal) into binary number - reading upwards, result is 111012


29 : 2 =  14 , remaining 1   20            last (smallest) digit
14 : 2 = 7 , remaining
0 21
7 : 2 = 3 , remaining 1 22
3 : 2 = 1 , remaining 1 23
1 : 2 = 0 , remaining 1 24 first digit

- end of procedure





Example

Transform 0,8125 (decimal) into binary number – reading downwards, result is 0,11012


0,8125  * 2 =      1, 625    2-1            first digit after zero
0,625 * 2 =
1, 25 2-2
0,25 * 2 = 0, 5 2-3
0,5 * 2 = 1, 0 2-4 last digit

0,0 end of procedure





Example

Transform 0,3 (decimal) into binary number – result is 0,01001 1001 1001… 2 shortly rounded = 0,010012


0,3  * 2 =      0, 6         2-1       first digit after zero
0,6 * 2 =
1, 2 2-2
--------
0,2 * 2 = 0, 4 2-3
0,4 * 2 = 0, 8 2-4
0,8 * 2 = 1, 6 2-5
0,6 * 2 = 1, 2 2-6
--------



procedure never ends





Example – Quick Method

Transform 53(decimal) into binary number using quick method


  53                                                                          25 + 24 + 22 + 20 =
- 32 -> 25 1*25 + 1*24 + 0*23 + 1*22 + 0*21 + 1*20 =

-------- 110101 2
21
- 16 -> 24
--------
5
- 4 -> 22
--------
1
- 1 -> 20
--------
0 -> end of procedure









Technorati Tags:
, , , , , , , , , , ,

Continue reading full article...

Decimal 2 Decimal

0 comments

Number we want to transform uses base X: we would like to transform this number into new one, that uses Y base. In this case we will use method of continuous dividing and multiplying (dividing numbers left of comma (,) with Y and multiplying numbers on the right side of comma, by Y - rational numbers). This method is best understood looking at these exampleswhere both X & Y equal to 10 (decimal base, B=10)



Decimal System:


Base: 10
Digits: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9




Example

Transform 5324 (decimal) into decimal number (?!) using method of continuous dividing – result 5324


5324 : 10 = 532 , remaining 4 100 last digit
532 : 10 = 53 , remaining
2 101
53 : 10 = 5 , remaining 3 102
5 : 10 = 0 , remaining 5 103 first digit


- end of procedure





Example

Transform 0,8125 (decimal) into decimal number (?!) using method of continuous multiplying – result 0,8125


0,8125  * 10 =   8, 125    10-1           first digit after zero
0,125 * 10 =
1, 25 10-2
0,25 * 10 = 2, 5 10-3
0,5 * 10 = 5, 0 10-4 last digit

0,0 end of procedure







Technorati Tags:
, , , , , , , , , , ,

Continue reading full article...

Numerical Systems

0 comments

Our society uses numerical system with base 10. Simple explanation why this system is used - simply because people have ten fingers, thus this is the easiest way for us to calculate numbers. If things were gone different, and something had messed up primordial soup -> developing Homo sapiens with eight fingers, it would be more likely we would use octal numeric system in present time. Infinite number of numerical systems exist, but following are most commonly used...




Decimal System:


Base: 10
Digits: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9




Octal System:


Base: 8
Digits: 0, 1, 2, 3, 4, 5, 6, 7
Example: 27 (decimal) = 33 8 (octal)




Hexadecimal (hex) System:


Base: 16
Digits: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F
Example: 27 (decimal) = 1B 16 (hex)




Binary System:


Base: 2
Digits: 0, 1
Example: 27 (decimal) = 11011 2 (binary)


To learn more about numerical systems and their transformation (decimal2binary, dec2hex, dec2octal, hex2octal,...) continue to next lecture.





Technorati Tags:
, , , , , , , , , , ,

Continue reading full article...

Numeric Transformations

0 comments

General Method of Transforming Numbers


Number we want to transform uses base X: we would like to transform this number into new one, that uses Y base. In this case we will use method of continuous dividing and multiplying (dividing numbers left of comma (,) with Y and multiplying numbers on the right side of comma, by Y - rational numbers). This method is best understood looking at these examples:




Example

Transform 5324 (decimal) into decimal number (?!) using method of continuous dividing – result 5324


5324 : 10 = 532 , remaining 4 100 last digit
532 : 10 = 53 , remaining
2 101
53 : 10 = 5 , remaining
3 102
5 : 10 = 0 , remaining
5 103 first digit

- end of procedure





Example

Transform 0,8125 (decimal) into decimal number (?!) using method of continuous multiplying – result 0,8125


0,8125  * 10 =   8, 125    10-1           first digit after zero
0,125 * 10 =
1, 25 10-2
0,25 * 10 = 2, 5 10-3
0,5 * 10 = 5, 0 10-4 last digit

0,0 end of procedure






Decimal 2 Binary




Example

Transform 29 (decimal) into binary number - reading upwards, result is 111012


29 : 2 =  14 , remaining 1   20            last (smallest) digit
14 : 2 = 7 , remaining
0 21
7 : 2 = 3 , remaining 1 22
3 : 2 = 1 , remaining 1 23
1 : 2 = 0 , remaining 1 24 first digit

- end of procedure





Example

Transform 0,8125 (decimal) into binary number – reading downwards, result is 0,11012


0,8125  * 2 =      1, 625    2-1            first digit after zero
0,625 * 2 =
1, 25 2-2
0,25 * 2 = 0, 5 2-3
0,5 * 2 = 1, 0 2-4 last digit

0,0 end of procedure





Example

Transform 0,3 (decimal) into binary number – result is 0,01001 1001 1001… 2 shortly rounded = 0,010012


0,3  * 2 =      0, 6         2-1       first digit after zero
0,6 * 2 =
1, 2 2-2
--------
0,2 * 2 = 0, 4 2-3
0,4 * 2 = 0, 8 2-4
0,8 * 2 = 1, 6 2-5
0,6 * 2 = 1, 2 2-6
--------



procedure never ends





Example – Quick Method

Transform 53(decimal) into binary number using quick method


  53                                                                          25 + 24 + 22 + 20 =
- 32 -> 25 1*25 + 1*24 + 0*23 + 1*22 + 0*21 + 1*20 =

-------- 110101 2
21
- 16 -> 24
--------
5
- 4 -> 22
--------
1
- 1 -> 20
--------
0 -> end of procedure






Decimal 2 Hex




Example

Transform 2540,34 (decimal) into hex number-result ~ 9EC, 570A316


a) left from”,

2540 : 16 = 158 , remaining 12 => C        160        last digit
158 : 16 = 9 , remaining 14 =>
E 161
9 : 16 = 0 , remaining 9 =>
9 162 first digit

end of procedure => 9EC 16


b) right from “,

0,34 * 16 = 5,44 5 => 5 16-1 first digit after zero
0,44 * 16 = 7,04 7 =>
7 16-2
0,04 * 16 = 0,64 0 => 0 16-3
0,64 * 16 = 10,24 10 => A 16-4
0,24 * 16 = 3,84 3 => 3 16-5


procedure could be continued => 0, 570A3… 16



Final result ~ 9EC , 570A316






Binary 2 Decimal




Example

Transform 110101 (binary) into decimal number


110101 2 = 1*25 + 1*24 + 0*23 + 1*22 + 0*21 + 1*20
= 1*25 + 1*24 + 1*22 + 1*20

= 1*32 + 1*16 + 1*4 + 1*1

=
53 10




Example

Transform -11,101 (binary) into decimal number


-11,101 2 = - (1*21 + 1*20 + 1*2-1 + 0*2-2 + 1*2-3)
= - (1*21 + 1*20 + 1*2-1 + 1*2-3)

= - (1*2 + 1*1 + 1*0,5 + 1*0,125)

=
- 3 , 625






Hex 2 Decimal




Example

Transform 9EC,570A3 (hex) into decimal number

9EC, 570A3 16 = 9*162 + 14*161 + 12*160 + 5*16-1 + 7*16-2 + 0*16-3 + 10*16-4 + 3*16-5

= 2304 + 224 +12 + 0,3125 + 0,02734375 + 0,0001525878... + 0,00000286102...

= 2540 , 33999919891357421875






Quick Method of Transforming between Binary, Hex and Octal System


Binary Hex Binary Octal

0000 0 000 0
0001 1 001 1
0010 2 010 2
0011 3 011 3
0100 4 100 4
0101 5 101 5
0110 6 110 6
0111 7 111 7
1000 8
1001 9
1010 A
1011 B
1100 C
1101 D
1110 E
1111 F





Example

Transform -6F,A 16 into binary number


-6F,A 16  =  -  0110  1111  ,  1010  2  =  - 1101111 , 101 2




Example

Transform 11,000011001 2 into hex number

11,000011001 2   =      11  ,  0000  1100  1  2
= 0011 , 0000 1100 1000 2

= 3 , 0 C 8 16

=
3 , 0C8 16



Example

Transform 37,24 8 into binary number


37,24 8 = 011 111 , 010 100 2 = 11111 , 0101 2




Example

Transform 1111011,10011101 2 into octal number

1111011,10011101 2   =        1  111  011  ,  100  111  01  2
= 001 111 011 , 100 111 010 2

= 1 7 3 , 4 7 2 16

=
173 , 472 16






Technorati Tags:
, , , , , , , , , , ,

Continue reading full article...


Our society uses numerical system based on number 10. There is a nutorious explanation why this system is used - it's simple, people have ten fingers, thus makes them easier to calculate numbers. If things were gone different, and something had messed up primordial soup -> developing Homo sapiens with eight fingers, it would be more likely we would use octal numeric system at present time. Infinite number of numerical systems exist, but following are most commonly used, and their conversion from one to another, is simple.




Decimal System:

Base: 10
Digits: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9



Octal System:

Base: 8
Digits: 0, 1, 2, 3, 4, 5, 6, 7
Example: 27 (decimal) = 33 8 (octal)



Hexadecimal (hex) System:

Base: 16
Digits: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F
Example: 27 (decimal) = 1B 16 (hex)



Binary System:

Base: 2
Digits: 0, 1
Example: 27 (decimal) = 11011 2 (binary)




General Method of Transforming Numbers


Number we want to transform uses base X: we would like to transform this number into new one, that uses Y base. In this case we will use method of continuous dividing and multiplying (dividing numbers left of comma (,) with Y and multiplying numbers on the right side of comma, by Y - rational numbers). This method is best understood looking at these examples:




Example

Transform 5324 (decimal) into decimal number (?!) using method of continuous dividing – result 5324


5324 : 10 = 532 , remaining 4 100 last digit
532 : 10 = 53 , remaining
2 101
53 : 10 = 5 , remaining
3 102
5 : 10 = 0 , remaining
5 103 first digit

- end of procedure





Example

Transform 0,8125 (decimal) into decimal number (?!) using method of continuous multiplying – result 0,8125


0,8125  * 10 =   8, 125    10-1           first digit after zero
0,125 * 10 =
1, 25 10-2
0,25 * 10 = 2, 5 10-3
0,5 * 10 = 5, 0 10-4 last digit

0,0 end of procedure






Decimal 2 Binary




Example

Transform 29 (decimal) into binary number - reading upwards, result is 111012


29 : 2 =  14 , remaining 1   20            last (smallest) digit
14 : 2 = 7 , remaining
0 21
7 : 2 = 3 , remaining 1 22
3 : 2 = 1 , remaining 1 23
1 : 2 = 0 , remaining 1 24 first digit

- end of procedure





Example

Transform 0,8125 (decimal) into binary number – reading downwards, result is 0,11012


0,8125  * 2 =      1, 625    2-1            first digit after zero
0,625 * 2 =
1, 25 2-2
0,25 * 2 = 0, 5 2-3
0,5 * 2 = 1, 0 2-4 last digit

0,0 end of procedure





Example

Transform 0,3 (decimal) into binary number – result is 0,01001 1001 1001… 2 shortly rounded = 0,010012


0,3  * 2 =      0, 6         2-1       first digit after zero
0,6 * 2 =
1, 2 2-2
--------
0,2 * 2 = 0, 4 2-3
0,4 * 2 = 0, 8 2-4
0,8 * 2 = 1, 6 2-5
0,6 * 2 = 1, 2 2-6
--------



procedure never ends





Example – Quick Method

Transform 53(decimal) into binary number using quick method


  53                                                                          25 + 24 + 22 + 20 =
- 32 -> 25 1*25 + 1*24 + 0*23 + 1*22 + 0*21 + 1*20 =

-------- 110101 2
21
- 16 -> 24
--------
5
- 4 -> 22
--------
1
- 1 -> 20
--------
0 -> end of procedure






Decimal 2 Hex




Example

Transform 2540,34 (decimal) into hex number-result ~ 9EC, 570A316


a) left from”,

2540 : 16 = 158 , remaining 12 => C        160        last digit
158 : 16 = 9 , remaining 14 =>
E 161
9 : 16 = 0 , remaining 9 =>
9 162 first digit

end of procedure => 9EC 16


b) right from “,

0,34 * 16 = 5,44 5 => 5 16-1 first digit after zero
0,44 * 16 = 7,04 7 =>
7 16-2
0,04 * 16 = 0,64 0 => 0 16-3
0,64 * 16 = 10,24 10 => A 16-4
0,24 * 16 = 3,84 3 => 3 16-5


procedure could be continued => 0, 570A3… 16



Final result ~ 9EC , 570A316






Binary 2 Decimal




Example

Transform 110101 (binary) into decimal number


110101 2 = 1*25 + 1*24 + 0*23 + 1*22 + 0*21 + 1*20
= 1*25 + 1*24 + 1*22 + 1*20

= 1*32 + 1*16 + 1*4 + 1*1

=
53 10




Example

Transform -11,101 (binary) into decimal number


-11,101 2 = - (1*21 + 1*20 + 1*2-1 + 0*2-2 + 1*2-3)
= - (1*21 + 1*20 + 1*2-1 + 1*2-3)

= - (1*2 + 1*1 + 1*0,5 + 1*0,125)

=
- 3 , 625






Hex 2 Decimal




Example

Transform 9EC,570A3 (hex) into decimal number

9EC, 570A3 16 = 9*162 + 14*161 + 12*160 + 5*16-1 + 7*16-2 + 0*16-3 + 10*16-4 + 3*16-5

= 2304 + 224 +12 + 0,3125 + 0,02734375 + 0,0001525878... + 0,00000286102...

= 2540 , 33999919891357421875






Quick Method of Transforming between Binary, Hex and Octal System


Binary Hex Binary Octal

0000 0 000 0
0001 1 001 1
0010 2 010 2
0011 3 011 3
0100 4 100 4
0101 5 101 5
0110 6 110 6
0111 7 111 7
1000 8
1001 9
1010 A
1011 B
1100 C
1101 D
1110 E
1111 F





Example

Transform -6F,A 16 into binary number


-6F,A 16  =  -  0110  1111  ,  1010  2  =  - 1101111 , 101 2




Example

Transform 11,000011001 2 into hex number

11,000011001 2   =      11  ,  0000  1100  1  2
= 0011 , 0000 1100 1000 2

= 3 , 0 C 8 16

=
3 , 0C8 16



Example

Transform 37,24 8 into binary number


37,24 8 = 011 111 , 010 100 2 = 11111 , 0101 2




Example

Transform 1111011,10011101 2 into octal number

1111011,10011101 2   =        1  111  011  ,  100  111  01  2
= 001 111 011 , 100 111 010 2

= 1 7 3 , 4 7 2 16

=
173 , 472 16






Technorati Tags:
, , , , , , , , , , ,

Continue reading full article...

Lesson 14: Arrays

1 comments

In C language arrays are very popular. They can be found in almost any program code and are pretty helpful and easy to understand. To understand them, just visualize a sequence of numbers and try assigning them to only one declaration. It can be done if the declaration is properly stated as an array including index brackets (example int MySequence[20]).



Arrays

Array is data structure used to share multiple data elements under a single name declaration. It’s important that every single element of data, we wish to assign to array, belongs to the same data type. Array’s elements are easily accessed – we use index; a number that must be nonnegative integer (constant, variable, integer expression). Element’s index is a number between 0 and the number of elements minus one, including. In short: Index ( [0, NrOfElements – 1].



Declaration of an array:


data_type array[index];



Array’s definition in C:

int x[20] – array consisted of 20 integer numbers
char symbols[2] – array consisted of 2 characters
float sequence[MAX] – MAX is constant



Assigning element’s values definition:

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

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



Accessing array’s elements:

x[0] – first element of an array
sequence[i] – i. element of an array, 0 <= i <= NrOfElements – 1
sequence[MAX – 1] – last element of an array



Common Wrong access to array’s elements:

int array[10] = {0};
int x = sequence[10];

float a = 1.;
int x = array[a];
int a = 1, b = 0, c = 1;
int x = array[(a && b) - c];




Example:

Write your own program that asks user to input sequence of numbers, afterwards it calculates arithmetic middle of the given sequence. Program also prints numbers smaller than arithmetic middle, and afterwards prints numbers bigger than arithmetic middle.



#include <stdio.h>
#define DIMENSION 10


int main(void) {

int i;

float sum = 0., arit_midd = 0., sequence[DIMENSION]={0};

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

printf("Input number: ");
scanf("%f",&sequence[i]);
sum += sequence[i];

}

arit_midd = sum / DIMENSION;
printf("Arithmetic middle of the sequence is %6.2f.\n", arit_midd);
for (i = 0; i < DIMENSION; i++) {

if (sequence[i] < arit_midd) {

printf("%6.2f is smaller than arithmetic middle.\n", sequence[i]);

}
}

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

if (sequence[i] > arit_midd) {

printf("%6.2f is bigger than arithmetic middle.\n", sequence[i]);

}
}

// What happens if the number is equal to arithmetic middle?

}





Example:


Write your own program that asks for input of sequence of numbers. After the program reads given numbers, it divides every number with the biggest sequence element and shows them in a way relative to the biggest element.


#include <stdio.h>
#define DIMENSION 10


int main(void) {

int i;
float max, array[DIMENSION];

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

printf("array[%d] = ", i);
scanf("%f",& array[i]);
if (i == 0) {

max = array[i];

}
if (max < array[i]) {

max = array[i];

}
}

printf("Biggest element in array is %f.\n\n", max);
for (i = 0; i < DIMENSION; i++) {

array[i] /= max;
printf("array[%d] = %f\n", i, array[i]);

}
}





Example:

Compose your own program that reads given natural numbers that belong in [10, 99] interval and counts how many times each number showed up. Program stops reading numbers when element that doesn’t belong to interval is given. Afterwards, program prints each number from the interval that has showed at least once, and number of times it has really been given.



#include <stdio.h>

#define LL 10 /* lower limit of the interval */

#define UL 99 /* upper limit of the interval */

int main(void) {

int number, i;
int counter[UL – LL + 1] = { 0 };

do {

printf("\nInput number from interval [%d, %d]: ", LL, UL);
scanf("%d", &number);
if (number >= LL && number <= UL) {

counter[number - LL]++;

}

} while (number >= LL && number <= UL);

for (i = DG; i <= UL; i++) {

if (counter[i - LL] > 0) {

printf("\nNumber %d showed up %d times", i, counter [i - LL]);

}
}
}



Technorati Tags:
, , , , , ,

Continue reading full article...

About

3 comments

Purpose: "This website will provide you with lessons and quality material to learn basics of C language programming in just a few days. All you have to do is visit it here and then and read trough my lessons. You will notice I'm putting new lessons every day or two. It would be practical if you had Visual Studio installed on your computer and used it parallel to this lessons, but again it isn't neccessary... just follow and read theese C/C++ programming lessons and examples, and you'll be on your way! Let's not waste time, here we go..."

Continue reading full article...

alloc.h

0 comments

#include <alloc.h>, syntax at the beginning of our code, means we automatically included these (pre-defined) functions in our program:




void *malloc (size_t size); NULL error
void free (void *block);
void *realloc(void *block, size_t size); NULL error










Technorati Tags:
, , , , , ,

Continue reading full article...

ctype.h

2 comments

#include <ctype.h>, syntax at the beginning of our code, means we automatically included these (pre-defined) functions in our program:



int toupper(int ch);
int tolower(int ch);
int isdigit(int c);
figure (0-9)
int isalpha(int c);
letter (A-Z or a-z)
int isalnum(int c);
letter (A-Z or a-z) or figure (0-9)
int isprint(int c);
character which can be printed (0x20-0x7E)
int iscntrl(int c);
control char (0x7F or 0x00-0x1F)
int isspace(int c);
empty space
int islower(int c);
letter (a-z)
int isupper(int c);
letter (A-Z)








Technorati Tags:
, , , , , ,

Continue reading full article...

string.h

2 comments

#include <string.h>, syntax at the beginning of our code, means we automatically included these (pre-defined) functions in our program:


char *strcpy(char *dest, const char *src);
char *strncpy(char *dest, const char *src, size_t maxlen);
char *strcat(char *dest, const char *src);

size_t strlen(const char *s);

char *strlwr(char *s);
char *strupr(char *s);

int strcmp(const char *s1, const char *s2);
int strcmpi(const char *s1, const char *s2);
int stricmp(const char *s1, const char *s2);
int strncmp(const char *s1, const char *s2, size_t maxlen);
int strncmpi(const char *s1, const char *s2, size_t maxlen);
int strnicmp(const char *s1, const char *s2, size_t maxlen);

char *strchr(const char *s, int c);
char *strstr(const char *string, const char *substring);







Technorati Tags:
, , , , , ,

Continue reading full article...

stdlib.h

0 comments

#include <stdlib.h>, syntax at the beginning of our code, means we automatically included these (pre-defined) functions in our program:




void exit (int status);
void randomize (void);
or void srand (unsigned int seed);
int rand (void);








Technorati Tags:
, , , , , ,

Continue reading full article...

math.h

1 comments

#include <math.h>, syntax at the beginning of our code, means we automatically included these (pre-defined) functions in our program:


int abs (int x); IxI
long labs (long x);

double fabs (double x);
double sin (double x);
double cos (double x);
double tan (double x);
double asin (double x);
double acos (double x);
double atan (double x);
double sinh (double x);
double cosh (double x);
double tanh (double x);

double exp (double x); ex
double log (double x); ln x
double log10 (double x); log x

double pow (double x,double y); xy
double sqrt(double x); sqare root of x
double fmod(double x, double y); x mod y

double ceil (double x);
double floor(double x);






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.