Top Banner
Fundamentals of Mahmoud A. Eladawi
149

C programming language

Jul 02, 2015

Download

Engineering

Mahmoud Eladawi

This is a tutorial on fundamentals of C programming language.
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: C programming language

Fundamentals of

Mahmoud A. Eladawi

Page 2: C programming language

Fundamentals of C

Mahmoud A. Eladawi

For Computer Engineering Students 3rd year.

Page 3: C programming language

© 2014. Mahmoud A. EladawiFor computer Engineering students.These are just some notes on C.Some topics are not included, like pointers. Make sure to write down the labs.

Page 4: C programming language

C programs developmentphases

Page 5: C programming language

Overview

The program you use to convert C code into executable machine code is called a compiler

If you are working on a project in which several source code files (compiled before to object files) are involved or you used others’ library, a second program called the linker is invoked.

The purpose of the linker is to "connect“ the files and produce either an executable program or a library.

A library is a set of routines, not a standalone program, but can be used by other programs or programmers.

Page 6: C programming language

How that all happen?

Page 7: C programming language

How th

at all happ

en?

Page 8: C programming language

The Preprocessor

The Preprocessor accepts source code as input and is responsible for removing comments and  interpreting special preprocessor directives denoted by #.

For example 1. #include ‐‐ includes contents of a named file (it will put the contents of 

header files in the most top area of program before compiling). Files usually called header files. e.g:#include <math.h> ‐‐ standard library maths file. #include <stdio.h> ‐‐ standard library I/O file 

2.     #define ‐‐ defines a symbolic substitution (will replace each A with    100). It does not take a memory location, just a find and replace:#define A 100

Page 9: C programming language

Preprocessor programprocesses the code.

Loader puts program inmemory.

CPU takes eachinstruction and executes it, possibly storing new data values as the program executes.

Compiler creates object code and storesit on disk.

Linker links the objectcode with the libraries

Loader

Primary Memory

Compiler

Editor

Preprocessor

Linker

Primary Memory

.

.

.

.

.

.

.

.

.

.

.

.

Disk

Disk

Disk

CPU

Disk

DiskHo

w th

at all happ

en?

(more de

tails)

Page 10: C programming language

C programs structure

Page 11: C programming language

Structure of the programming

/*Author : Mahmoud Eladawi*/#include <stdio.h> /* comment */int z;int main(void){

printf("Hello\n");printf("Welcome to the 3rd year CE!\n");

return 0;} Hello

Welcome to the 3rd year CE!

tells compiler about standard input and output functions (i.e. printf + others)

main function

“begin”

“end”flag success to operating system

Page 12: C programming language

General rules of C

• C is case sensitive ‐ all keywords and Standard Library functions are lowercase• Each block star with ({) and end with (}) • All C Statements are free‐form

– Can begin and end on any line and in any column• C statements are always terminated with a semicolon “;”.• White space (blanks, tabs, new lines and comments) are ignored by the 

compiler• White space must separate keywords from other things. (e.g. int x : here we 

must use white space between keyword int and x) Otherwise they are optional. (e.g. x = y : here the paces are optional we can write x=y)

• White spaces cannot be used within literals. (i.e. numbers, strings, ..)• Comments: All text enclosed within “/* ‐‐‐‐‐ */”

EX: int x;  /*here we define x*/

‐ could be multiline.• In c, keywords and standard library are all in small case.

Page 13: C programming language
Page 14: C programming language

Writing C programs

Page 15: C programming language

Variables

• I need a memory location where I can use to store value and change it during runtime.

• To do that I need:• A variable name to reference it whenever I need it. (As I don’t want to 

remember the variable address, which changes every runtime.• A variable data type.

• Defining variable name and data type called variable definition.

For example:int b;

This line says, "I want to create a space called b that is able to hold one integer value." A variable has a name (in this case, b) and a type (in this case, int, an integer). 

Page 16: C programming language

Variable definition

• A variable definition means to tell the compiler where and how much to create the storage for the variable. A variable definition specifies a data type and contains a list of one or more variables of that type as follows:

Page 17: C programming language

voidenum

structures

arraysint

float

double

Data Types

Primitive (basic) User-Defined Data TypeNon-Primitive Data Type Empty Data Type

unions

typedef

Pointer

Data type defines the operations that could be applied on variable, size of variable, and the interpretation of memory content (of the variable address.)

char

Page 18: C programming language

Primitive (basic) typesType Size(bits) Range

signed char 8 -128 127

char 8 Depends on compiler (unsigned or signed by default)

unsigned char 8 0 255 int or signed int 16 -32768 32767unsigned int 16 0 65535

short int or signed short int

8 -128 127

unsigned short int

8 0 255

long int or signed long int

32 -2147483648 2147483647

unsigned long int

32 0 4294967295

float 32 -3.4E38 3.4E38double 64 -1.7E308 1.7E308long double 80 -3.4E4932 1.1E4932

Page 19: C programming language

Note:

• The data types sizes of short int, int, and long int are not fixed. They varies from platform to another. What C language require is:long int >=    int >=    short intso you have to know the platform you are working with. The last slide is valid for 32 bit windows and linux platform.

• We can write short instead of short int.and long instead of long integer.

Page 20: C programming language

Void 

S.N. Types and Description1 Function returns as void

There are various functions in C which do not return value or you can say they return void. A function with no return value has the return type as void. For example:  void exit (int status);

2 Function arguments as voidThere are various functions in C which do not accept any parameter. A function with no parameter can accept as a void. For example: int rand(void);

3 Pointers to voidA pointer of type void * represents the address of an object, but not its type. For example a memory allocation function void *malloc( size_t size ); returns a pointer to void which can be casted to any data type.

The void type specifies that no value is available. It is used in three kinds of situations:

Page 21: C programming language

Identifiers (Names)

Identifiers are names that are given to various program elements such as variables, function,.. :1. They must begin with a letter or underscore 

( _ ) and can be followed by ONLY any combination of letters (upper‐or lowercase), underscores, or the digits 0–9.

2. The name is not a C keyword

Page 22: C programming language
Page 23: C programming language

On the other hand, the following variable names are not valid for the stated reasons:

sum$value $ is not a valid character.piece flag  Embedded spaces are not permitted.3Spencer Variable names cannot start with a number.int ‘int’ is a reserved word.

The following is a list of valid variable names.sumpieceFlagIJ5x7Number_of_moves_sysflag

Identifiers

Page 24: C programming language

Initializing variables

• Variable initialization means putting (Assigning) the first data in the variable memory space.– Ex: 

int x;       /*variable definition*/x = 5; /*variable initialization*/

– Ex:int x =5;  /*defining and initializing variable at the same line*/

– Ex:int x=5, y=3;

/*defining multivariable with their initial values at the same line*/

Page 25: C programming language

Default values

• What if I defined value but did not assign a value for it?– Global, static local variables and pointers are initialized to Null (all bit set to zero).

• Because kernel initialize the .bss segment of program to 0s at startup time.

• Un‐initialized static and global variables are stores in .bss.

– Otherwise, the variables are not initialized and have random values. (The random past content in the memory location at the variable address).

• They are stored in Stack segment, which is not initialized by kernel.

Page 26: C programming language

Literals

• Integer literals:–An integer literal can be a decimal, octal, or hexadecimal constant. A prefix specifies the base or radix: 

• 0x or 0X for hexadecimal (i.e. 0xA4 or 0XA4),

• 0 for octal (i.e. 044)

• and nothing for decimal (i.e. 44).

Page 27: C programming language

• An integer literal can also have a suffix that is a combination of U (for unsigned) and L (for long). The suffix can be uppercase or lowercase and can be in any order.

• Examples:85 /* decimal */0213 /* octal */0x4b /* hexadecimal */30 /* int */30u /* unsigned int */30l /* long */30ul /* unsigned long */

Page 28: C programming language

• Floating point literals:– A floating‐point literal has an integer part, a decimal point, a fractional part, and an exponent part.

– It can be in one of two forms:• [+/‐] ##.##

10.5          ‐15.73            +12.0         ‐0.6

• [+/‐] ## [.##] e [+/‐] ## 105e‐1     ‐1573E‐2       +1.2e1        ‐6E‐1

o Note:oUse decimal point, exponential or both.o Exponential could be E or e

Page 29: C programming language

• Character literals:– A character literal can be 

• a plain character (e.g., 'x'), • an escape sequence (e.g., '\t'), 

Page 30: C programming language

• Some escape characters:

Escape Sequence Literal Characters placed into string\0 null character\a alert\b backspace\f form feed\n line feed (or newline in POSIX)\r carriage return (or newline in Mac OS 9 and earlier)\t horizontal tab\v vertical tab\" double quote (")\' single quote (')\\ backslash (\)

Page 31: C programming language

Hello World

/*Example*/

#include <stdio.h>

int main(){printf("\nHello\tWorld\n");

return 0;}

Page 32: C programming language

• String literal:– String literals are enclosed in double quotes "“– A string contains characters that are similar to character literals.

• “Hello world”– You can split string into many strings, and separate them with any white space“Hello world”  “Hello “         “world”“Hello “

“wold”“H” “ello ”    “world”• All produce the same output.

– You can write the string in many lines ending each line with \

• “Hello \world”

Page 33: C programming language

Where are variables defined?

1. A variable that is declared within a function is called local variable and it can be accessed within that scope only. That is applied also for the parameters of functions.

2. The variable that is declared outside any function is called global variable. Can be access anywhere in the code.

EX:

Int x=10;

int main(void) {int y =20; }void function1( float s ){} 

x: global variableY and s: local variables

Page 34: C programming language

Scope of variables

• If we used static with:

A)Local variable :the variable is still seen within the function or block only, but it remains in memory while program is running. So it holds its values all run time.

B)Global variable:the global variable cannot be declared with exern in other source file so, the global variable is seen within the file only. 

Page 35: C programming language

Scope of variables and life time

Scope mean where we can access the variable.

1. Global variables can be access in all program and remains in memory all the program run time.

2. Global variable with static keyword can be accessed within the file only and remains in memory all the program run time. 

3. Local variables are seen in their enclosing functions only and they are destroyed when the end of the function is reached } . Any variable declared between { } can be accessed inside these brackets {} only and they are destroyed when the end of the block is reached } 

4. Local variable with static keyword can be accessed within {  and } where they are defined only, and they remain in memory all program runtime. (it holds its values after we reach } and not destroyed)

Page 36: C programming language

Scope (Where we can access variable)

Life time what? How?

All Program All run time Global 1‐Define the variable out of all functions.2‐use extern in the other files you want to use the same variable in.

Block ( between { and } )

From beginning of block “{“ to the end of the block “}”

local variables or function parameters

Define the variable after “{“ So it is visible until we reach “}“

file All run time Static global  Define the variable out of all functions with keyword static

Block ( between {and } )

All run time Static local Define the variable after  “{“ with keyword static

Page 37: C programming language

Scope of variables

int x = 10;

int main(){int z =20;     /*this variable is seen in main() only*/ printf(“global is %i and local is %i”, x, z);     /*global variable x seen in all program*/

}

Void function1(){

printf (“out of scope is: %i”, z);    /*Error as z is out of enclosing {}*/

}

Page 38: C programming language

Scope of variables• To see the global variable declared in file in another file we should declare 

it in the top of file with keyword extern.• We can put that declaration with extern in header file and include it.

int x =10;

int main(void){

….

}

File1.c

Int main(void){printf(“%i”, x)     /*Error*/

}

extern int x;Int main(void){printf(“%i”, x)    /* output=10*/

}

File2.c

File3.c

Page 39: C programming language

EX:

Page 40: C programming language

EX:int function1 (void){

static int y=10;    /*this will be executed first time we call function1 only*/

y=y+1;return y;

}

int main(void){

int x;x= function1()   /*x=11*/x=function1()  /*x=12 not 11*/

}

Page 41: C programming language

EX:int function1 (void){

int y=10;    /*this will be executed every time we call function1 */y=y+1;return y;

}int main(void)}

int x;x= function1()   /*x=11*/x=function1()  /*x=11*/

}

Page 42: C programming language

Static int x =10;

Int main(void){

….

}

File1.c

extern int x;    /*Error as x was declared static*/Int main(void){printf(“%i”,x)    /* outpot=10*/

}

File2.c

EX

Page 43: C programming language

int i;                      /* Program scope */static int j;            /* File scope */func ( int k ) {      /* k is block scope */int m;                 /* Block scope */….}

EX

Page 44: C programming language

void  func(void) {

int a;{  

int b = 10;a = 15;

}printf ( “%d %d\n”,a,b);

}Won’t work!The variable b is inside a block and therefore is not visible to the rest of the function.

EX

Page 45: C programming language

• What if I declared local variable as the same name of global variables???

int x =10;

Int main(void){

int x=20;printf(“%i”, x);      /*will print 20 here the global variable is replaced by local x in this function only*/

}Void function1 (void){printf(“%i”,x);    /*this will print 20 !! */}

Page 46: C programming language

Summary so far

A local block is any portion of a C program that is enclosed by the left brace ({) and the right brace (}).

A C function contains left and right braces, and therefore anything between the two braces is contained in a local block.

An if statement or a switch statement can also contain braces, so the portion of code between these two braces would be considered a local block.

Additionally, you might want to create your own local block without the aid of a C function or keyword construct. This is perfectly legal.

Variables can be declared within local blocks, but they must be declared only at the beginning of a local block.

Variables declared in this manner are visible only within the local block. Duplicate variable names declared within a local block take precedence 

over variables with the same name declared outside the local block.

Page 47: C programming language

#include <stdio.h>

void main(){/* Begin local block for function main() */int test_var = 10;printf(“Test variable before the if statement: %d\n”, test_var);if (test_var > 5){

/* Begin local block for “if” statement */int test_var = 5;printf(“Test variable within the if statement: %d\n”,test_var);

Complete example:

Page 48: C programming language

{/* Begin independent local block (not tied toany function or keyword) */int test_var = 0;printf(“Test variable within the independent local block:%d\n”, test_var);}/* End independent local block */

}/* End local block for “if” statement */

printf(“Test variable after the if statement: %d\n”, test_var);}/* End local block for function main() */

Page 49: C programming language

‐This example program produces the following output:Test variable before the if statement: 10Test variable within the if statement: 5Test variable within the independent local block: 0Test variable after the if statement: 10

‐Notice that as each test_var was defined, it took precedence over the previously defined test_var. ‐Alsonotice that when the if statement local block had ended, the program had reentered the scope of the original test_var, and its value was 10.

Page 50: C programming language

• “Global” variables that do not have to be accessed from more than one file should be declared static and should not appear in a header file.

• Static variables are excellent for use as a local variable that does not lose its value when the function exits. For example, you might have a function that gets called numerous times, and that part of the function’s job is to count how many times it gets called. You cannot accomplish this task with a simple local variable because it will be uninitialized each time the function is entered.

• So why not just use a global variable instead? The static local variable and global variable are same, but the global variable is visible to all program functions, and the static local variable is visible to only a function or block.

• Global and static local variables reside in memory all run time, so it’s initialised one time only in each program run, while local variables is erased from memory when its containing block is ended by } , so they are reinitialised every time their block starts with {.

Summary so far cont.

Page 51: C programming language

Type Conversion

• When variables of one type are mixed with variables of another type, a type conversion will occur from smaller type to bigger type (not to lose data). If they are same type the value will be the same type too.

Page 52: C programming language

1. char and short operands are converted to int

2. Lower data types are converted to the higher data types and result is of higher type.

3. The conversions between unsigned and signed types may not yield intuitive results.

4. Examplefloat f; double d; long l; int i; short s;d + f f will be converted to doublei / s s will be converted to intl / i i is converted to long; longresult

Hierarchy

Double

float

long

Int

Short and char

Page 53: C programming language

• In an assignment statement, the type conversion rule is easy: The value of the right side (expression side) of the assignment is converted to the type of the left side (target variable)

• The default type for integral constant is int, and the default type of real constant is doubleex:  char x = 23;       /*here conversion from type int to char occurred*/ex: float y=35.5 ;   /*here conversion from type double to float occurred*/

How to change the explicitly default (or any) data type?A)suffixes : to covert data constants only.b)casting : to convert data constants and variables.

Page 54: C programming language

A)Suffixes:

Page 55: C programming language
Page 56: C programming language

B)Casting:

#include <stdio.h>

int main(void)      /* print i and i/2 with fractions */{

printf(''%f\n", 5/2);           /*print 2.0 */Printf(“%f\n”, (float)5/2)            /*this prints2.5*/return 0;

}

Page 57: C programming language

Conversion rules: from

to

Page 58: C programming language

Qualifiers of data types

1. Const: If we used const with variable this means that the value of the variable cannot be changed during program execution, you can only assign it a value at definition.

Ex:   const int x;x=10;   /*Error*/const y =20;  /*legal*/

2. Volatile:Sometimes I need to check if the value of the variables is changed by external factor, such as if the variable is a buffer of I/P device.If I tried to get this value normally during program execution, the output will be the last value I have assigned to the variable even if it has been changed by external device after that.So to make the compiler check (physically) the value of the variable in memory even if I did not change it’s value we use volatile

Ex:  volatile int buffer ;

Page 59: C programming language

Qualifiers of data types

3.    register:If register is used with variable, that tells the compiler to store the variable in a register not in main memory. This make the program far faster specially if used in variables of loops.

Ex: register int i; for (i=0; i<1034; i++){}

4. extern : done!!!

5. static done!!

Page 60: C programming language

Operators

Note:‐) int c =A++   /* c=10 A=11*/‐) int c =++A    /*A=11 c=11*/

‐In C no Boolean type, so we use integer or character if =0 so false other is true !So 1,3,68,.. Is like true !

Page 61: C programming language
Page 62: C programming language

Note:

• As there is no bool type in C. false is always 0 and anything else is true.

• Logical operators give 0 if relation is false and 1 if it’s true. 

Page 63: C programming language
Page 64: C programming language
Page 65: C programming language
Page 66: C programming language

whiledo..whileforExiting from a loop      (break,continue, goto)

Loops

Page 67: C programming language

while

Page 68: C programming language

while

Page 69: C programming language

while

Page 70: C programming language

while

Page 71: C programming language

do…while

Page 72: C programming language

do…while

Page 73: C programming language

do…while

Page 74: C programming language

do…while

Page 75: C programming language

for Loop

Page 76: C programming language

for Loop

Page 77: C programming language

for Loop

Page 78: C programming language

for Loop

Page 79: C programming language
Page 80: C programming language

for Loop

Page 81: C programming language

for Loop

Page 82: C programming language

break Statement

• It is an jump instruction and can be used inside the switch and loop statements.

• The execution of the break statements causes the control transfer to the statement immediately after the loop.

Page 83: C programming language

break Statement

Page 84: C programming language

break Statement

Page 85: C programming language

break Statement

Page 86: C programming language

break Statement

Page 87: C programming language

break Statement

Page 88: C programming language

break Statement

Page 89: C programming language

continue Statement

• It is a jump statement.• It is used only inside the loop.• Its execution does not exit from the loop but escape the loop for that iteration and transfer the control back to the loop for the new iteration.

Page 90: C programming language

continue Statement

Page 91: C programming language

continue Statement

Page 92: C programming language

continue Statement

Page 93: C programming language

continue Statement

Page 94: C programming language

continue Statement

Page 95: C programming language

goto Statement

• It is used the alter the normal sequence of flow by transferring the control to some other part of the program unconditionally.

• It is followed by the label statement which determine the instruction to be handled next after the execution of the goto statement.

Page 96: C programming language

goto Statement

Page 97: C programming language

goto Statement

Page 98: C programming language

goto Statement

Page 99: C programming language

goto Statement

Page 100: C programming language

Logical expressions If statementSwitch statement

Selection Statements

Page 101: C programming language

Flow of Control

• Unless specified , the order of statement execution through a C program is linear: one statement after the other, in sequence.

• Some programming statements modify that order, allowing us to:– decide whether or not to execute a particular statement, or perform a statement over and over, repetitively

Page 102: C programming language

102

Flow of Control

• These decisions are based on a boolean Or logical expression (also called a condition) that evaluates to true or false

• The order of statement execution is called the flow of control

Page 103: C programming language

Flow of Control

Sequential Flow 

Page 104: C programming language

Flow of Control

Selection Statements

Page 105: C programming language

Flow of Control

Repetition

Page 106: C programming language

Logical Expression

• Logical expression is an expression which uses one or more logical operators, e.g.,(temperature > 90.0 && humidity > 0.90)!(n <= 0 || n >= 100).

The output of the logical expression is the booleanvalue either true or false.

Page 107: C programming language

if Statements

• If statements consists of boolean expression followed by one or more statements.

• If the boolean expression evaluates to true, the statements inside the block get executed otherwise the first statement outside the block get executed.

• The false value is 0 and all the other values are evaluated as true in C.

Page 108: C programming language

if Statement

• The syntax of an If statement in C Program is given below

Page 109: C programming language

if Statements

Page 110: C programming language

if Statement(Example)

Page 111: C programming language

Output

Page 112: C programming language

if…else  Statement

• If statements can be followed by the optional else statements, which get executed when the boolean expression is false.

Page 113: C programming language

if…else  Statement

Page 114: C programming language

if…else  Statement(Example)

Page 115: C programming language

if…else  Statement

Page 116: C programming language

if…else if…else  Statement

• If statement can be followed by optional else if..else statement, which is very useful to test various conditions using single if…else if statement.

• Following things should be kept in mind– An if can have zero or one else's and it must come after any   else if's.

– An if can have zero to many else if's and they must come before the else.

– Once an else if succeeds, none of the remaining else if's or else's will be tested.

Page 117: C programming language

if…else if…else  Statement

Page 118: C programming language

if…else if…else  Statement(Example)

#include <stdio.h>#include<conio.h>

int main (){int a = 100;if( a == 10 ){printf("Value of a is 10\n" );

}else if( a == 20 ){printf("Value of a is 20\n" );

}

else if( a == 30 ){printf("Value of a is 30\n" );

}else{printf("None of the values is matching\n" );

}printf("Exact value of a is: %d\n", a );

getch();return 0;

}

Page 119: C programming language

if…else if…else  Statement

Page 120: C programming language

Nested if Statements

• It is always legal in C programming to nest if‐else statements, which means we can use one if or else if statement inside another if or else if statement(s).

Page 121: C programming language

Nested if Statements

#include <stdio.h>#include <conio.h>int main (){int a = 100;int b = 200;if( a == 100 ){if( b == 200 ){printf("Value of a is 100 and 

b is 200\n" );

}}

printf("Exact value of a is : %d\n", a );

printf("Exact value of b is : %d\n", b );

getch();return 0;

}

Page 122: C programming language

Nested if Statements

Page 123: C programming language

Switch Statement

• A switch statement allows a variable to be tested for equality against a list of values. 

• Each value is called a case, and the variable being switched on is checked for each switch case.

• The following rules apply to a switch statement:– The expression used in a switch statement must have an integral or enumerated type.

– You can have any number of case statements within a switch. Each case is followed by the value to be compared to and a colon.

– The constant‐expression for a case must be the same data type as the variable in the switch, and it must be a constant or a literal.

Page 124: C programming language

Switch Statement– When the variable being switched on is equal to a case, the statements following that case will execute until a break statement is reached.

– When a break statement is reached, the switch terminates, and the flow of control jumps to the next line following the switch statement.

– Not every case needs to contain a break. If no break appears, the flow of control will fall through to subsequent cases until a break is reached.

– A switch statement can have an optional default case, which must appear at the end of the switch. The default case can be used for performing a task when none of the cases is true. No break is needed in the default case.

Page 125: C programming language

Switch Statement

Page 126: C programming language

Switch Statement

Page 127: C programming language

Switch Statement

#include <stdio.h>#include <conio.h>int main (){char grade = 'B';switch(grade){case 'A' :printf("Excellent!\n" );break;

case 'B' :case 'C' :printf("Well done\n" );break;

case 'D' :printf("You passed\n" );break;

case 'F' :printf("Better try again\n" );break;

default :printf("Invalid grade\n" );

}printf("Your grade is  %c\n", grade );

getch();return 0;

}

Page 128: C programming language

Switch Statement

Page 129: C programming language

The general form of a function definition in C programming language is as follows:

return_type function_name ( parameter list ){body of the function

}

Functions:

Page 130: C programming language

A function definition in C programming language consists of a function header and a function body. Here are all the parts of a function:• Return Type: A function may return a value. The return_type is the data type

of the value the function returns. Some functions perform the desired operations without returning a value. In this case, the return_type is the keyword void.

• Function Name: This is the actual name of the function. The function name and the parameter list together constitute the function signature.

• Parameters: A parameter is like a placeholder. When a function is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument. The parameter list refers to the type, order, and number of the parameters of a function. Parameters are optional; that is, a function may contain no parameters.

• Function Body: The function body contains a collection of statements that define what the function does.If function returns value, we use return keyword.

Functions:

Page 131: C programming language

int mult (int x, int y) /* the function return int{ and takes two integer

parameters x and y */

return x * y; /*the function returns the product of two numbers*/

}

Functions - Example:

Page 132: C programming language

#include <stdio.h>

int main(){

int x =2, y=3, result;result = mult (x, y); /*Here the function mult is not known yet, as it’s

under the definition of main function*/}

int mult (int x, int y){

return x * y;}

Functions - Example:

Page 133: C programming language

1 – Writing the definition of mult function above main function:

#include <stdio.h>

int mult (int x, int y){

return x * y;}

int main(){

int x, y, result;result = mult (x, y);

}

To solve this problem we have 2 solutions:

Page 134: C programming language

2- Declare the function (The common one)return_type function_name ( parameter list with or without names)

#include <stdio.h>

int mult (int , int )

int main(){int x, y, result;result = mult (x, y); /*Now mult function is known from the declaration*/

}

int mult (int x, int y){return x * y;

}

To solve this problem we have 2 solutions:

Note that the declaration is same as function header.We tell the compiler that there is fuctioncalled mult defined else where.

Page 135: C programming language

All arrays consist of contiguous memory locations.

The lowest address corresponds to the first element and the highest address to the last element.

Arrays:

Page 136: C programming language

Declaring Arrays:

To declare an array in C, a programmer specifies the type of the elements and the number of elements required by an array as follows:

type arrayName [ arraySize ];

For example, to declare a 10-element array called balance of type double, use this statement:

double balance[10];

To access any element of the array we specify its index:double salary = balance[9];

Page 137: C programming language

Assigning values to array elements:

You can initialize array in C either one by one or using a single statement as follows:

1- one by one: (Index starts with 0)balance[0] = 1000.0;balance[1] = 2.0;balance[2] = 3.4;..balance[9] = 20.5;

Page 138: C programming language

Assigning values to array elements:

2 – one statement (in initialization):double balance[10] = {1000.0, 2.0, 3.4, 7.0, 50.0, 55.5, 60.3,

210.0, .01, 20.2};

-We can neglect array size at definition in this method:

double balance[] = {1000.0, 2.0, 3.4, 7.0, 50.0, 55.5, 60.3, 210.0, .01, 20.2};

-Here compiler determines the size of array enough to hold the initialization created. (Here 10)

Page 139: C programming language

Note:

• Suppose, you declared the array of 10 students. For example: arr[10]. You can use array members from arr[0] to arr[9]. But, if you tried to use element arr[10], arr[13] etc. Compiler may not show error using these elements but, may cause fatal error during program execution.

• If we initialized the array with elements less than its size, the rest of elements will be filled with 0

int Array[5] = {1, 2, 3} /*Here value of elements of Array[3] and Array[4] will be assigned value 0 */

• Search for multi-dimensional arrays.

Page 140: C programming language

Structures:

Page 141: C programming language

Structures:

We can define variables Point1 and Point2 of type struct point in two ways:

struct point{

int x;int y;

};

struct point Point1;struct point Point2;

struct point{

int x;int y;

} Point1, Point2;Same As

struct{

int x;int y;

} Point1, Point2;

We can neglect struct name in

this method

Page 142: C programming language

Assigning values to members:

1-Accessing each member:

Point1.x=10;Point1.y=12;Point2.x=20;Point2.y=22;

2- At definition time: (same order of members)

struct point Point1={10, 12};struct point Point2={20, 22};

or:

struct{

int x;int y;

} Point1 ={10, 12}, Point2 ={20, 22};

Page 143: C programming language

Structures:

Page 144: C programming language

Structures:

Page 145: C programming language

Structures:

Page 146: C programming language

Using typedef with structures:

typedef struct {type member1;type member2; …

} NewTypeName ;

Example:typedef struct{

int x;int y;

} point;

point Point1 ={10, 12}; /*Now we use Point as new type*/point Point2 ={20, 22};

Page 147: C programming language

How structure are stored

In order to align the data in memory, one or more empty bytes (addresses) are inserted (or left empty) between memory addresses which are allocated for other structure members while memory allocation. This concept is called structure padding.

Architecture of a computer processor is such a way that it can read 1 word (4 byte in 32 bit processor) from memory at a time.

To make use of this advantage of processor, data are always aligned as 4 bytes package which leads to insert empty addresses between other member’s address.

Because of this structure padding concept in C, size of the structure is always not same as what we think.

Page 148: C programming language

How structure are stored

For example, please consider below structure that has 5 members.

struct student{

int id1;int id2;char a;char b;float percentage;

};

Page 149: C programming language

The End

Mahmoud Eladawi