Professional Documents
Culture Documents
ECE 126
INTRODUCTION TO C
PROGRAMMING
COURSE NOTES
NAME :
GROUP:
LECTURER :
PROGRAMME
COURSE
CREDIT HOUR
SEMESTER
PRE-REQUISITE
STATUS
CONTACT HOUR
SYNOPSIS
This course provides an introduction to C programming and its application in
solving simple engineering problems.
OBJECTIVES
Upon completion of this course, the students will be able to:
To develop algorithms and program the solutions to simple engineering
problems.
To understand the programming concepts required to implement the
solution in C programming language.
2
COURSE EVALUATION
Coursework
1. Lab/assignments
2. Test (2)
3. Mini Project (1)
Total Marks
Percentage
20%
50%
30%
100%
TEXT BOOK
DEITEL & DEITEL (Latest Edition). C How To Program by PEARSON/ Prentice Hall
REFERENCES
1. Jeri R. Hanley, Elliot B. Koffman, `C Program design for Engineers`, 2nd Edition,
Addison Wesley, 2000.
2. Pradip Dey & Manas Ghosh, `Computer Fundamentals and Programming in C`,
Oxford University Press, 2006.
3. H. M. Dietel & P.J. Dietel, `C How to Program`, Prentice Hall, 2004.
4. Behrouz A. Forouzan & Richard F. Gilberg, `A Structured Programming Approach
Using c`, Brooks/Cole, 2001.
3
COURSE TOPICS
WEEK
1
(2 hours)
CHAPTER
1
INTRODUCTION TO C
PROGRAMMING
2-3
(2 hours)
2
INPUT AND OUTPUT
OPERATION
4
(2 hours)
3
CONTROL FLOW
5
(4 hours)
3
CONTROL FLOW
6
(2 hours)
3
CONTROL FLOW
4
FUNCTIONS
CONTENT/SUB-CHAPTER
INITIAL CONCEPT
i. Introduction to C programming
ii. Producing an executable program (compiling
& linking)
iii. Constants, Variables and Data types types (int,
float,string,char)
iv. Operators and precedence
v. Data type conversion
i. Printf and Scanf
ii. Working with file
SELECTION STATEMENTS
i. If.else
ii. Switch case
REPETITIVE STATEMENTS
i. For
ii. While() and Dowhile()
SELECTION STATEMENTS
i. Break/continue
FUNCTIONS
i. Introduction to function
ii. Function prototype
iii. Function definition
4
FUNCTIONS
5
SIMPLE ARRAY
8
(2 hours)
5
SIMPLE ARRAYS
9
(2 hours)
6
POINTER
INTRODUCTION TO POINTER
i. Pointer declaration and synatx
ii. call by value and call by reference
10
(2 hours)
6
POINTER
INTRODUCTION TO POINTER
i. Using pointer with functions and array
11
(2 hours)
7
STRUCTURES
12
12,13,14
FUNCTIONS
i. Function call
ii. Recursive function
SIMPLE ARRAY
i. Array declaration and syntax
i. One dimensional array
ii. Two dimensional array
STRUCTURE
i. Structure declaration and syntax
ii. Structure initialization
iii. Pointers to structure
TEST 2 (Chapter 4 7)
MINI PROJECT WORKS
Chapter 1
Introduction to C Programming
6
LESSON OUTCOME
At the end of the lesson, students should be able to
describe and explain:
Introduction to C Programming Language
Development Stages of C Program
Flowchart
Variables and Data types
Keywords and Constants
Operators and precedence
Data type conversion
7
What is a program?
A list of instructions.
Written in a programming language (c, c++, java).
Determines the behavior of a machine
(computer, robot).
Programming Language
A machine language that has its own set of
grammatical rules.
It is used to instruct a machine to perform
specific tasks.
History
C was developed in 1972 by Dennis Ritchie at
Bell Laboratories.
Based on a programming language called B
(which is derived from BCPL language).
C was designed and developed for the
development of UNIX operating system.
C has been widely used to develop many type
of application software from a basic to
operating system.
BCPL- Basic Combined Programming Language
10
Christopher
Strachey
Uni. Cambridge
& Uni. London
Complex thus
not popular
Martin Richards
Powerful and
Portable
One data type
B
Ken Thompson
& Dennis Ritchie
Bell Labs
One data type
1972
BCPL
1969
CPL (Combined
Programming
Language)
1966
1963
History
C
Dennis Ritchie
at Bell
Laboratories
Based on a
programming
language called
B
Designed and
developed for
the
development of
UNIX operating
system
11
12
13
Editing
Process of writing the C source code.
Using editor program (i.e. vi and emacs for
Linux, Notepad for Windows)
Software package provides programming
environment
Integrated editor
Managing and maintaining source code
i.e. C++ Builder, Code::Blocks, Dev-C++, Microsoft
Visual Studio
14
15
Linking
Process of combining generated object files.
Add required codes from C standard library.
Produce an executable file.
16
Executing
Run the program to check whether it produce
the desired output.
Testing stage where you check the output of
your program.
The program does not produces the suppose
output, then you have made logic (semantic)
error.
17
C Program Layout
C program consists of two sections:
Pre-processor directives
Main function
pre-processor directives
main()
Pre-processor section
{
Main function section
statements
}
18
Pre-processor Directives
Specify what compiler should do before
compilation.
Include header files.
Header file keep information about the library
functions (printf, scanf).
Pre-processor directives begins with the #
symbol.
19
Main Function
The program starts its execution.
Define the program definition.
20
An Example of C Program
Sample output:
C program example
21
Additional - Comments
A comment, not actually part of the program.
Provide information on what the program
does.
Begin with /* and end with */ or written as
//.
Good habit to include comments.
Keep inform what are the code actually doing.
22
Important line in C
Symbol # indicates that this is a pre-processor
directive
Include stdio.h header file in our program
stdio.h contains information on
input/output routines.
We are using the printf() function from
stdio.h
23
24
25
26
27
Flowchart
Basic shapes of flowchart
point / terminal
data / process
decision / option
yes
Flowchart
Sequence flow
start
Boil water
Coffee = 1 spoon
Sugar = 2 spoon
Pour coffee and
sugar into a cup
Add water
Display coffee is
ready
end
29
start
Flowchart
Boil water
Looping flow
Pour coffee into a
cup
Add sugar
Add water
yes
Over sweet?
no
end
30
Flowchart
Combination
flow
start
A
Boil water
end
no
Over sweet?
yes
Add water
end
no
Tasteless?
yes
Add sugar
31
EXAMPLE 1
Read 1 integer number entered by the user via a keyboard. Check and display
the output, which one is the positive and negative values.
32
EXAMPLE 2
Read 2 integer numbers entered by the user via a keyboard. Compare and
display the output, which one is greater between two inputs.
33
Exercise
Draw a flowchart to solve below problem:
Prepare cupcakes. Ingredients are flour, yeast,
and sugar. Make sure you taste the dough
before baking process.
Find solution to calculate the average marks for
3 of student. Then, display the average value.
34
ANSWER
#include<stdio.h>
main(){
int mark1,mark2,mark3;
float average=0;
printf("Enter marks for student 1:");
scanf("%d",&mark1);
printf("Enter mark for student 2:");
scanf("%d",&mark2);
printf("Enter marks for student 3:");
scanf("%d",&mark3);
average = (mark1 + mark2 + mark3) / 3.0;
printf("The average marks for all students entered is %.2f\n", average);
return 0;
}
35
EXAMPLE
Draw a flowchart to solve below problem:
Read 10 integer numbers, entered by a user
through a keyboard. Search a highest and lowest
number. Display the output which are the
highest and lowest number.
ANSWER
start
Highest?
no
yes
Keep into high variables
10 input integers?
no
yes
Display the highest and lowest integer
End
Variables
Every variable has name, type and value.
Variable name / Identifier :
Must start with character or underscore ( _ ), cannot
start with number or symbol and not a keyword .
Must not include any space and it is letter case sensitive.
Eg:
stud1, Stud1, stud_name, _student (valid)
@stud, stud name, 1stud (invalid)
Variable type :
Based on the data type integer, floating point numbers
and characters.
The value can be change any time.
Whenever a new value is placed into a variable, it
replaces the previous value.
Variables
Variable must be declare / initialize before it can be used
in the next line of statements.
Variable declaration :
To declare a variable with a name and suitable data
type.
Eg:
int student; int staff;
double x, y;
Variable initialization :
To declare a variable and assign a certain value to the
varible.
Eg:
int student=5; int staff=1;
double x=1.12;
double y=9.999;
Data Types
Integer:
Whole number (decimal).
Positive, negative or zero : 25, 0, -9.
Variable declaration:
int x;
Floating point numbers:
double / float
Variable declaration: double y;
float z;
Characters:
A character is a single letter, digit, symbol or space. Eg:
m,B,#,3,=,@, .
A string is series of characters .
Eg:
student ,F#,$35,
class_93,ALI BABA.
Eg
Sample: Integer & float
#include<stdio.h>
int main()
{
int a, b;
float c;
printf("Enter two numbers to add\n");
scanf("%d%d",&a,&b);
printf(Value of entered number a : %d\n",a);
c = (float)a / b;
printf(Average of entered numbers = %2f\n",c);
return 0;
}
Sample : Character
#include <stdio.h>
int main()
{
char string[] = "Hello World";
printf("%s\n", string);
return 0;
}
Keywords
Special words reserved for C.
Cannot be used as variable names.
Eg: data types (int,void,const,static)
instruction statements
(if,for,case,break,return,include)
Constants
Constant name is declared just like variable name.
Constant value cannot be changed after its declaration.
2 ways for constant declaration :
const double pi = 3.147; or
#define pi 3.147
Assignment Operator
Arithmetic Operators
Operators
Symbol
Addition
Substraction
Multiplication
Division
Modulus
Ex : Arithmetic Operators
#include <stdio.h>
int main()
{
int first, second, add, subtract, multiply;
int divide, modulus;
printf("Enter two integers\n");
scanf("%d%d", &first, &second);
add = first + second;
subtract = first - second;
multiply = first * second;
divide = first / second;
modulus= first % second;
printf("Sum = %d\n",add);
printf("Difference = %d\n",subtract);
printf("Multiplication = %d\n",multiply);
printf("Division = %d\n",divide);
printf("Modules = %d\n",modulus);
return 0;
}
Output of program:
Relational Operators
Operator
Symbol
Less than
<
>
Greater than or
equal to
>=
Equal to
==
Not equal to
!=
Also
known as
Equality
Operators
Logical Operators
Operators
Symbol
NOT
AND
&&
OR
||
Expression
Value
!1
!0
Expression
Value
0 && 0
0 && 1
1 && 0
1 && 1
Expression
Value
0 || 0
0 || 1
1 || 0
1 || 1
Increment and
Decrement Operators
Increment operator ++
add 1
Increment and
Decrement Operators
Example
y
int y,c,x;
y=5,c=1,x=3;
c++;
x+=2;
--y;
y=c++;
y=++x;
(in memory)
50
Operator Precedence
Highest Precedence / Priority
parenthesis,
logical op.
( ) !
Function call,
arithmetic op.
* / %
arithmetic op.
+ -
relational op.
Addition, subtraction
Comparisons: less-than, ...
equality op.
== !=
logical op.
&&
Logical AND
logical op.
||
Logical OR
Example
The following table shows all the arithmetic operators supported by the C
language. Assume variable A holds 10 and variable B holds 20, then calculate:
Operator Description
Example
Answer
A+B
30
AB
10
AB
200
BA
B%A
++
A++
11
--
9
52
Operator Precedence
Eg:
3 + 4 5 = 4 5 + 3 = 23
2 + (3 4) = (3 4)+2 = 14
Ex 1
7 % 3 + 4 * 2 (1 + 12) / 4
Ans:6
Ex 2
Let x=4 ,y =5,z=9.
x > 5 || y < 7 && z != 2
Ans:Yes
Program output:
Line 1 - Value of c is 31
Line 2 - Value of c is 11
Line 3 - Value of c is 210
Line 4 - Value of c is 2
Line 5 - Value of c is 1
Line 6 - Value of c is 21
Line 7 - Value of c is 22
Exercise
What data types would you use to hold the
following data?
Customer name
Your house number
A price
Car registrations
The time
A six digit number
Write C statements to declare them all.
55
num2
num3
56
Exercise : Answer
num1
num2
num3
Output of program:
57
int main() {
int x = 10, y, z;
x++;
y = ++x;
z= x + y-}
58
int a = 0, b = 10, c = 5, d = 8;
b = ++a * b;
a *= c++;
c--;
d /= --c;
b = a % c++;
59
Chapter 2
LESSON OUTCOME
At the end of the lesson, students should be able to
describe and explain:
Input and Output Devices
printf statement
scanf statement
Field Widths and Precisions
Printing Literals and Escape Sequences
61
62
63
printf
display the
data at the
monitor
scanf
64
Printing Integers
Integer
Whole number (no decimal point): 25, -9, 0
Positive, negative, or zero
Only minus sign prints by default
66
Printing Integers
Conversion Specifier Description
d
o
u
x or X
67
68
The following declaration and initialization create a string consisting of the word "Hello". To hold
the null character at the end of the array, the size of the character array containing the string is
one more than the number of characters in the word "Hello.
If you follow the rule of array initialization then you can write the above statement as follows
#include <stdio.h>
int main () {
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
printf("Greeting message: %s\n", greeting );
return 0;
}
70
Description
Read an optionally signed decimal integer. The corresponding
argument is a pointer to integer.
Read an octal integer. The corresponding argument is a pointer to
unsigned integer.
Read a hexadecimal integer. The corresponding argument is a
pointer to unsigned integer.
Read a floating-point value. The corresponding argument is a
pointer to a floating-point variable.
72
73
int x = 123;
printf(%2d, x) output:123
printf(%5d, x) output: 123
printf(%-5d, x) output:123
printf(%.5d, x) output:00123
printf(%7.5d, x) output:00123
76
float y = 4.56;
printf(%2f, x) output:4.56
printf(%9f, x) output: 4.560000
printf(%-9f, x) output:4.560000
printf(%.4f, x) output:4.5600
printf(%.1f, x) output:4.6
printf(%6.3f, x) output: 4.560
77
char a = Z;
char b[] = ZOO;
printf(%2c, a) output: Z
printf(%-2c, a) output:Z
printf(%2s, b) output:ZOO
printf(%5s, b) output: ZOO
printf(%-5s, x) output:ZOO
78
79
\"
\?
\\
\a
\b
\f
\n
\r
\t
\v
80
Exercise
Write a statement to accomplish each of the following:
i. Define the variables x, y, z and result to be of type
int.
ii. Prompt the user to enter three integers.
iii. Read three integers from the keyboard and store
them in the variables x, y and z.
iv. Compute the product of the three integers
contained in variables x, y and z, and assign the
result to the variable result.
v. Print the result.
81
Answer
82