SlideShare a Scribd company logo
Fundamentals of 
Mahmoud A. Eladawi
Fundamentals of C 
Mahmoud A. Eladawi 
For Computer Engineering Students 3rd year.
© 2014. Mahmoud A. Eladawi 
For computer Engineering students. 
These are just some notes on C. 
Some topics are not included, like pointers. Make sure to write down the 
labs.
C programs development 
phases
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.
How that all happen?
How that all happen?
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
Preprocessor program 
processes the code. 
Compiler creates object 
code and stores 
it on disk. 
Linker links the object 
code with the libraries 
Loader puts program in 
memory. 
CPU takes each 
instruction and executes 
it, possibly storing new 
data values as the 
program executes. 
Editor 
Disk How that all happen? 
Preprocessor 
Loader 
Primary Memory 
Compiler 
Linker 
Primary Memory 
... 
... 
... 
... 
Disk 
Disk 
Disk 
CPU 
Disk 
(more details)
C programs structure
Structure of the programming 
tells compiler about standard input and output functions (i.e. printf + others) 
/*Author : Mahmoud Eladawi*/ 
#include <stdio.h> /* comment */ 
int z; 
int main(void) 
{ 
printf("Hellon"); 
printf("Welcome to the 3rd year CE!n"); 
return 0; 
} Hello 
Welcome to the 3rd year CE! 
main function 
“begin” 
“end” 
flag success to 
operating 
system
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.
C programming language
Writing C programs
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).
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:
void 
enum 
int arrays 
structures 
float 
double 
Data Types 
Primitive (basic) Non-Primitive Data Type User-Defined Data Type Empty Data Type 
unions 
typedef 
Pointer 
char 
Data type defines the operations that could be applied on variable, size of variable, and the 
interpretation of memory content (of the variable address.)
Primitive (basic) types 
Type 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 32767 
unsigned 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.4E38 
double 64 -1.7E308 1.7E308 
long double 80 -3.4E4932 1.1E4932
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 int 
so 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.
Void 
The void type specifies that no value is available. It is used in three kinds of situations: 
S.N. Types and Description 
1 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 void 
There 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 void 
A 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.
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
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. 
sum 
pieceFlag 
I 
J5x7 
Number_of_moves 
_sysflag 
Identifiers
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*/
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.
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).
• 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 */
• 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. 
oExponential could be E or e
• Character literals: 
– A character literal can be 
• a plain character (e.g., 'x'), 
• an escape sequence (e.g., 't'),
• 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 ()
/*Example*/ 
#include <stdio.h> 
int main() 
{ 
printf("nHellotWorldn"); 
return 0; 
} 
Hello World
• 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”
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 variable 
Y and s: local variables
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.
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)
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
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 {}*/ 
}
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. 
File1.c 
int x =10; 
int main(void) 
{ 
…. 
} 
File2.c 
Int main(void) 
{ 
printf(“%i”, x) /*Error*/ 
} 
File3.c 
extern int x; 
Int main(void) 
{ 
printf(“%i”, x) /* output=10*/ 
}
EX:
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*/ 
}
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*/ 
}
File1.c 
Static int x =10; 
Int main(void) 
{ 
…. 
} 
File2.c 
extern int x; /*Error as x was declared static*/ 
Int main(void) 
{ 
printf(“%i”,x) /* outpot=10*/ 
} 
EX
EX 
int i; /* Program scope */ 
static int j; /* File scope */ 
func ( int k ) { /* k is block scope */ 
int m; /* Block scope */ 
…. 
}
EX 
void func(void) 
{ 
int a; 
{ 
int b = 10; 
a = 15; 
} 
printf ( “%d %dn”,a,b); 
} 
Won’t work! 
The variable b is inside a block and therefore is not visible to the 
rest of the function.
• 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 !! */ 
}
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.
Complete example: 
#include <stdio.h> 
void main() 
{ 
/* Begin local block for function main() */ 
int test_var = 10; 
printf(“Test variable before the if statement: %dn”, test_var); 
if (test_var > 5) 
{ 
/* Begin local block for “if” statement */ 
int test_var = 5; 
printf(“Test variable within the if statement: %dn”, 
test_var);
{ 
/* Begin independent local block (not tied to 
any function or keyword) */ 
int test_var = 0; 
printf(“Test variable within the independent local block:%dn”, test_var); 
} 
/* End independent local block */ 
} 
/* End local block for “if” statement */ 
printf(“Test variable after the if statement: %dn”, test_var); 
} 
/* End local block for function main() */
‐This example program produces the following output: 
Test variable before the if statement: 10 
Test variable within the if statement: 5 
Test variable within the independent local block: 0 
Test 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.
Summary so far cont. 
• “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 {.
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.
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. Example 
float f; double d; long l; 
int i; short s; 
d + f f will be converted to double 
i / s s will be converted to int 
l / i i is converted to long; long 
result 
Hierarchy 
Double 
float 
long 
Int 
Short and 
char
• 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 double 
ex: 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.
A)Suffixes:
C programming language
B)Casting: 
#include <stdio.h> 
int main(void) /* print i and i/2 with fractions */ 
{ 
printf(''%fn", 5/2); /*print 2.0 */ 
Printf(“%fn”, (float)5/2) /*this prints2.5*/ 
return 0; 
}
Conversion rules: from 
to
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 ;
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!!
Operators 
‐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 ! 
Note: 
‐) int c =A++ /* c=10 A=11*/ 
‐) int c =++A /*A=11 c=11*/
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.
C programming language
C programming language
C programming language
Loops 
while 
do..while 
for 
Exiting from a loop (break,continue, goto)
while
while
while
while
do…while
do…while
do…while
do…while
for Loop
for Loop
for Loop
for Loop
C programming language
for Loop
for Loop
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.
break Statement
break Statement
break Statement
break Statement
break Statement
break Statement
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.
continue Statement
continue Statement
continue Statement
continue Statement
continue Statement
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.
goto Statement
goto Statement
goto Statement
goto Statement
Selection Statements 
Logical expressions 
 If statement 
Switch statement
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
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
Flow of Control 
Sequential Flow
Flow of Control 
Selection Statements
Flow of Control 
Repetition
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 boolean 
value either true or false.
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.
if Statement 
• The syntax of an If statement in C Program is 
given below
if Statements
if Statement(Example)
Output
if…else Statement 
• If statements can be followed by the optional 
else statements, which get executed when the 
boolean expression is false.
if…else Statement
if…else Statement(Example)
if…else Statement
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.
if…else if…else Statement
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 10n" ); 
} 
else if( a == 20 ) 
{ 
printf("Value of a is 20n" ); 
} 
else if( a == 30 ) 
{ 
printf("Value of a is 30n" ); 
} 
else 
{ 
printf("None of the values is 
matchingn" ); 
} 
printf("Exact value of a is: %dn", a 
); 
getch(); 
return 0; 
}
if…else if…else Statement
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).
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 200n" ); 
} 
} 
printf("Exact value of a is : %dn", 
a ); 
printf("Exact value of b is : 
%dn", b ); 
getch(); 
return 0; 
}
Nested if Statements
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.
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.
Switch Statement
Switch Statement
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 donen" ); 
break; 
case 'D' : 
printf("You passedn" ); 
break; 
case 'F' : 
printf("Better try againn" ); 
break; 
default : 
printf("Invalid graden" ); 
} 
printf("Your grade is %cn", grade 
); 
getch(); 
return 0; 
}
Switch Statement
Functions: 
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: 
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 - Example: 
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: 
#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; 
}
To solve this problem we have 2 solutions: 
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: 
2- Declare the function (The common one) 
return_type function_name ( parameter list with or without names) 
Note that the declaration is same as function 
#include <stdio.h> 
header. 
We tell the compiler that there is fuction 
int mult (int , int ) 
called mult defined else where. 
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; 
}
Arrays: 
All arrays consist of contiguous memory locations. 
The lowest address corresponds to the first element and the highest 
address to the last element.
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];
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;
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)
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.
Structures:
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 
{ 
We can neglect 
struct name in 
this method 
int x; 
int y; 
} Point1, Point2;
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};
Structures:
Structures:
Structures:
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};
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.
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; 
};
The End 
Mahmoud Eladawi

More Related Content

PPTX
Core java
PPTX
Network topology
PPTX
Microsoft word for beginners
PPTX
Go Programming language, golang
PPTX
MEDICAL ETHICS 2.pptx
PPTX
Coordinate geometry
PPT
Introduction to C Programming
PPTX
Oop c++class(final).ppt
Core java
Network topology
Microsoft word for beginners
Go Programming language, golang
MEDICAL ETHICS 2.pptx
Coordinate geometry
Introduction to C Programming
Oop c++class(final).ppt

What's hot (20)

PPTX
Basic Input and Output
PPTX
Data Type in C Programming
PPTX
PPTX
Introduction to C programming
PPTX
C programming language tutorial
PPT
C program
PPT
File handling in c
PPT
Programming in c
PPTX
PPT
RECURSION IN C
PPT
Introduction to c programming
PPTX
Introduction to programming
PPTX
Header files of c++ unit 3 -topic 3
PPTX
6.applet programming in java
PPTX
Constants, Variables, and Data Types
PPT
Unit 4 Foc
PPTX
PPTX
Input output statement in C
Basic Input and Output
Data Type in C Programming
Introduction to C programming
C programming language tutorial
C program
File handling in c
Programming in c
RECURSION IN C
Introduction to c programming
Introduction to programming
Header files of c++ unit 3 -topic 3
6.applet programming in java
Constants, Variables, and Data Types
Unit 4 Foc
Input output statement in C
Ad

Similar to C programming language (20)

PPTX
Fundamentals of Programming Constructs.pptx
PPT
Lecture 01 2017
PPTX
UNIT 5 C PROGRAMMING, PROGRAM STRUCTURE
PPTX
A Comprehensive Guide to C Programing Basics, Variable Declarations, Input/O...
PPTX
C++ Unit 1PPT which contains the Introduction and basic o C++ with OOOps conc...
PPT
Escape Sequences and Variables
PDF
UNIT1 PPS of C language for first year first semester
PDF
C notes.pdf
PDF
7986-lect 7.pdf
PPTX
venkatesh.pptx
PPTX
PPS_unit_2_gtu_sem_2_year_2023_GTUU.pptx
PPTX
4 Introduction to C.pptxSSSSSSSSSSSSSSSS
PPTX
C PROGRAMMING LANGUAGE.pptx
PDF
introduction to programming using ANSI C
PPTX
C lang7age programming powerpoint presentation
PPTX
Introduction Of C++
DOCX
fds unit1.docx
PPTX
COMPUTER PROGRAMMING LANGUAGE C++ 1.pptx
PPT
Getting started with c++
PPT
Getting started with c++
Fundamentals of Programming Constructs.pptx
Lecture 01 2017
UNIT 5 C PROGRAMMING, PROGRAM STRUCTURE
A Comprehensive Guide to C Programing Basics, Variable Declarations, Input/O...
C++ Unit 1PPT which contains the Introduction and basic o C++ with OOOps conc...
Escape Sequences and Variables
UNIT1 PPS of C language for first year first semester
C notes.pdf
7986-lect 7.pdf
venkatesh.pptx
PPS_unit_2_gtu_sem_2_year_2023_GTUU.pptx
4 Introduction to C.pptxSSSSSSSSSSSSSSSS
C PROGRAMMING LANGUAGE.pptx
introduction to programming using ANSI C
C lang7age programming powerpoint presentation
Introduction Of C++
fds unit1.docx
COMPUTER PROGRAMMING LANGUAGE C++ 1.pptx
Getting started with c++
Getting started with c++
Ad

Recently uploaded (20)

PDF
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
PDF
July 2025 - Top 10 Read Articles in International Journal of Software Enginee...
PPTX
Strings in CPP - Strings in C++ are sequences of characters used to store and...
PPTX
additive manufacturing of ss316l using mig welding
PPTX
Geodesy 1.pptx...............................................
PPTX
bas. eng. economics group 4 presentation 1.pptx
PPTX
M Tech Sem 1 Civil Engineering Environmental Sciences.pptx
PDF
Embodied AI: Ushering in the Next Era of Intelligent Systems
PPTX
MCN 401 KTU-2019-PPE KITS-MODULE 2.pptx
PPTX
Infosys Presentation by1.Riyan Bagwan 2.Samadhan Naiknavare 3.Gaurav Shinde 4...
PPTX
Construction Project Organization Group 2.pptx
PPTX
KTU 2019 -S7-MCN 401 MODULE 2-VINAY.pptx
PPTX
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
PDF
Structs to JSON How Go Powers REST APIs.pdf
PDF
Mohammad Mahdi Farshadian CV - Prospective PhD Student 2026
PPTX
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
PDF
PPT on Performance Review to get promotions
PPTX
Lecture Notes Electrical Wiring System Components
PDF
Arduino robotics embedded978-1-4302-3184-4.pdf
PDF
PRIZ Academy - 9 Windows Thinking Where to Invest Today to Win Tomorrow.pdf
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
July 2025 - Top 10 Read Articles in International Journal of Software Enginee...
Strings in CPP - Strings in C++ are sequences of characters used to store and...
additive manufacturing of ss316l using mig welding
Geodesy 1.pptx...............................................
bas. eng. economics group 4 presentation 1.pptx
M Tech Sem 1 Civil Engineering Environmental Sciences.pptx
Embodied AI: Ushering in the Next Era of Intelligent Systems
MCN 401 KTU-2019-PPE KITS-MODULE 2.pptx
Infosys Presentation by1.Riyan Bagwan 2.Samadhan Naiknavare 3.Gaurav Shinde 4...
Construction Project Organization Group 2.pptx
KTU 2019 -S7-MCN 401 MODULE 2-VINAY.pptx
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
Structs to JSON How Go Powers REST APIs.pdf
Mohammad Mahdi Farshadian CV - Prospective PhD Student 2026
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
PPT on Performance Review to get promotions
Lecture Notes Electrical Wiring System Components
Arduino robotics embedded978-1-4302-3184-4.pdf
PRIZ Academy - 9 Windows Thinking Where to Invest Today to Win Tomorrow.pdf

C programming language

  • 2. Fundamentals of C Mahmoud A. Eladawi For Computer Engineering Students 3rd year.
  • 3. © 2014. Mahmoud A. Eladawi For computer Engineering students. These are just some notes on C. Some topics are not included, like pointers. Make sure to write down the labs.
  • 5. 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.
  • 6. How that all happen?
  • 7. How that all happen?
  • 8. 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
  • 9. Preprocessor program processes the code. Compiler creates object code and stores it on disk. Linker links the object code with the libraries Loader puts program in memory. CPU takes each instruction and executes it, possibly storing new data values as the program executes. Editor Disk How that all happen? Preprocessor Loader Primary Memory Compiler Linker Primary Memory ... ... ... ... Disk Disk Disk CPU Disk (more details)
  • 11. Structure of the programming tells compiler about standard input and output functions (i.e. printf + others) /*Author : Mahmoud Eladawi*/ #include <stdio.h> /* comment */ int z; int main(void) { printf("Hellon"); printf("Welcome to the 3rd year CE!n"); return 0; } Hello Welcome to the 3rd year CE! main function “begin” “end” flag success to operating system
  • 12. 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.
  • 15. 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).
  • 16. 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:
  • 17. void enum int arrays structures float double Data Types Primitive (basic) Non-Primitive Data Type User-Defined Data Type Empty Data Type unions typedef Pointer char Data type defines the operations that could be applied on variable, size of variable, and the interpretation of memory content (of the variable address.)
  • 18. Primitive (basic) types Type 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 32767 unsigned 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.4E38 double 64 -1.7E308 1.7E308 long double 80 -3.4E4932 1.1E4932
  • 19. 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 int so 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.
  • 20. Void The void type specifies that no value is available. It is used in three kinds of situations: S.N. Types and Description 1 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 void There 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 void A 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.
  • 21. 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
  • 23.  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. sum pieceFlag I J5x7 Number_of_moves _sysflag Identifiers
  • 24. 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*/
  • 25. 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.
  • 26. 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).
  • 27. • 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 */
  • 28. • 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. oExponential could be E or e
  • 29. • Character literals: – A character literal can be • a plain character (e.g., 'x'), • an escape sequence (e.g., 't'),
  • 30. • 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 ()
  • 31. /*Example*/ #include <stdio.h> int main() { printf("nHellotWorldn"); return 0; } Hello World
  • 32. • 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”
  • 33. 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 variable Y and s: local variables
  • 34. 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.
  • 35. 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)
  • 36. 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
  • 37. 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 {}*/ }
  • 38. 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. File1.c int x =10; int main(void) { …. } File2.c Int main(void) { printf(“%i”, x) /*Error*/ } File3.c extern int x; Int main(void) { printf(“%i”, x) /* output=10*/ }
  • 39. EX:
  • 40. 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*/ }
  • 41. 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*/ }
  • 42. File1.c Static int x =10; Int main(void) { …. } File2.c extern int x; /*Error as x was declared static*/ Int main(void) { printf(“%i”,x) /* outpot=10*/ } EX
  • 43. EX int i; /* Program scope */ static int j; /* File scope */ func ( int k ) { /* k is block scope */ int m; /* Block scope */ …. }
  • 44. EX void func(void) { int a; { int b = 10; a = 15; } printf ( “%d %dn”,a,b); } Won’t work! The variable b is inside a block and therefore is not visible to the rest of the function.
  • 45. • 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 !! */ }
  • 46. 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.
  • 47. Complete example: #include <stdio.h> void main() { /* Begin local block for function main() */ int test_var = 10; printf(“Test variable before the if statement: %dn”, test_var); if (test_var > 5) { /* Begin local block for “if” statement */ int test_var = 5; printf(“Test variable within the if statement: %dn”, test_var);
  • 48. { /* Begin independent local block (not tied to any function or keyword) */ int test_var = 0; printf(“Test variable within the independent local block:%dn”, test_var); } /* End independent local block */ } /* End local block for “if” statement */ printf(“Test variable after the if statement: %dn”, test_var); } /* End local block for function main() */
  • 49. ‐This example program produces the following output: Test variable before the if statement: 10 Test variable within the if statement: 5 Test variable within the independent local block: 0 Test 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.
  • 50. Summary so far cont. • “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 {.
  • 51. 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.
  • 52. 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. Example float f; double d; long l; int i; short s; d + f f will be converted to double i / s s will be converted to int l / i i is converted to long; long result Hierarchy Double float long Int Short and char
  • 53. • 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 double ex: 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.
  • 56. B)Casting: #include <stdio.h> int main(void) /* print i and i/2 with fractions */ { printf(''%fn", 5/2); /*print 2.0 */ Printf(“%fn”, (float)5/2) /*this prints2.5*/ return 0; }
  • 58. 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 ;
  • 59. 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!!
  • 60. Operators ‐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 ! Note: ‐) int c =A++ /* c=10 A=11*/ ‐) int c =++A /*A=11 c=11*/
  • 62. 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.
  • 66. Loops while do..while for Exiting from a loop (break,continue, goto)
  • 67. while
  • 68. while
  • 69. while
  • 70. while
  • 82. 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.
  • 89. 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.
  • 95. 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.
  • 100. Selection Statements Logical expressions  If statement Switch statement
  • 101. 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
  • 102. 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
  • 103. Flow of Control Sequential Flow
  • 104. Flow of Control Selection Statements
  • 105. Flow of Control Repetition
  • 106. 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 boolean value either true or false.
  • 107. 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.
  • 108. if Statement • The syntax of an If statement in C Program is given below
  • 111. Output
  • 112. if…else Statement • If statements can be followed by the optional else statements, which get executed when the boolean expression is false.
  • 116. 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.
  • 118. 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 10n" ); } else if( a == 20 ) { printf("Value of a is 20n" ); } else if( a == 30 ) { printf("Value of a is 30n" ); } else { printf("None of the values is matchingn" ); } printf("Exact value of a is: %dn", a ); getch(); return 0; }
  • 120. 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).
  • 121. 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 200n" ); } } printf("Exact value of a is : %dn", a ); printf("Exact value of b is : %dn", b ); getch(); return 0; }
  • 123. 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.
  • 124. 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.
  • 127. 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 donen" ); break; case 'D' : printf("You passedn" ); break; case 'F' : printf("Better try againn" ); break; default : printf("Invalid graden" ); } printf("Your grade is %cn", grade ); getch(); return 0; }
  • 129. Functions: The general form of a function definition in C programming language is as follows: return_type function_name ( parameter list ) { body of the function }
  • 130. Functions: 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.
  • 131. Functions - Example: 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*/ }
  • 132. Functions - Example: #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; }
  • 133. To solve this problem we have 2 solutions: 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); }
  • 134. To solve this problem we have 2 solutions: 2- Declare the function (The common one) return_type function_name ( parameter list with or without names) Note that the declaration is same as function #include <stdio.h> header. We tell the compiler that there is fuction int mult (int , int ) called mult defined else where. 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; }
  • 135. Arrays: All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element.
  • 136. 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];
  • 137. 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;
  • 138. 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)
  • 139. 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.
  • 141. 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 { We can neglect struct name in this method int x; int y; } Point1, Point2;
  • 142. 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};
  • 146. 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};
  • 147. 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.
  • 148. 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; };
  • 149. The End Mahmoud Eladawi