SlideShare une entreprise Scribd logo
1  sur  62
Télécharger pour lire hors ligne
C Programming
Language
Eng. Khaled Khamis
1
overview
• C basics.
• C and C++.
• Preprocessor/Compiler/linker/IDE
• make/makefile.
• Program structure.
• keywords.
• Data types.
• Variables.
• Operators.
• Input/Output.
• Decision,Loop statements.
• Functions
• Preprocessor directives
• Arrays,pointers
Eng. Khaled Khamis
2
C basics
• C is one of the most widely used languages in the world and is
fairly stable.
• Currently, the most commonly-used language for embedded
systems.
• An improved C language called C++ has been invented.
• Of higher level languages, C is the closest to assembly
languages
• bit manipulation instructions.
• pointers (indirect addressing).
• Most microcontrollers have available C compilers
• Writing in C simplifies code development for large projects.
Eng. Khaled Khamis
3
C and C++
• C follows the procedural programming paradigm while
C++ is a multi-paradigm language(procedural as well
as object oriented)
In case of C, importance is given to the steps or procedure of the
program while C++ focuses on the data rather than the process.
Also, it is easier to implement/edit the code in case of C++ for
the same reason.
• In case of C, the data is not secured while the data is
secured(hidden) in C++
This difference is due to specific OOP features like Data Hiding
which are not present in C.
Eng. Khaled Khamis
4
C and C++
• C is a low-level language while C++ is a middle-level
language.
C is regarded as a low-level language(difficult interpretation &
less user friendly) while C++ has features of both low-
level(concentration on whats going on in the machinehardware)
& high-level languages(concentration on the program itself) &
hence is regarded as a middle-level language.
Eng. Khaled Khamis
5
C and C++
• C is function-driven while C++ is object-driven
Functions are the building blocks of a C program while objects
are building blocks of a C++ program.
• C++ supports function overloading while C does not
Overloading means two functions having the same name in the
same program. This can be done only in C++ with the help
of Polymorphism(an OOP feature)
Eng. Khaled Khamis
6
C and C++
• We can use functions inside structures in C++ but not in C.
In case of C++, functions can be used inside a structure while
structures cannot contain functions in C.
• The NAMESPACE feature in C++ is absent in case of C
C++ uses NAMESPACE which avoid name collisions. For
instance, two students enrolled in the same university cannot have
the same roll number while two students in different universities
might have the same roll number. The universities are two
different namespace & hence contain the same roll
number(identifier) but the same university(one namespace)
cannot have two students with the same roll number(identifier)
Eng. Khaled Khamis
7
C and C++
• The standard input & output functions differ in the two
languages
C uses scanf & printf while C++ uses cin>> & cout<< as their
respective input & output functions
• C++ allows the use of reference variables while C does
not
Reference variables allow two variable names to point to the
same memory location. We cannot use these variables in C
programming.
Eng. Khaled Khamis
8
preprocessor
• Include files are “pasted in” (#include)
• Macros are “expanded” (#define)
• Comments are stripped out ( /* */ , // )
• Continued lines are joined (  )
Eng. Khaled Khamis
9
Compiler & linker
• The compiler converts the resulting text into binary code the CPU
can run directly.
• Then the linker links executables.
Eng. Khaled Khamis
10
Compiler model
Eng. Khaled Khamis
11
IDE
• Integrated development environment
• An IDE normally consists of a source code editor, build
automation tools and a debugger.
• Some IDEs contain a compiler, interpreter, or both, such
as Net Beans and Eclipse
Eng. Khaled Khamis
12
make and Makefiles, Overview
• Why use make?
• convenience of only entering compile directives once
• make is smart enough (with your help) to only compile and link modules that have
changed or which depend on files that have changed
• allows you to hide platform dependencies
• promotes uniformity
• simplifies my (and hopefully your) life when testing and verifying your code
• A makefile contains a set of rules for building a program
target ... : prerequisites ...
command
Eng. Khaled Khamis
13
Program structure
#include <stdio.h>
/* The simplest C Program */
int main(void)
{
printf(“Hello Worldn”);
return 0;
}
The main() function is always
where your program starts
running.
#include inserts another file. “.h” files are called “header”
files. They contain stuff needed to interface to libraries and
code in other “.c” files.
This is a comment. The compiler ignores this.
Blocks of code are marked by {
… }
Print out a message. ‘n’ means “new line”.Return ‘0’ from this function
What do the < >
mean?
Can your program have
more than one .c file?
Eng. Khaled Khamis
14
C keywords
Eng. Khaled Khamis
15
Data types
Eng. Khaled Khamis
16
char x;
char y=‘e’;
A Variable names a place in memory where you
store a Value of a certain Type.
Symbol Addr Value
0
1
2
3
x 4 ?
y 5 ‘e’ (101)
6
7
8
9
10
11
12
You first Declare a variable by giving it a name
and specifying the type, and optionally an initial
value declare vs define?
Type is single character (char)
extern? static? const?
Name What names are legal?
Initial value
Initial value of x is undefined
The compiler puts them
somewhere in memory.
What is a Variable?
Eng. Khaled Khamis
17
Variable scope
• local variables
• Are variables that can only be referenced inside the current
function.
• Global variables
• Variable that not declared inside a function and can be
referenced anywhere in the program.
Eng. Khaled Khamis
18
Constants
• Numerical Constants
• Constants like 12, 253 are stored as int type. No decimal
point.
• 12L or 12l are stored as long int.
• 12U or 12u are stored as unsigned int.
• 12UL or 12ul are stored as unsigned long int.
• Numbers with a decimal point (12.34) are stored as double.
• Numbers with exponent (12e-3 = 12 x 10-3 ) are stored as double.
• 12.34f or 1.234e1f are stored as float.
• These are not valid constants:
25,000 7.1e 4 $200 2.3e-3.4 etc.
Eng. Khaled Khamis
19
Example 1
#include <stdio.h>
int main() {
int number = 23;
printf (“Number is %d”, number);
return 0;
}
Output: Number is 23
Eng. Khaled Khamis
20
C Operators
== equal to
< less than
<= less than or equal
> greater than
>= greater than or equal
!= not equal
&& logical and
|| logical or
! logical not
+ plus
- minus
* multiply
/ divide
% modulo
& bitwise and
| bitwise or
^ bitwise xor
~ bitwise not
<< shift left
>> shift right
Eng. Khaled Khamis
21
Assignment Operators
x = y assign y to x
x++ post-increment x
++x pre-increment x
x-- post-decrement x
--x pre-decrement x
Note the difference between ++x and x++:
int x=5;
int y;
y = ++x;
/* x == 6, y == 6 */
int x=5;
int y;
y = x++;
/* x == 6, y == 5 */
int x=5;
if (x=6) /* always true */
{
/* x is now 6 */
}
/* ... */
int x=5;
if (x==6) /* false */
{
/* ... */
}
/* x is still 5 */
x += y assign (x+y) to x
x -= y assign (x-y) to x
x *= y assign (x*y) to x
x /= y assign (x/y) to x
x %= y assign (x%y) to x
recommendation
Eng. Khaled Khamis
22
Some more Arithmetic Operators
• Prefix Increment : ++a
• example:
• int a=5;
• b=++a; // value of b=6; a=6;
• Postfix Increment: a++
• example
• int a=5;
• b=a++; //value of b=5; a=6;
Eng. Khaled Khamis
23
Contd…
• Modulus (remainder): %
• example:
• 12%5 = 2;
• Assignment by addition: +=
• example:
• int a=4;
• a+=1; //(means a=a+1) value of a becomes 5
Can use -, /, *, % also
Eng. Khaled Khamis
24
Input / Output
 printf (); //used to print to console(screen)
 scanf (); //used to take an input from console(user).
example: printf(“%c”, ’a’); scanf(“%d”, &a);
More format specifiers
%c The character format specifier.
%d The integer format specifier.
%i The integer format specifier (same as %d).
%f The floating-point format specifier.
%o The unsigned octal format specifier.
%s The string format specifier.
%u The unsigned integer format specifier.
%x The unsigned hexadecimal format specifier.
%% Outputs a percent sign.
Eng. Khaled Khamis
25
PRINTF()
• n and t are called escape sequence
• n  New line
• t  TAB
• See complete list in the reference
Eng. Khaled Khamis
26
SCANF()
• & (ampersand) is the address operator in C.
• It tells scanf about the address of the variable we want to
store the value in.
Eng. Khaled Khamis
27
Example 2
#include <stdio.h>
int main() {
int number ;
printf (“ Enter a Number: ”);
scanf (“%d”, &number);
printf (“Number is %dn”, number);
return 0;
}
Eng. Khaled Khamis
28
Conditional Operator [ ?: ]
• A conditional expression is of the form
expr1 ? expr2 : expr3
The expressions can recursively be conditional expressions.
• A substitute for if-else
• Example :
(a<b)?((a<c)?a:c):((b<c)?b:c)
What does this expression evaluate to?
Eng. Khaled Khamis
29
Conditional Operator [ ?: ]
• A conditional expression is of the form
expr1 ? expr2 : expr3
The expressions can recursively be conditional expressions.
• A substitute for if-else
• Example :
(a<b)?((a<c)?a:c):((b<c)?b:c)
This evaluates to min(a,b,c)
Eng. Khaled Khamis
30
If statement
If(condition){
//executed if true
}else{
//executed if false
}
Eng. Khaled Khamis
31
What will be the output?
if(z = y < 0) x = 10;
Printf("%d %dn", x, z);
When y=5 and y=-2?
Eng. Khaled Khamis
32
What will be the output?
• if(z = y < 0) x = 10;
printf(“%d %dn”, x, z);
• When y=10?
Eng. Khaled Khamis
33
Switch case
Switch(variable){
case 1: //code for case 1
break;
case 2: //code for case 2
break;
default: //if variable is not 1 or 2
}
Eng. Khaled Khamis
34
Switch Example
switch (letter = getchar()) {
case‘a’: case ’A’: case ‘e’ : case
‘E’:
case‘i’: case ‘I’: case ’o’ : case
‘O’:
case‘u’: case ‘U’:
printf(“Vowel”); break;
default: printf(“Consonant”);
}
Eng. Khaled Khamis
35
While
• Syntax
while(condition){
//code
}
• Example
Count=0;
While(count<10){
printf(“current count is %d”,count);
count++;
}
Eng. Khaled Khamis
36
While example
int i=0, x=0 ;
while (i<10) {
if(i%3==0) {
x += i;
printf(“%d “, x);
}
++i;
}
Eng. Khaled Khamis
37
For
• Syntax
For(start;condition;increment/decrement){
//code to be repeated
}
• Example:
For(i=0;i<5;i++){
printf(“the value of I is %d”,i);
}
Eng. Khaled Khamis
38
For loop example
int i, j, x;
for(i=0, x=0; i<5; ++i)
for(j=0; j<i; ++j) {
x += (i+j-1);
printf(“%d ”, x);
}
Eng. Khaled Khamis
39
Why functions
• Huge codes are difficult to understand and debug.
• Makes the code look simpler, neater and makes your task
easier.
• Re-usability of code.
Example:
Imagine a program in which we need to swap two numbers often.
Life becomes easy if we could swap in a single step.
printf(),scanf() are functions too. They make our work so easy.
Eng. Khaled Khamis
40
Functions
• Function Declaration/ Prototype:
int func(int , int);
• Function Definition:
int func ( int a, int b){
printf(“Welcome to func”);
return (a + b);
}
Eng. Khaled Khamis
41
Argument or parameter?
• The value passed to a method is called its
“argument”
• The variable which receives the arguments is called
“parameter”
• Parameters are declared inside the parenthesis and we
must declare the type of the parameter.
• Argument may be an expression but,
type (argument) = type (parameter)
Eng. Khaled Khamis
42
Typical Example#include <stdio.h>
void add_print(int , int); //function declaration
int main(){
int a=4;
int b=5;
printf(“Entering ‘add_print’ functionn”);
add_print(a,b);
printf(“Just came from ‘add_print’ functionn”);
return 0;
}
//function definition
void add_print(int val1,int val2){
int c;
printf(“The two values entered are:%d,%d n”,val1,val2);
c=val1+val2;
printf(“Sum of numbers entered is:%d n”,c);
}
What are parameters and arguments?
Eng. Khaled Khamis
43
Contd.
• In the above example,
• ‘a’, ‘b’ are arguments to the function.
• ‘val1’, ‘val2’ are the parameters of the function.
• Scope and Life
• ‘a’, ‘b’
• Have scope limited to the main function.
• Their life is till the main exits.
• ‘val1’, ‘val2’
• Have scope limited to the function block.
• Their life is till the function call is over.
Eng. Khaled Khamis
44
Call by value or call by reference?
• Till now the functions took the values of the arguments from
the calling function (main).
• What if we need to change the values of variables in the calling
function?
• How do we get access to the calling function’s data?
Simple!! Send the address of the variable
Eng. Khaled Khamis
45
Another Example#include <stdio.h>
int swap(int *, int *); //function declaration
int main(){
int a=4;
int b=5;
swap(&a,&b);
printf(“The value of ‘a’ is %d and the value of ‘b’ is %d n”, a,b);
return 0;
} // the values of a and b did swap .
//function definition
int swap(int *val1,int *val2){
int temp;
printf(“The two values entered are:%d,%d n”,*val1,*val2);
temp=*val1;
*val1=*val2;
*val2=temp;
}
Eng. Khaled Khamis
46
preprocessor
• We can write methods, declare variable in multiple files.
• Need to link these.
• # include<filename> includes the file filename.
• # define ABC(X) X*X
• Replaces the occurrences of ABC(z) with z*z.
• What happens to ABC(z+1)? // try out
Eng. Khaled Khamis
47
• What if ABC(X) is already defined?
• #ifndef - #endif
#ifndef ABC(X)
#define ABC(X) X*X
#endif
Eng. Khaled Khamis
48
Arrays
• An Array is a collection of variables of the same type that
are referred to through a common name.
• Declaration
type var_name[size]
e.g
int A[6];
double d[15];
Eng. Khaled Khamis
49
Array Initialization
After declaration, array contains some garbage value.
Static initialization
Run time initialization
int month_days[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int i;
int A[6];
for(i = 0; i < 6; i++)
A[i] = 6 - i;
Eng. Khaled Khamis
50
Memory addresses
• Memory is divided up into one byte pieces
individually addressed.
- minimum data you can request from the
memory is 1 byte
• Each byte has an address.
for a 32 bit processor, addressable
memory is 232 bytes. To uniquely identify
each of the accessible byte you
need log2232 = 32 bits
0A 0x00001234
23 0x00001235
6C 0x00001236
1D 0x00001237
‘W’ 0x00001238
‘o’ 0x00001239
‘w’ 0x0000123
A
‘0’ 0x0000123B
. .
. .
. .
0x24680975
0x24680976
0x24680977
0x24680978
Eng. Khaled Khamis
51
Array - Accessing an element
int A[6];
6 elements of 4 bytes each,
total size = 6 x 4 bytes = 24 bytes
Read an element
Write to an element
A[0] A[1] A[2] A[3] A[4] A[5]
0x1000 0x1004 0x1008 0x1012 0x1016 0x1020
6 5 4 3 2 1
int tmp = A[2];
A[3] = 5;
Eng. Khaled Khamis
52
Strings in C
• No “Strings” keyword
• A string is an array of characters.
OR
char string[] = “hello world”;
char *string = “hello world”;
Eng. Khaled Khamis
53
Significance of NULL character ‘0’
• Compiler has to know where the string ends
• ‘0’ denotes the end of string
Some more characters :
‘n’ = new line, ‘t’ = horizontal tab, ‘v’ = vertical tab, ‘r’ =
carriage return
‘A’ = 0x41, ‘a’ = 0x61, ‘0’ = 0x00
char string[] = “hello world”;
printf(“%s”, string);
Eng. Khaled Khamis
54
Pointers in C
• A char pointer points to a single byte.
• An int pointer points to first of the four bytes.
• A pointer itself has an address where it is stored in the
memory. Pointers are usually four bytes.
• * is called the dereference operator
• *p gives the value pointed by p
• & (ampersand) is called the reference operator
• &i returns the address of variable i
int *p;  int* p;
int i = 4;
p = &i;
Eng. Khaled Khamis
55
More about pointers
int x = 1, y = 2, z[10];
int *ip; /* A pointer to an int */
ip = &x; /* Address of x */
y = *ip; /* Content of ip */
*ip = 0; /* Clear where ip points */
ip = &z[0]; /* Address of first element
of z */
Eng. Khaled Khamis
56
Pointer Arithmetic
• A 32-bit system has 32 bit address space.
• To store any address, 32 bits are required.
• Pointer arithmetic : p+1 gives the next memory location
assuming cells are of the same type as the base type of p.
Eng. Khaled Khamis
57
Pointers and arrays
• Pointers and arrays are tightly coupled.
char a[] = “Hello World”;
char *p = &a[0];
Eng. Khaled Khamis
58
Pointers and function arguments
• Functions only receive copies of the variables passed to
them.
• A function needs to know the address of a variable if it is
to affect the original variable
• Large items like strings or arrays cannot be passed to
functions either.
Eng. Khaled Khamis
59
2-Dimensional Arrays
(Array of arrays)
int d[3][2];
Access the point 1, 2 of the array:
d[1][2]
Initialize (without loops):
int d[3][2] = {{1, 2}, {4, 5}, {7, 8}};
Eng. Khaled Khamis
60
More about 2-Dimensional
arrays
d[0][0] d[0][1] d[0][2] d[0][3]
d[1][0] d[1][1] d[1][2] d[1][3]
d[2][0] d[2][1] d[2][2] d[2][3]
A Multidimensional array is stored in a row major format.
A two dimensional case:
 next memory element to d[0][3] is d[1][0]
What about memory addresses sequence of a three
dimensional array?
 next memory element to t[0][0][0] is t[0][0][1]
Eng. Khaled Khamis
61
Questions?
Eng. Khaled Khamis
62

Contenu connexe

Tendances

Tendances (19)

C++ Programming
C++ ProgrammingC++ Programming
C++ Programming
 
45 Days C++ Programming Language Training in Ambala
45 Days C++ Programming Language Training in Ambala45 Days C++ Programming Language Training in Ambala
45 Days C++ Programming Language Training in Ambala
 
c++
 c++  c++
c++
 
Basics of c++
Basics of c++Basics of c++
Basics of c++
 
C programming tutorial for Beginner
C programming tutorial for BeginnerC programming tutorial for Beginner
C programming tutorial for Beginner
 
C++ programming program design including data structures
C++ programming program design including data structures C++ programming program design including data structures
C++ programming program design including data structures
 
The smartpath information systems c plus plus
The smartpath information systems  c plus plusThe smartpath information systems  c plus plus
The smartpath information systems c plus plus
 
basics of C and c++ by eteaching
basics of C and c++ by eteachingbasics of C and c++ by eteaching
basics of C and c++ by eteaching
 
C++ Programming Course
C++ Programming CourseC++ Programming Course
C++ Programming Course
 
C++ How to program
C++ How to programC++ How to program
C++ How to program
 
Introduction to C++
Introduction to C++ Introduction to C++
Introduction to C++
 
Basics of c++
Basics of c++Basics of c++
Basics of c++
 
Intro to C++ - language
Intro to C++ - languageIntro to C++ - language
Intro to C++ - language
 
C++ for beginners
C++ for beginnersC++ for beginners
C++ for beginners
 
Overview of c++ language
Overview of c++ language   Overview of c++ language
Overview of c++ language
 
Lex and Yacc ppt
Lex and Yacc pptLex and Yacc ppt
Lex and Yacc ppt
 
Reduce course notes class xii
Reduce course notes class xiiReduce course notes class xii
Reduce course notes class xii
 
Lex Tool
Lex ToolLex Tool
Lex Tool
 
Programming of c++
Programming of c++Programming of c++
Programming of c++
 

En vedette

AVR_Course_Day1 basic electronics
AVR_Course_Day1 basic electronicsAVR_Course_Day1 basic electronics
AVR_Course_Day1 basic electronicsMohamed Ali
 
AVR_Course_Day5 avr interfaces
AVR_Course_Day5 avr interfacesAVR_Course_Day5 avr interfaces
AVR_Course_Day5 avr interfacesMohamed Ali
 
AVR_Course_Day2 what is pcb
AVR_Course_Day2 what is pcbAVR_Course_Day2 what is pcb
AVR_Course_Day2 what is pcbMohamed Ali
 
AVR_Course_Day4 introduction to microcontroller
AVR_Course_Day4 introduction to microcontrollerAVR_Course_Day4 introduction to microcontroller
AVR_Course_Day4 introduction to microcontrollerMohamed Ali
 
AVR_Course_Day8 motor drive and pwm techniques
AVR_Course_Day8 motor drive and pwm techniquesAVR_Course_Day8 motor drive and pwm techniques
AVR_Course_Day8 motor drive and pwm techniquesMohamed Ali
 
1169_ali_mohamed
1169_ali_mohamed1169_ali_mohamed
1169_ali_mohamedMohamed Ali
 
Basics of C programming
Basics of C programmingBasics of C programming
Basics of C programmingavikdhupar
 
APRS - the amateur radio tracking system
APRS - the amateur radio tracking system APRS - the amateur radio tracking system
APRS - the amateur radio tracking system FSCONS
 
Complete Overview of MESH for Amateur Radio (Updated Nov. 2014)
Complete Overview of MESH for Amateur Radio (Updated Nov. 2014)Complete Overview of MESH for Amateur Radio (Updated Nov. 2014)
Complete Overview of MESH for Amateur Radio (Updated Nov. 2014)va3bco
 
An innovative introductory course to systems engineering teaching.pptx
An innovative introductory course to systems engineering teaching.pptxAn innovative introductory course to systems engineering teaching.pptx
An innovative introductory course to systems engineering teaching.pptxJoseph KAsser
 
Kasser synergy amateur radio
Kasser synergy   amateur radioKasser synergy   amateur radio
Kasser synergy amateur radioJoseph KAsser
 
Raspberry Pi and Amateur Radio
Raspberry Pi and Amateur RadioRaspberry Pi and Amateur Radio
Raspberry Pi and Amateur RadioKevin Hooke
 
Mobile design matters - iOS and Android
Mobile design matters - iOS and AndroidMobile design matters - iOS and Android
Mobile design matters - iOS and AndroidLight Lin
 
best notes in c language
best notes in c languagebest notes in c language
best notes in c languageIndia
 
Beginning Real World iOS App Development
Beginning Real World iOS App DevelopmentBeginning Real World iOS App Development
Beginning Real World iOS App DevelopmentAndri Yadi
 
Introduction to Amateur (Ham) Radio - For Elementary School Students by VE7NZ
Introduction to Amateur (Ham) Radio - For Elementary School Students by VE7NZIntroduction to Amateur (Ham) Radio - For Elementary School Students by VE7NZ
Introduction to Amateur (Ham) Radio - For Elementary School Students by VE7NZSlidingaround
 
Try amateur satellites presentation
Try amateur satellites presentationTry amateur satellites presentation
Try amateur satellites presentationPeter Goodhall
 
Gigigo Workshop - Create an iOS Framework, document it and not die trying
Gigigo Workshop - Create an iOS Framework, document it and not die tryingGigigo Workshop - Create an iOS Framework, document it and not die trying
Gigigo Workshop - Create an iOS Framework, document it and not die tryingAlex Rupérez
 

En vedette (20)

AVR_Course_Day1 basic electronics
AVR_Course_Day1 basic electronicsAVR_Course_Day1 basic electronics
AVR_Course_Day1 basic electronics
 
AVR_Course_Day5 avr interfaces
AVR_Course_Day5 avr interfacesAVR_Course_Day5 avr interfaces
AVR_Course_Day5 avr interfaces
 
AVR_Course_Day2 what is pcb
AVR_Course_Day2 what is pcbAVR_Course_Day2 what is pcb
AVR_Course_Day2 what is pcb
 
AVR_Course_Day4 introduction to microcontroller
AVR_Course_Day4 introduction to microcontrollerAVR_Course_Day4 introduction to microcontroller
AVR_Course_Day4 introduction to microcontroller
 
AVR_Course_Day8 motor drive and pwm techniques
AVR_Course_Day8 motor drive and pwm techniquesAVR_Course_Day8 motor drive and pwm techniques
AVR_Course_Day8 motor drive and pwm techniques
 
1169_ali_mohamed
1169_ali_mohamed1169_ali_mohamed
1169_ali_mohamed
 
Basics of C programming
Basics of C programmingBasics of C programming
Basics of C programming
 
APRS - the amateur radio tracking system
APRS - the amateur radio tracking system APRS - the amateur radio tracking system
APRS - the amateur radio tracking system
 
Complete Overview of MESH for Amateur Radio (Updated Nov. 2014)
Complete Overview of MESH for Amateur Radio (Updated Nov. 2014)Complete Overview of MESH for Amateur Radio (Updated Nov. 2014)
Complete Overview of MESH for Amateur Radio (Updated Nov. 2014)
 
05 Views
05 Views05 Views
05 Views
 
An innovative introductory course to systems engineering teaching.pptx
An innovative introductory course to systems engineering teaching.pptxAn innovative introductory course to systems engineering teaching.pptx
An innovative introductory course to systems engineering teaching.pptx
 
Kasser synergy amateur radio
Kasser synergy   amateur radioKasser synergy   amateur radio
Kasser synergy amateur radio
 
Raspberry Pi and Amateur Radio
Raspberry Pi and Amateur RadioRaspberry Pi and Amateur Radio
Raspberry Pi and Amateur Radio
 
Mobile design matters - iOS and Android
Mobile design matters - iOS and AndroidMobile design matters - iOS and Android
Mobile design matters - iOS and Android
 
C Programming - Refresher - Part III
C Programming - Refresher - Part IIIC Programming - Refresher - Part III
C Programming - Refresher - Part III
 
best notes in c language
best notes in c languagebest notes in c language
best notes in c language
 
Beginning Real World iOS App Development
Beginning Real World iOS App DevelopmentBeginning Real World iOS App Development
Beginning Real World iOS App Development
 
Introduction to Amateur (Ham) Radio - For Elementary School Students by VE7NZ
Introduction to Amateur (Ham) Radio - For Elementary School Students by VE7NZIntroduction to Amateur (Ham) Radio - For Elementary School Students by VE7NZ
Introduction to Amateur (Ham) Radio - For Elementary School Students by VE7NZ
 
Try amateur satellites presentation
Try amateur satellites presentationTry amateur satellites presentation
Try amateur satellites presentation
 
Gigigo Workshop - Create an iOS Framework, document it and not die trying
Gigigo Workshop - Create an iOS Framework, document it and not die tryingGigigo Workshop - Create an iOS Framework, document it and not die trying
Gigigo Workshop - Create an iOS Framework, document it and not die trying
 

Similaire à AVR_Course_Day3 c programming

c programming L-1.pdf43333333544444444444444444444
c programming L-1.pdf43333333544444444444444444444c programming L-1.pdf43333333544444444444444444444
c programming L-1.pdf43333333544444444444444444444PurvaShyama
 
Esoft Metro Campus - Programming with C++
Esoft Metro Campus - Programming with C++Esoft Metro Campus - Programming with C++
Esoft Metro Campus - Programming with C++Rasan Samarasinghe
 
C programming language tutorial
C programming language tutorialC programming language tutorial
C programming language tutorialSURBHI SAROHA
 
Basics of C Prog Lang.pdf
Basics of C Prog Lang.pdfBasics of C Prog Lang.pdf
Basics of C Prog Lang.pdfKalighatOkira
 
Chap_________________1_Introduction.pptx
Chap_________________1_Introduction.pptxChap_________________1_Introduction.pptx
Chap_________________1_Introduction.pptxRonaldo Aditya
 
A brief introduction to C Language
A brief introduction to C LanguageA brief introduction to C Language
A brief introduction to C LanguageMohamed Elsayed
 
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]Chris Adamson
 
Introduction to c programming
Introduction to c programmingIntroduction to c programming
Introduction to c programmingAlpana Gupta
 
CLEAN CODING AND DEVOPS Final.pptx
CLEAN CODING AND DEVOPS Final.pptxCLEAN CODING AND DEVOPS Final.pptx
CLEAN CODING AND DEVOPS Final.pptxJEEVANANTHAMG6
 
Programming languages
Programming languagesProgramming languages
Programming languagesEelco Visser
 
Learn c++ Programming Language
Learn c++ Programming LanguageLearn c++ Programming Language
Learn c++ Programming LanguageSteve Johnson
 
Programming for Problem Solving Unit 2
Programming for Problem Solving Unit 2Programming for Problem Solving Unit 2
Programming for Problem Solving Unit 2Dhiviya Rose
 

Similaire à AVR_Course_Day3 c programming (20)

c programming L-1.pdf43333333544444444444444444444
c programming L-1.pdf43333333544444444444444444444c programming L-1.pdf43333333544444444444444444444
c programming L-1.pdf43333333544444444444444444444
 
C++primer
C++primerC++primer
C++primer
 
Esoft Metro Campus - Programming with C++
Esoft Metro Campus - Programming with C++Esoft Metro Campus - Programming with C++
Esoft Metro Campus - Programming with C++
 
Return of c++
Return of c++Return of c++
Return of c++
 
C programming language tutorial
C programming language tutorialC programming language tutorial
C programming language tutorial
 
#Code2 create c++ for beginners
#Code2 create  c++ for beginners #Code2 create  c++ for beginners
#Code2 create c++ for beginners
 
Lecture1
Lecture1Lecture1
Lecture1
 
Introduction to C programming
Introduction to C programmingIntroduction to C programming
Introduction to C programming
 
College1
College1College1
College1
 
Basics of C Prog Lang.pdf
Basics of C Prog Lang.pdfBasics of C Prog Lang.pdf
Basics of C Prog Lang.pdf
 
Chap_________________1_Introduction.pptx
Chap_________________1_Introduction.pptxChap_________________1_Introduction.pptx
Chap_________________1_Introduction.pptx
 
A brief introduction to C Language
A brief introduction to C LanguageA brief introduction to C Language
A brief introduction to C Language
 
C Tutorials
C TutorialsC Tutorials
C Tutorials
 
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
 
Introduction to c programming
Introduction to c programmingIntroduction to c programming
Introduction to c programming
 
CLEAN CODING AND DEVOPS Final.pptx
CLEAN CODING AND DEVOPS Final.pptxCLEAN CODING AND DEVOPS Final.pptx
CLEAN CODING AND DEVOPS Final.pptx
 
Programming languages
Programming languagesProgramming languages
Programming languages
 
Learn c++ Programming Language
Learn c++ Programming LanguageLearn c++ Programming Language
Learn c++ Programming Language
 
Prog1-L1.pdf
Prog1-L1.pdfProg1-L1.pdf
Prog1-L1.pdf
 
Programming for Problem Solving Unit 2
Programming for Problem Solving Unit 2Programming for Problem Solving Unit 2
Programming for Problem Solving Unit 2
 

Dernier

Thermal Engineering Unit - I & II . ppt
Thermal Engineering  Unit - I & II . pptThermal Engineering  Unit - I & II . ppt
Thermal Engineering Unit - I & II . pptDineshKumar4165
 
DC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equationDC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equationBhangaleSonal
 
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptx
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptxS1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptx
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptxSCMS School of Architecture
 
DeepFakes presentation : brief idea of DeepFakes
DeepFakes presentation : brief idea of DeepFakesDeepFakes presentation : brief idea of DeepFakes
DeepFakes presentation : brief idea of DeepFakesMayuraD1
 
NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...
NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...
NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...Amil baba
 
PE 459 LECTURE 2- natural gas basic concepts and properties
PE 459 LECTURE 2- natural gas basic concepts and propertiesPE 459 LECTURE 2- natural gas basic concepts and properties
PE 459 LECTURE 2- natural gas basic concepts and propertiessarkmank1
 
Design For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the startDesign For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the startQuintin Balsdon
 
Orlando’s Arnold Palmer Hospital Layout Strategy-1.pptx
Orlando’s Arnold Palmer Hospital Layout Strategy-1.pptxOrlando’s Arnold Palmer Hospital Layout Strategy-1.pptx
Orlando’s Arnold Palmer Hospital Layout Strategy-1.pptxMuhammadAsimMuhammad6
 
Unleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leapUnleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leapRishantSharmaFr
 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXssuser89054b
 
AIRCANVAS[1].pdf mini project for btech students
AIRCANVAS[1].pdf mini project for btech studentsAIRCANVAS[1].pdf mini project for btech students
AIRCANVAS[1].pdf mini project for btech studentsvanyagupta248
 
COST-EFFETIVE and Energy Efficient BUILDINGS ptx
COST-EFFETIVE  and Energy Efficient BUILDINGS ptxCOST-EFFETIVE  and Energy Efficient BUILDINGS ptx
COST-EFFETIVE and Energy Efficient BUILDINGS ptxJIT KUMAR GUPTA
 
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKARHAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKARKOUSTAV SARKAR
 
Block diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.pptBlock diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.pptNANDHAKUMARA10
 
Work-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptxWork-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptxJuliansyahHarahap1
 
GEAR TRAIN- BASIC CONCEPTS AND WORKING PRINCIPLE
GEAR TRAIN- BASIC CONCEPTS AND WORKING PRINCIPLEGEAR TRAIN- BASIC CONCEPTS AND WORKING PRINCIPLE
GEAR TRAIN- BASIC CONCEPTS AND WORKING PRINCIPLEselvakumar948
 
Hostel management system project report..pdf
Hostel management system project report..pdfHostel management system project report..pdf
Hostel management system project report..pdfKamal Acharya
 
Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptDineshKumar4165
 

Dernier (20)

FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced LoadsFEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
 
Thermal Engineering Unit - I & II . ppt
Thermal Engineering  Unit - I & II . pptThermal Engineering  Unit - I & II . ppt
Thermal Engineering Unit - I & II . ppt
 
DC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equationDC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equation
 
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptx
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptxS1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptx
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptx
 
DeepFakes presentation : brief idea of DeepFakes
DeepFakes presentation : brief idea of DeepFakesDeepFakes presentation : brief idea of DeepFakes
DeepFakes presentation : brief idea of DeepFakes
 
NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...
NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...
NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...
 
PE 459 LECTURE 2- natural gas basic concepts and properties
PE 459 LECTURE 2- natural gas basic concepts and propertiesPE 459 LECTURE 2- natural gas basic concepts and properties
PE 459 LECTURE 2- natural gas basic concepts and properties
 
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak HamilCara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
 
Design For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the startDesign For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the start
 
Orlando’s Arnold Palmer Hospital Layout Strategy-1.pptx
Orlando’s Arnold Palmer Hospital Layout Strategy-1.pptxOrlando’s Arnold Palmer Hospital Layout Strategy-1.pptx
Orlando’s Arnold Palmer Hospital Layout Strategy-1.pptx
 
Unleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leapUnleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leap
 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
 
AIRCANVAS[1].pdf mini project for btech students
AIRCANVAS[1].pdf mini project for btech studentsAIRCANVAS[1].pdf mini project for btech students
AIRCANVAS[1].pdf mini project for btech students
 
COST-EFFETIVE and Energy Efficient BUILDINGS ptx
COST-EFFETIVE  and Energy Efficient BUILDINGS ptxCOST-EFFETIVE  and Energy Efficient BUILDINGS ptx
COST-EFFETIVE and Energy Efficient BUILDINGS ptx
 
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKARHAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
 
Block diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.pptBlock diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.ppt
 
Work-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptxWork-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptx
 
GEAR TRAIN- BASIC CONCEPTS AND WORKING PRINCIPLE
GEAR TRAIN- BASIC CONCEPTS AND WORKING PRINCIPLEGEAR TRAIN- BASIC CONCEPTS AND WORKING PRINCIPLE
GEAR TRAIN- BASIC CONCEPTS AND WORKING PRINCIPLE
 
Hostel management system project report..pdf
Hostel management system project report..pdfHostel management system project report..pdf
Hostel management system project report..pdf
 
Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.ppt
 

AVR_Course_Day3 c programming

  • 2. overview • C basics. • C and C++. • Preprocessor/Compiler/linker/IDE • make/makefile. • Program structure. • keywords. • Data types. • Variables. • Operators. • Input/Output. • Decision,Loop statements. • Functions • Preprocessor directives • Arrays,pointers Eng. Khaled Khamis 2
  • 3. C basics • C is one of the most widely used languages in the world and is fairly stable. • Currently, the most commonly-used language for embedded systems. • An improved C language called C++ has been invented. • Of higher level languages, C is the closest to assembly languages • bit manipulation instructions. • pointers (indirect addressing). • Most microcontrollers have available C compilers • Writing in C simplifies code development for large projects. Eng. Khaled Khamis 3
  • 4. C and C++ • C follows the procedural programming paradigm while C++ is a multi-paradigm language(procedural as well as object oriented) In case of C, importance is given to the steps or procedure of the program while C++ focuses on the data rather than the process. Also, it is easier to implement/edit the code in case of C++ for the same reason. • In case of C, the data is not secured while the data is secured(hidden) in C++ This difference is due to specific OOP features like Data Hiding which are not present in C. Eng. Khaled Khamis 4
  • 5. C and C++ • C is a low-level language while C++ is a middle-level language. C is regarded as a low-level language(difficult interpretation & less user friendly) while C++ has features of both low- level(concentration on whats going on in the machinehardware) & high-level languages(concentration on the program itself) & hence is regarded as a middle-level language. Eng. Khaled Khamis 5
  • 6. C and C++ • C is function-driven while C++ is object-driven Functions are the building blocks of a C program while objects are building blocks of a C++ program. • C++ supports function overloading while C does not Overloading means two functions having the same name in the same program. This can be done only in C++ with the help of Polymorphism(an OOP feature) Eng. Khaled Khamis 6
  • 7. C and C++ • We can use functions inside structures in C++ but not in C. In case of C++, functions can be used inside a structure while structures cannot contain functions in C. • The NAMESPACE feature in C++ is absent in case of C C++ uses NAMESPACE which avoid name collisions. For instance, two students enrolled in the same university cannot have the same roll number while two students in different universities might have the same roll number. The universities are two different namespace & hence contain the same roll number(identifier) but the same university(one namespace) cannot have two students with the same roll number(identifier) Eng. Khaled Khamis 7
  • 8. C and C++ • The standard input & output functions differ in the two languages C uses scanf & printf while C++ uses cin>> & cout<< as their respective input & output functions • C++ allows the use of reference variables while C does not Reference variables allow two variable names to point to the same memory location. We cannot use these variables in C programming. Eng. Khaled Khamis 8
  • 9. preprocessor • Include files are “pasted in” (#include) • Macros are “expanded” (#define) • Comments are stripped out ( /* */ , // ) • Continued lines are joined ( ) Eng. Khaled Khamis 9
  • 10. Compiler & linker • The compiler converts the resulting text into binary code the CPU can run directly. • Then the linker links executables. Eng. Khaled Khamis 10
  • 12. IDE • Integrated development environment • An IDE normally consists of a source code editor, build automation tools and a debugger. • Some IDEs contain a compiler, interpreter, or both, such as Net Beans and Eclipse Eng. Khaled Khamis 12
  • 13. make and Makefiles, Overview • Why use make? • convenience of only entering compile directives once • make is smart enough (with your help) to only compile and link modules that have changed or which depend on files that have changed • allows you to hide platform dependencies • promotes uniformity • simplifies my (and hopefully your) life when testing and verifying your code • A makefile contains a set of rules for building a program target ... : prerequisites ... command Eng. Khaled Khamis 13
  • 14. Program structure #include <stdio.h> /* The simplest C Program */ int main(void) { printf(“Hello Worldn”); return 0; } The main() function is always where your program starts running. #include inserts another file. “.h” files are called “header” files. They contain stuff needed to interface to libraries and code in other “.c” files. This is a comment. The compiler ignores this. Blocks of code are marked by { … } Print out a message. ‘n’ means “new line”.Return ‘0’ from this function What do the < > mean? Can your program have more than one .c file? Eng. Khaled Khamis 14
  • 17. char x; char y=‘e’; A Variable names a place in memory where you store a Value of a certain Type. Symbol Addr Value 0 1 2 3 x 4 ? y 5 ‘e’ (101) 6 7 8 9 10 11 12 You first Declare a variable by giving it a name and specifying the type, and optionally an initial value declare vs define? Type is single character (char) extern? static? const? Name What names are legal? Initial value Initial value of x is undefined The compiler puts them somewhere in memory. What is a Variable? Eng. Khaled Khamis 17
  • 18. Variable scope • local variables • Are variables that can only be referenced inside the current function. • Global variables • Variable that not declared inside a function and can be referenced anywhere in the program. Eng. Khaled Khamis 18
  • 19. Constants • Numerical Constants • Constants like 12, 253 are stored as int type. No decimal point. • 12L or 12l are stored as long int. • 12U or 12u are stored as unsigned int. • 12UL or 12ul are stored as unsigned long int. • Numbers with a decimal point (12.34) are stored as double. • Numbers with exponent (12e-3 = 12 x 10-3 ) are stored as double. • 12.34f or 1.234e1f are stored as float. • These are not valid constants: 25,000 7.1e 4 $200 2.3e-3.4 etc. Eng. Khaled Khamis 19
  • 20. Example 1 #include <stdio.h> int main() { int number = 23; printf (“Number is %d”, number); return 0; } Output: Number is 23 Eng. Khaled Khamis 20
  • 21. C Operators == equal to < less than <= less than or equal > greater than >= greater than or equal != not equal && logical and || logical or ! logical not + plus - minus * multiply / divide % modulo & bitwise and | bitwise or ^ bitwise xor ~ bitwise not << shift left >> shift right Eng. Khaled Khamis 21
  • 22. Assignment Operators x = y assign y to x x++ post-increment x ++x pre-increment x x-- post-decrement x --x pre-decrement x Note the difference between ++x and x++: int x=5; int y; y = ++x; /* x == 6, y == 6 */ int x=5; int y; y = x++; /* x == 6, y == 5 */ int x=5; if (x=6) /* always true */ { /* x is now 6 */ } /* ... */ int x=5; if (x==6) /* false */ { /* ... */ } /* x is still 5 */ x += y assign (x+y) to x x -= y assign (x-y) to x x *= y assign (x*y) to x x /= y assign (x/y) to x x %= y assign (x%y) to x recommendation Eng. Khaled Khamis 22
  • 23. Some more Arithmetic Operators • Prefix Increment : ++a • example: • int a=5; • b=++a; // value of b=6; a=6; • Postfix Increment: a++ • example • int a=5; • b=a++; //value of b=5; a=6; Eng. Khaled Khamis 23
  • 24. Contd… • Modulus (remainder): % • example: • 12%5 = 2; • Assignment by addition: += • example: • int a=4; • a+=1; //(means a=a+1) value of a becomes 5 Can use -, /, *, % also Eng. Khaled Khamis 24
  • 25. Input / Output  printf (); //used to print to console(screen)  scanf (); //used to take an input from console(user). example: printf(“%c”, ’a’); scanf(“%d”, &a); More format specifiers %c The character format specifier. %d The integer format specifier. %i The integer format specifier (same as %d). %f The floating-point format specifier. %o The unsigned octal format specifier. %s The string format specifier. %u The unsigned integer format specifier. %x The unsigned hexadecimal format specifier. %% Outputs a percent sign. Eng. Khaled Khamis 25
  • 26. PRINTF() • n and t are called escape sequence • n  New line • t  TAB • See complete list in the reference Eng. Khaled Khamis 26
  • 27. SCANF() • & (ampersand) is the address operator in C. • It tells scanf about the address of the variable we want to store the value in. Eng. Khaled Khamis 27
  • 28. Example 2 #include <stdio.h> int main() { int number ; printf (“ Enter a Number: ”); scanf (“%d”, &number); printf (“Number is %dn”, number); return 0; } Eng. Khaled Khamis 28
  • 29. Conditional Operator [ ?: ] • A conditional expression is of the form expr1 ? expr2 : expr3 The expressions can recursively be conditional expressions. • A substitute for if-else • Example : (a<b)?((a<c)?a:c):((b<c)?b:c) What does this expression evaluate to? Eng. Khaled Khamis 29
  • 30. Conditional Operator [ ?: ] • A conditional expression is of the form expr1 ? expr2 : expr3 The expressions can recursively be conditional expressions. • A substitute for if-else • Example : (a<b)?((a<c)?a:c):((b<c)?b:c) This evaluates to min(a,b,c) Eng. Khaled Khamis 30
  • 31. If statement If(condition){ //executed if true }else{ //executed if false } Eng. Khaled Khamis 31
  • 32. What will be the output? if(z = y < 0) x = 10; Printf("%d %dn", x, z); When y=5 and y=-2? Eng. Khaled Khamis 32
  • 33. What will be the output? • if(z = y < 0) x = 10; printf(“%d %dn”, x, z); • When y=10? Eng. Khaled Khamis 33
  • 34. Switch case Switch(variable){ case 1: //code for case 1 break; case 2: //code for case 2 break; default: //if variable is not 1 or 2 } Eng. Khaled Khamis 34
  • 35. Switch Example switch (letter = getchar()) { case‘a’: case ’A’: case ‘e’ : case ‘E’: case‘i’: case ‘I’: case ’o’ : case ‘O’: case‘u’: case ‘U’: printf(“Vowel”); break; default: printf(“Consonant”); } Eng. Khaled Khamis 35
  • 37. While example int i=0, x=0 ; while (i<10) { if(i%3==0) { x += i; printf(“%d “, x); } ++i; } Eng. Khaled Khamis 37
  • 38. For • Syntax For(start;condition;increment/decrement){ //code to be repeated } • Example: For(i=0;i<5;i++){ printf(“the value of I is %d”,i); } Eng. Khaled Khamis 38
  • 39. For loop example int i, j, x; for(i=0, x=0; i<5; ++i) for(j=0; j<i; ++j) { x += (i+j-1); printf(“%d ”, x); } Eng. Khaled Khamis 39
  • 40. Why functions • Huge codes are difficult to understand and debug. • Makes the code look simpler, neater and makes your task easier. • Re-usability of code. Example: Imagine a program in which we need to swap two numbers often. Life becomes easy if we could swap in a single step. printf(),scanf() are functions too. They make our work so easy. Eng. Khaled Khamis 40
  • 41. Functions • Function Declaration/ Prototype: int func(int , int); • Function Definition: int func ( int a, int b){ printf(“Welcome to func”); return (a + b); } Eng. Khaled Khamis 41
  • 42. Argument or parameter? • The value passed to a method is called its “argument” • The variable which receives the arguments is called “parameter” • Parameters are declared inside the parenthesis and we must declare the type of the parameter. • Argument may be an expression but, type (argument) = type (parameter) Eng. Khaled Khamis 42
  • 43. Typical Example#include <stdio.h> void add_print(int , int); //function declaration int main(){ int a=4; int b=5; printf(“Entering ‘add_print’ functionn”); add_print(a,b); printf(“Just came from ‘add_print’ functionn”); return 0; } //function definition void add_print(int val1,int val2){ int c; printf(“The two values entered are:%d,%d n”,val1,val2); c=val1+val2; printf(“Sum of numbers entered is:%d n”,c); } What are parameters and arguments? Eng. Khaled Khamis 43
  • 44. Contd. • In the above example, • ‘a’, ‘b’ are arguments to the function. • ‘val1’, ‘val2’ are the parameters of the function. • Scope and Life • ‘a’, ‘b’ • Have scope limited to the main function. • Their life is till the main exits. • ‘val1’, ‘val2’ • Have scope limited to the function block. • Their life is till the function call is over. Eng. Khaled Khamis 44
  • 45. Call by value or call by reference? • Till now the functions took the values of the arguments from the calling function (main). • What if we need to change the values of variables in the calling function? • How do we get access to the calling function’s data? Simple!! Send the address of the variable Eng. Khaled Khamis 45
  • 46. Another Example#include <stdio.h> int swap(int *, int *); //function declaration int main(){ int a=4; int b=5; swap(&a,&b); printf(“The value of ‘a’ is %d and the value of ‘b’ is %d n”, a,b); return 0; } // the values of a and b did swap . //function definition int swap(int *val1,int *val2){ int temp; printf(“The two values entered are:%d,%d n”,*val1,*val2); temp=*val1; *val1=*val2; *val2=temp; } Eng. Khaled Khamis 46
  • 47. preprocessor • We can write methods, declare variable in multiple files. • Need to link these. • # include<filename> includes the file filename. • # define ABC(X) X*X • Replaces the occurrences of ABC(z) with z*z. • What happens to ABC(z+1)? // try out Eng. Khaled Khamis 47
  • 48. • What if ABC(X) is already defined? • #ifndef - #endif #ifndef ABC(X) #define ABC(X) X*X #endif Eng. Khaled Khamis 48
  • 49. Arrays • An Array is a collection of variables of the same type that are referred to through a common name. • Declaration type var_name[size] e.g int A[6]; double d[15]; Eng. Khaled Khamis 49
  • 50. Array Initialization After declaration, array contains some garbage value. Static initialization Run time initialization int month_days[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; int i; int A[6]; for(i = 0; i < 6; i++) A[i] = 6 - i; Eng. Khaled Khamis 50
  • 51. Memory addresses • Memory is divided up into one byte pieces individually addressed. - minimum data you can request from the memory is 1 byte • Each byte has an address. for a 32 bit processor, addressable memory is 232 bytes. To uniquely identify each of the accessible byte you need log2232 = 32 bits 0A 0x00001234 23 0x00001235 6C 0x00001236 1D 0x00001237 ‘W’ 0x00001238 ‘o’ 0x00001239 ‘w’ 0x0000123 A ‘0’ 0x0000123B . . . . . . 0x24680975 0x24680976 0x24680977 0x24680978 Eng. Khaled Khamis 51
  • 52. Array - Accessing an element int A[6]; 6 elements of 4 bytes each, total size = 6 x 4 bytes = 24 bytes Read an element Write to an element A[0] A[1] A[2] A[3] A[4] A[5] 0x1000 0x1004 0x1008 0x1012 0x1016 0x1020 6 5 4 3 2 1 int tmp = A[2]; A[3] = 5; Eng. Khaled Khamis 52
  • 53. Strings in C • No “Strings” keyword • A string is an array of characters. OR char string[] = “hello world”; char *string = “hello world”; Eng. Khaled Khamis 53
  • 54. Significance of NULL character ‘0’ • Compiler has to know where the string ends • ‘0’ denotes the end of string Some more characters : ‘n’ = new line, ‘t’ = horizontal tab, ‘v’ = vertical tab, ‘r’ = carriage return ‘A’ = 0x41, ‘a’ = 0x61, ‘0’ = 0x00 char string[] = “hello world”; printf(“%s”, string); Eng. Khaled Khamis 54
  • 55. Pointers in C • A char pointer points to a single byte. • An int pointer points to first of the four bytes. • A pointer itself has an address where it is stored in the memory. Pointers are usually four bytes. • * is called the dereference operator • *p gives the value pointed by p • & (ampersand) is called the reference operator • &i returns the address of variable i int *p;  int* p; int i = 4; p = &i; Eng. Khaled Khamis 55
  • 56. More about pointers int x = 1, y = 2, z[10]; int *ip; /* A pointer to an int */ ip = &x; /* Address of x */ y = *ip; /* Content of ip */ *ip = 0; /* Clear where ip points */ ip = &z[0]; /* Address of first element of z */ Eng. Khaled Khamis 56
  • 57. Pointer Arithmetic • A 32-bit system has 32 bit address space. • To store any address, 32 bits are required. • Pointer arithmetic : p+1 gives the next memory location assuming cells are of the same type as the base type of p. Eng. Khaled Khamis 57
  • 58. Pointers and arrays • Pointers and arrays are tightly coupled. char a[] = “Hello World”; char *p = &a[0]; Eng. Khaled Khamis 58
  • 59. Pointers and function arguments • Functions only receive copies of the variables passed to them. • A function needs to know the address of a variable if it is to affect the original variable • Large items like strings or arrays cannot be passed to functions either. Eng. Khaled Khamis 59
  • 60. 2-Dimensional Arrays (Array of arrays) int d[3][2]; Access the point 1, 2 of the array: d[1][2] Initialize (without loops): int d[3][2] = {{1, 2}, {4, 5}, {7, 8}}; Eng. Khaled Khamis 60
  • 61. More about 2-Dimensional arrays d[0][0] d[0][1] d[0][2] d[0][3] d[1][0] d[1][1] d[1][2] d[1][3] d[2][0] d[2][1] d[2][2] d[2][3] A Multidimensional array is stored in a row major format. A two dimensional case:  next memory element to d[0][3] is d[1][0] What about memory addresses sequence of a three dimensional array?  next memory element to t[0][0][0] is t[0][0][1] Eng. Khaled Khamis 61