This document provides an overview of the C programming language. It discusses C basics, the differences between C and C++, and various C concepts like data types, variables, operators, input/output, decision and loop statements, functions, arrays, pointers, and preprocessor directives. It also covers topics like the preprocessor, compiler, linker, program structure, and integrated development environments. The document is presented as a slideshow with explanatory text and examples to illustrate key C programming concepts.
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
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
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