C Tutorial
C Tutorial
C Tutorial
This is the first lesson I wrote. Its purpose is to introduce you to the world of
programming, showing you the way computers think or archive data. Please
be patient and read through the whole lesson carefully in order to fully
understand showed examples and calculations. I understand you can't wait to
start using the code, but believe me these general foundations are somehow
necessary to fully understand next tutorials and lessons I'll provide you with.
Take time, new lessons will be published in a time interval necessary for me
to compose them for your, and in the mean time you have time to carefully
run through previous like this one. Now we can begin...
Binary Numbers
Base system uses base B, and includes numbers 0, 1, 2, ... , B-1
For example in decimal system B=10, and numbers included are 0, 1, 2, ..., 8 &
9.
If the base B=2, then the system is binary, and its numbers are 0 & 1.
From English term BInary digiT, comes the name for lowest amount of
information BIT.
Example:
5710 = 5 * 101 + 7 * 100 = 1*25 + 1*24 + 1*23 + 0*22 + 0*21 + 1*20 = 1 1 1 0 0
12
Number 57 in decimal is shown by two numbers, while in binaries six figures
are necessary to show data. Binaries compared to other numbering systems,
logically use most amount of elements (data) to give us information. Number
of BITS used to write down a number is limited due to technical reasons.
Machines used to process and save binary information, are usually constructed
form electronic elements with 2 stable states (bistables), which are efficient and
cheap to produce.
Switching from decimal to binary numbers:
Binary number is made by leftovers we get from dividing (reading upwards)
57 : 2 = 28 1 1 1 0 0 1
1
28 : 2 = 14
0
14 : 2 = 7
0
7:2=3
1
3:2=1
1
1:2=0
1
Positive Number 0 1 0 1
( one komplement) - 0 1 0 1
1010
(dual complement) + 0 0 0 1
1011
1 0 1 1 (-5)
+ 0 1 0 1 (+5)
---------------
0000
extra 1
0 1 1 1 ( 7)
+ 1 0 1 1 (-5)
---------------
0010
extra 1
If we have n=3 bit length registry, (first bit reserved for telling us if its –/+),
next numbers can be shown:
Decades Binaries
0 000
1 001
2 010
3 011
-4 100
-3 101
-2 110
-1 111
Rational numbers
Rational numbers have binary “spot” which is similar to decimal spot used by
decimal numbers.
Example: conversion of rational number
5.75 10 = 5 * 100 + 7 * 10-1 + 5 * 10-2 =
= 1*22 + 0*21 + 1*20 + 1*2-1 + 1*2-2 = 1 0 1 . 1 1 2
Conversion of decimal number to binary number
1.25 = 1 + .25
.25 * 2 1 . 0 1
0.50
.5 * 2
1.0
.3 * 2 1 1 0 1 . 0 1 0 0 1 1 0 0 1 ...
0.6
.6 * 2
1.2
.2 * 2
0.4
.4 * 2
0.8
.8 * 2
1.6
.6 * 2
1.2
....
Notice that finite decimal number is shown as infinite periodic binary number.
Binary Number is mounted with exponent of Base 2, in a way that a binary dot
is moved left or right, depending if exponent is positive or negative
Example: 1 . 1 1 * 22 = 1 1 1
Update - March, 8. 2006: Don't panic! if you didn't quite understand these
numerical systems, You can still read my additional lesson that should in-
depth cover this topic. There are many examples on numeric conversions
also. Soon, I'm going to post another lesson on calculations with binarie
numbers.
Examples:
2 = 102 * 20 = 12 * 21 = 0100 0000 0000 0000 ... 0000 0000 = 4000 0000 hex
P = 0, K = 1 + 127 = 128 (10000000), M = (1.) 000 0000 ... 0000 0000
-2 = -102 * 20 = -12 * 21 = 1100 0000 0000 0000 ... 0000 0000 = C000 0000
hex
Equal to 2, but P = 1
4 = 1002 * 20 = 12 * 22 = 0100 0000 1000 0000 ... 0000 0000 = 4080 0000 hex
Equal Mantissa, BE = 2, K = 2 + 127 = 129 (10000001)
6 = 1102 * 20 = 1.12 * 22 = 0100 0000 1100 0000 ... 0000 0000 = 40C0 0000
hex
1 = 12 * 20 = 0011 1111 1000 0000 ... 0000 0000 = 3F80 0000 hex
K = 0 + 127 (01111111).
.75 = 0.112 * 20 = 1.12 * 2-1 = 0011 1111 0100 0000 ... 0000 0000 = 3F40 0000
hex
Special Case - 0:
Normalization of number 0 can’t produce shape 1.xxxxx
0 = 0 0000000 0000 ... like 1.02 * 2-127
double
P forsign ( P=1 negative, P=0 positive)
Range:
K [0,2047].
K = 0 reserved for display of zero
K = 2047 reserved for display infinity
BE = K - 1023
BE [-1022,1023]
There is also:
long double 80 bits
Characteristic: 15 bits
Binary exponent: Characteristic - 16383
Real constants
1. 2.34 9e-8 8.345e+25 double
2f 2.34F -1.34e5f float
1.L 2.34L -2.5e-37L long double
Type Size
float 4 octet
double 8 octet
Example:
int var;
printf("%d",sizeof(char)); // prints 1
printf("%d",sizeof(var)); // prints 4 (on MSVisualC++ 6.0)
Example:
0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1
If we take the same flow of binary digits, and save them in an integer
variablewithout forsign, then the leading 1 is part of the number (NOT
FORESIGN IN THIS CASE). In this way number 65531 is shown:
1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1
short int -> int -> unsigned int ->long int -> unsigned long int -> float -
> double-> long double
Exmple:
int a;
unsigned long b;
float f, g;
double d;
g = a + f; // a transforms to float
d = a + b; // a and b transform to unsigned long, adding
// is produced in unsigned long domain and then
// the result type unsigned long is transformed
// to double
Example:
long lm = LONG_MAX, l; // LONG_MAX = 2147483647
unsigned long um = ULONG_MAX; // ULONG_MAX = 4294967295
float f;
l = lm + 1; // result: -2147483648 (fill over to neg. field)
f = lm + 1; // result: -2147483648.000000 (result is made
// in long domain)
l = um + 1; // result: 0 (fill over)
f = um + 1; // result: 0.000000 (result is made in
// unsigned long domain)
Example:
a = (int) c;
b = (double)d + c;
DIVIDING INTEGERS
It’s important to notice that sometimes we get “unwanted” results when
dividing whole numbers. For example if we want to assign ½ to real variable
a, assigning won’t work as we would like it; the result wouldn’t be 0.5:
a = 1 / 2;
a = (float) 1 / 2; or
a = 1. / 2; or
a = 1 / 2.;
Important:
First case shows us way of using explicit casting (it could also be used on
second operand), and second and third example shows us possibility of
adding spot, which declares constant as real number. This makes our result
to be processed in real domain.
OPERATORS PRIORITY
1. * / %
2. + -
Example:
What’s the result of following expression?
5 + 10 / 3 * ( 8 – 6 )
5 + 10 / 3 * 2
5+3*2
5+6
11
Example:
What’s the result?
a) 9 / 4
Result: 2 (dividing of whole numbers)
b) 9 % 4
Result: 1 (% means remainder form division of whole numbers: 9 : 4 = 2 +
remainder 1)
Example:
What’s the result we get assigned to following operands i, x, c
int i;
double x, c, d;
after these phrases:
d = 6.0;
i = (int)(d + 1.73);
x = i / 2;
c = (double)i / 2;
Result:
i = 7, x = 3, c = 3.5
& AND
| OR
^ XOR
<< SHIFT LEFT
>> SHIFT RIGHT
~ NOT
Operators &, |, ^ are binary operators (defined above two bits). Operator ~
isunary operator (defined above single bit).
b1 b2 b1 & b2 b1 | b2 b1 ^ b2
0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 0
b1 ~b1
0 1
1 0
Example:
Calculate phrases: 3 & 5, 3 | 5, 3 ^ 5, ~3
Operators <<>> are used to reposition all the variables content bits, left or
right. Repositioning all the bits one place left is the same as multiplying the
variables content by 2 (x2), while repositioning one place right is the same as
dividing content with 2 (/2).
Electronic computers in general have repositioning instruction implemented in
their registry and in this way multiplying or dividing using number proportional
with 2, is many times faster than classical multiplying or dividing.
Number of places this operand repositions the content, is given with parameter.
Example:
Calculate these phrases: 2<<1 , and 37 >>2
Important:
In case data is saved in a single octet, without the bit reserved for foresign
(+/-), calculate 128 <<1
This lesson, as can be presumed from its title, will teach you what is
ASCII code, how does it affect programmer’s variables and what
is the difference between number and numerical figure. This one's
easy... Hope you still haven't pulled back; just when I hit you in
the face with hardcore code in next few lessons, don't say I caught
you off guard :) Developing your own program, even as simple as
calculator can give you nice, productive feeling.
48 – 57 – numbers '0'-'9'
CHARACTER CONSTANTS
char a;
a = 'X';
Example:
c = 'A';
//with \x
Example:
c='\\';
char a;
a = '1'; // equal to: a = 49;
Example:
char a = '7';
number = a – 48; or
number = a – '0'; or
Example:
char c ='A';
Example:
char a,b;
int i;
i = a - '0' + b - '0';
or
i = a + b – 2 * '0';
or
i = a + b - 96; // 2 * 48
ASSIGNIN OPERATOR
Example:
We can put:
a = b + 3;
but we can’t:
b + 3 = a;
Example:
a = b = c = 0;
a = b = c + 3;
Is this possible?
Example:
Phrase:
i = i + 5;
can also be written this way:
i += 5;
Phrase:
i = i * a;
i *= a;
C language has two operators that are able to resize variable’s value to
higher or lower value. Cause of their existence is to provide more efficient
executions (there are some special processor instructions that are capable
executing this operations very fast).
Using ++ or – operators with simple numeric types (variants of char, int and
real types), resizes to higher or lower value just by one. These operators are
useful when working with index fields, pointers and counters inside a loop.
It is advised to use prefix operators, because they are more efficient (postfix
operators create a temporary variable where they assign previous operand’s
value, which is used through the whole expression).
Example:
a = 5;
b = ++a * 2;
c = b++;
After execution of these orders, a gets value 6, b gets value 13, and c gets
value 12
In this expression we’re not sure which function will be processed first..
COMPARISON OPERATORS
CONDITION PHRASE IF
1. Simple selection
2. Two-sided selection
3. Multi-sided selection
Example:
What’s the result we get printed on screen, after this block of orders is
executed?
1.) a = 25 and b = 4.
2.) a = 0, b = 0
if (a = b)
else
printf ("Values of both variables are different\n");
Result:
Important:
if (a = b)
a = b; if (a)
Example:
Write your own program block that will add int variables a and b if the value
of char variable c is equal to '+'. If the value of c is '-', then it will subtract
mentioned variables. If the value of c is some other sign, then program must
return error sentence. Result must be assigned to variable r.
int a,b,r;
char c;
if( c == '+' )
r = a + b;
else if( c == '-')
r = a - b;
else
printf("Error – wrong operation");
Example:
Write your own program that will calculate crossing point of two lengths in
a real number axis (assuming that the first length is left on the axis and the
second right on the axis).
Important:
int a1, a2, b1, b2; // lengths [a1, a2] and [b1, b2]
int r1, r2; // result [r1, r2]
OPERATORS PRIORITY
Result:
int a = 5, b = -1, c = 0;
c = (a = c && b) ? a = b: ++c;
printf("a = %d, b = %d, c = %d: \n", a, b, c);
Result:
a = 0 , b = -1 , c = 1
TWOSIDED SELECTION
Example:
Write your own program that calculates and prints absolute value of given
number:
#include<stdio.h>
void main(){
int number,abs;
else { /*else */
#include <stdio.h>
#define PI 3.141592
void main(){
area=radius*radius*PI;
printf("Circle’s area is: %f\n", area);
}
}
What will be printed if someone enters -10 in "Input circle’s radius:"
if (radius <= 0) {
else {
area=radius*radius*PI;
printf("Circle’s area is: %f\n", area);
}
Example:
Write your own program which reads two given numbers, tests if the first
number is dividable with second one (with no remain left); and prints
suitable message. Second number must be different than 0 (why?).
#include <stdio.h>
void main(){
int a,b;
if (a % b == 0) {
}
else {
if (b != 0) {
MULTISIDED SELECTION
Example:
#inclde <stdio.h>
#define lower 50.0
#define upper 80.0
void main(){
float temp;
Program Iterations
Write your own program that will read given positive-whole numbers, until
number zero is given. Then it will print which given number was the
smallest. The program must ignore given negative numbers (given =
keyboard inputted).
3. after we processed the whole field, temp variable now stores the real
minimum member of field.
Example:
flow: 5, 6, 3, 9, 4, 7, 2, -1, 5.
#include <stdio.h>
void main() {
int min, x = 0;
while (x != 0) {
#include <stdio.h>
void main() {
while (x != 0) {
}
}
Example:
Program reads positive-whole numbers until their sum reaches value bigger
than approved range short int allows. Program also prints last valid sum.
#include <stdio.h>
void main() {
while (!end) {
printf("Input number : ");
scanf("%d", &x);
sum += x;
} else {
end = 1;
}
}
Example:
void main() {
if (i % 7 == 0) {
i++;
}
}
Example:
void main() {
++ nrSteps;
if (number % 2){
number = number * 3 + 1;
else {
number /= 2;
}
Give positive number: 9
In 1. step, number = 28
In 2. step, number = 14
In 3. step, number = 7
In 4. step, number = 22
In 5. step, number = 11
In 6. step, number = 34
In 7. step, number = 17
In 8. step, number = 52
In 9. step, number = 26
In 10. step, number = 13
In 11. step, number = 40
In 12. step, number = 20
In 13. step, number = 10
In 14. step, number = 5
In 15. step, number = 16
In 16. step, number = 8
In 17. step, number = 4
In 18. step, number = 2
In 19. step, number = 1
All together 19 steps.
Syntax:
Common use:
for (i = start; i <= end; i = i + k) {
.
.
.
}
Example:
Write your own program that will calculate arithmetic middle of n given
numbers.
#include <stdio.h>
void main() {
int i, n, sum, x;
float arit_midd;
Example:
Write your own program which will print real numbers from 0 till n, with
step of 0.1
#include <stdio.h>
void main() {
int n;
float i;
}
}
Example:
Write your own program which will print numbers dividable with 7, 13 and
19, and lower than given number n. Numbers must be printed from biggest
to the lowest one.
#include <stdio.h>
void main() {
int i, n;
if ( i % 7 == 0 ) || ( i % 13 == 0 ) || (i % 19 == 0) {
}
}
}
Warning:
or
for(;;){
//block of orders
Block of orders inside the body of loop is executed infinite number of times
if that block doesn’t consist of: breaking order (break), order for escaping
the function (return), program finish function call (exit) or goto order.
Common Mistakes:
Iteration (loop) which tests condition at the end.
Syntax:
do {
.
.
.
} while (expression);
Example in C:
do {
.
.
.
} while (x < y);
repeat
.
.
.
until ( x >= y )
Example
Write your own program that reads numbers from interval [-100, 100] or
[800, 1000]. Program has to print how much of these numbers were positive,
how much of them were negative and how much times 0 encountered.
#include <stdio.h>
void main(){
int number;
int nrPositive=0, nrNegative=0, nrZero=0;
printf("Give in numbers: ");
do {
scanf("%d", &number);
if (number >=-100 && number <=100 || number >=800 && number
<=1000) {
}while (number >=-100 && number <=100 || number >=800 && number
<=1000);
Example
k=0;
i=7;
lab:
k=k+i*2;
i=i-2;
printf ("%d\n", k);
if (i >= -7) goto lab;
1.)
k=0;
i=7;
while (i>=-7) {
k=k+i*2;
i=i-2;
printf ("%d\n", k);
}
2.)
k=0;
i=7;
do {
k=k+i*2;
i=i-2;
printf ("%d\n", k);
3.)
k = k + i * 2;
printf ("%d\n", k);
}
Example:
Write your own program that tests if the given number is prime number.
#include <stdio.h>
#include <math.h>
void main() {
}
}
if( prime )
else
printf("%d isn’t prime number!\n", n);
• Test if the number is dividable with 2, and if it isn’t, test inside loop if
the number is dividable with odd numbers bigger than 2
Example:
Write your own program that reads integers given by keyboard and applies
following rule above them: if the given number is smaller than zero,
program should print error message and stop reading numbers. If the given
number is bigger than 100, it should be skipped and program should read
another number. All other numbers should be red and printed. Program must
stop reading numbers when 0 or error shows up.
#include <stdio.h>
void main() {
int x;
do {
if (x > 100) {
} while (x != 0);
}
Syntax:
switch( expression ){
• pay attention: if the keyword break isn’t stated inside case block;
program continues to next case block in the list!
Example
Program reads student’s grade given from keyboard (from 1 to 5) and prints
it’s description.
#include <stdio.h>
void main() {
int grade;
printf ("Input grade :");
scanf("%d", & grade);
switch (grade) {
case 1:
printf("Fall (F)\n");break;
case 2:
printf("Bad (D)\n");break;
case 3:
printf("Good (C)\n");break;
case 4:
printf("Very Good (B)\n");break;
case 5:
printf("Excellent (A)\n");break;
default:
printf("You have inputted false grade\n");
break; // break isn’t necessary here
}
}
Pay Attention:
If break; was to be left-out from every case block, for given grade 3
(example), the result would be false and following:
Good
Very Good
Excellent
You have inputted false grade
Pay Attention:
If the “default” block is last block in your switch order, then it isn’t
necessary to state break next to it.
Pay Attention:
Consequence of falling through case labels in lack of break order is that the
same collection of orders is executed for more different case labels. Better
explained, this allows the following code
switch (letter) {
switch (letter) {
case 'a':
case 'e':
case 'i' :
case 'o':
case 'u': NrOfVowels ++; break;
default : NrOfOthers++; break;
}
Lesson 13: Hello World! - A Classic -
Loops
Example:
i = 1;
while (i < 5) {
if (i==3) {
} else if (i==4) {
}
i++;
}
Result:
Example:
Write your own program block that prints multiplying table of numbers up
to 100.
Same thing:
Example:
Write your own program block that prints first N Fibonacci numbers. N is
given by keyboard. Algorithm to calculate Fibonacci Numbers:
1, 1, 2, 3, 5, 8, 13, 21,...
#include <stdio.h>
int main () {
int N, i, f0 = 1, f1 = 1,f = 1;
printf ("\n Input amount of Fibonacci Numbers (N) : \n");
scanf ("%d",&N);
for (i = 0; i <= N; i++) {
if (i > 1) {
f = f1 + f0;
f0 = f1;
f1 = f;
}
printf ("Fibonnaci (%d) = %d \n", i , f);
}
return 0;
}
Example:
Write your own program which reads 2 real numbers and numeric operation
executed above them (+, -, /, *) (all given by keyboard). If the given
operation is different than allowed, program asks for new operation input.
#include <stdio.h>
int main(void) {
do {
printf("Input operation: ");
operation = getche();
printf("\n");
repeatOperationInput = 0;
switch(operation) {
// What if b == 0?
}
Lesson 14: Arrays
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:
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};
}
}
}
}
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];
max = array[i];
}
if (max < array[i]) {
max = array[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>
int main(void) {
int number, i;
int counter[UL – LL + 1] = { 0 };
do {
counter[number - LL]++;
}
}
}
Lesson 15: Matrixes and 2D Arrays
/* array of characters */
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;
}
}
min_maindg = mat[0][0];
//min el. is mat(0,0), this is why loop starts from 1
min_maindg = mat[i][i];
}
}
min_secdg = mat[i][NR_COL-i-1];
}
}
#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;
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];
do {
}
}
printf("%3d", mat[i][j]);
}
printf("\n");
}
// transposing
temp = mat[i][j];
mat[i][j] = mat[j][i];
mat[j][i] = temp;
}
}
printf("%3d", mat[i][j]);
}
printf("\n");
}
} // main
1 2
3 4
5 6
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];
sum[j] += mat[i][j];
}
}
prod[i] = 1;
prod[i] *= mat[i][j];
}
}
min_sum_ind = 0;
for (j = 1; j < NR_COL; j++) {
if (sum[j] < sum[min_sum_ind]) {
min_sum_ind = j;
}
}
max_prod_ind = i;
}
}
Shorter variant for storing elements and calculating sums & products:
prod[i] = 1;
for (j = 0; j < NR_COL; j++) {
sum[j] = 0;
}
sum[j] += mat[i][j];
}
}
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 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:
void twotimes(int 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:
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:
Example:
#include <stdio.h>
#include <math.h>
return sum;
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++ ) {
return sum;
Important:
Examples are translated using Microsoft Visual C++ compiler.
Example:
Result:
a = 6 *b = 6
a = 6 b = 1245052
&a = 1245052 &b = 1245048
Important:
Result:
Typical Mistakes:
scanf(“%d", n);
printf(“%d", &n);
Any declared array’s name can also be used as a pointer. Any pointer can
also be used as an array.
Result:
Important:
int *r = ++q;
//r address:1245028, value:1245048
//q address:1245032, value:1245048
Result:
(p + 1) = 1245052 *(p + 1) = 4
(p - 1) = 1245044 *(p - 1) = 2
q = 1245048 *q = 3
r = 1245048 *r = 3
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>
*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
}
float x, y; // x address:1245052,value:?
// y address:1245048,value:?
printf("x=%f y=%f",x,y);
// x address:1245052, value:1.755165
// y address:1245048, value:0.958851
Question:
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:
int min, i;
*nratorSum = nrator1*denom2+denom1*nrator2;
*denomSum = denom1*denom2;
} else {
i = min / 2;
while ( i >= 2) {
*nratorSum /= i;
*denomSum /= i;
--i;
}
}
}
...
res = p[0];
for (i = 1; i < length; i++)
if (p[i] > res)
res = p[i];
return res;
float res;
int i;
res = *p;
p++;
for (i = 1; i < length; i++, p++)
if (*p > res)
res = *p;
return res;
}
Important:
Example:
grade[flow[i] -1]++;
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:
Solution:
int i;
// if shifting right
// if shifting left
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;
}
}
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 lowermemory addresses).
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);
...
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)
sizeof(char)
+ sizeof(returning address 1)
+ 2 * sizeof(int)
+ 2 * sizeof(float)
+ sizeof(returning address 2)
--------------
= 25 byte
Lesson 19: C Programming Examples
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:
float mat[MAXROW][MAXCOL];
#include <stdio.h>
#define MAXROW 100
#define MAXCOL 100
float res;
int i;
int i, j;
float sum;
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) {
add=sumEl(row,col,MAXCOL,(float *) mat);
printf("\n\nSum of matrix
elements is %f", add );
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);
}
}
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;
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
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.
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];
}
}
Numerical Systems
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)
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)
Numeric Transformations
Example
- end of procedure
Example
Decimal 2 Binary
Example
- end of procedure
Example
Example
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
a) left from”,”
Example
Example
Hex 2 Decimal
Example
= 2540 , 33999919891357421875
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
Example
Example
math.h
Published Sunday, March 05, 2006 by Vurdlak | E-mail this post
#include <math.h>, syntax at the beginning of our code, means we automatically included
these (pre-defined) functions in our program:
stdlib.h
Published Sunday, March 05, 2006 by Vurdlak | E-mail this post
#include <stdlib.h>, syntax at the beginning of our code, means we automatically included
these (pre-defined) functions in our program:
string.h
Published Sunday, March 05, 2006 by Vurdlak | E-mail this post
#include <string.h>, syntax at the beginning of our code, means we automatically included
these (pre-defined) functions in our program:
ctype.h
Published Sunday, March 05, 2006 by Vurdlak | E-mail this post
#include <ctype.h>, syntax at the beginning of our code, means we automatically included
these (pre-defined) functions in our program:
#include <alloc.h>, syntax at the beginning of our code, means we automatically included
these (pre-defined) functions in our program: