(O'SMART) ELE 276 Lecture Notes-Compressed
(O'SMART) ELE 276 Lecture Notes-Compressed
(O'SMART) ELE 276 Lecture Notes-Compressed
ELE 276
• This lecture material and other distributed materials for this ELE276
course are not for sale.
• This lecture material is largely based on the programming text “C
How To Program” by Paul Deitel and Harvey Deitel.
• This lecture material is by no means a substitute for the
aforementioned programming text which students of this ELE276
course are advised to get a copy at the University Library, University
e-Library or University Resource Center.
• Students are also advised to get their system installed with C/C++
compiler for hands-on/practical programming exercises. You may
check (http://www.stroustrup.com/compilers.html) for suitable
compilers.
• For additional technical details, students are advised to consult the C
Standard Documentation or you may check
(http://www.gnu.org/software/gnu-c-manual/gnu-c-manual.html).
2
1.1 Introduction
• We will learn
– The C programming language
– Structured programming and proper programming techniques
• This course is appropriate for
– Technically oriented people with little or no programming
experience
– Experienced programmers who want a deep and rigorous
treatment of the language
3
1.7 History of C
• C
– Evolved by Ritchie from two previous programming
languages, BCPL and B
– Used to develop UNIX
– Used to write modern operating systems
– Hardware independent (portable)
– By late 1970's C had evolved to "Traditional C"
• Standardization
– Many slight variations of C existed, and were incompatible
– Committee formed to create a "unambiguous, machine-
independent" definition
– Standard created in 1989, updated in 1999
10
ELE 276
• This lecture material and other distributed materials for this ELE276
course are not for sale.
• This lecture material is largely based on the programming text “C
How To Program” by Paul Deitel and Harvey Deitel.
• This lecture material is by no means a substitute for the
aforementioned programming text which students of this ELE276
course are advised to get a copy at the University Library, University
e-Library or University Resource Center.
• Students are also advised to get their system installed with C/C++
compiler for hands-on/practical programming exercises. You may
check (http://www.stroustrup.com/compilers.html) for suitable
compilers.
• For additional technical details, students are advised to consult the C
Standard Documentation or you may check
(http://www.gnu.org/software/gnu-c-manual/gnu-c-manual.html).
Downloaded from www.schoolnetwork.io 2
Basic Definitions
• Computer program is just a collection of the
instructions necessary to solve a specific problem.
• The basic operations of a computer system form
what is known as the computer’s instruction set.
• the approach or method that is used to solve the
problem is known as an algorithm.
• Programming language can be broadly divided
into two types: Low Level Languages and High
Level Languages.
Downloaded from www.schoolnetwork.io 5
Basic Definitions
• Low level languages can be subdivided into
machine level and assembly level language.
• In machine level language computer only
understand digital numbers i.e. in the form of 0
and 1 (binary digit). This type of program is not
portable, difficult to implement/maintain and also
error prone.
Downloaded from www.schoolnetwork.io 6
Basic Definitions
• The assembly language is modified version of
machine level language where instructions are
given in English like word as ADD, SUM, MOV
etc.
• It is easy to write and understand but not
understand by the machine.
• So the translator used here is assembler to
translate into machine level.
• Programmer has to know low level language
details. In the assembly level language the data are
stored in the computer register, which varies for
different computer. Hence it is not portable.
Downloaded from www.schoolnetwork.io 7
Basic Definitions
• High level language are machine independent,
means it is portable.
• The language in this category is MATLAB,
C/C++, Java, Pascal, Cobol, Fortran etc.
• High level languages are not understood by the
machine. So there is need to translate by the
translator into machine level.
• A translator is software which is used to translate
high level language as well as low level language
in to machine level language.
Downloaded from www.schoolnetwork.io 8
Basic Definitions
• There are three types of translator: Compiler,
Interpreter and Assembler.
• Compiler and interpreter are used to convert the
high level language into machine level language.
• The program written in high level language is
known as source program and the corresponding
machine level language program is called as object
program.
Downloaded from www.schoolnetwork.io 9
Basic Definitions
• Both compiler and interpreter perform the same
task but there working is different.
• Compiler read the program at-a-time and searches
the error and lists them. If the program is error
free then it is converted into object program.
• When program size is large then compiler is
preferred.
• Whereas interpreter read only one line of the
source code and convert it to object code. By
checking error, statement by statement, it takes
more time.
Downloaded from www.schoolnetwork.io 10
Basic Definitions
• Typical errors reported during the phase of
compilation might be due to an expression that has
unbalanced parentheses (syntax error), or due to
the use of a variable that is not “defined”
(semantic error).
• The process of compiling and linking a program is
often called building.
Downloaded from www.schoolnetwork.io 11
Basic Definitions
• Results that are displayed by the program, known
as output, appear in a window, sometimes called
the console.
• If the program does not produce the desired
results, it is necessary to go back and reanalyze the
program’s logic. This is known as the debugging
phase, during which an attempt is made to remove
all the known problems or bugs from the program.
Downloaded from www.schoolnetwork.io 12
Basic Definitions
• The process of editing, compiling, running, and
debugging programs is often managed by a single
integrated application known as an Integrated
Development Environment, or IDE for short.
• An IDE is a windows-based program that allows
us to easily manage large software programs, edit
files in windows, and compile, link, run, and
debug programs.
Downloaded from www.schoolnetwork.io 13
Basic Definitions
• On Mac OS X, CodeWarrior and Xcode are two
IDEs that are used by many programmers.
• Under Windows, Microsoft Visual Studio is a
good example of a popular IDE.
• Kylix is a popular IDE for developing applications
under Linux.
• Most IDEs also support program development in
several different programming languages in
addition to C, such as C# and C++.
Downloaded from www.schoolnetwork.io 14
Structure of a C Program
• 1 ) Comment line
• 2) Preprocessor directive
• 3 ) Global variable declaration
• 4) main function( )
• {
• Local variables;
• Statements;
• }
• User defined function
• }
• }
Downloaded from www.schoolnetwork.io 15
Structure of a C Program
• Comment line:
• It indicates the purpose of the program. It is
represented as: /*……………………………..*/
• Comment line is used for increasing the
readability of the program.
• It is useful in explaining the program and
generally used for documentation.
• It is enclosed within the decimeters.
• Comment line can be single or multiple line but
should not be nested.
• It can be anywhere in the program except inside
string constant & character constant.
Downloaded from www.schoolnetwork.io 16
Structure of a C Program
• Preprocessor Directive:
• #include<stdio.h> tells the compiler to include
information about the standard input/output
library.
• It is also used in symbolic constant such as
#define PI 3.14(value).
• The stdio.h (standard input output header file)
contains definition & declaration of system
defined function such as printf( ), scanf( ), pow( )
etc.
• Generally printf() function used to display and
scanf() function used to read value.
Downloaded from www.schoolnetwork.io 17
Structure of a C Program
• Global Declaration:
• This is the section where variable are declared
globally so that it can be access by all the
functions used in the program.
• And it is generally declared outside the main
function.
Downloaded from www.schoolnetwork.io 18
Structure of a C Program
• main()
• It is the user defined function and every program has one
main() function from where actually program is started and
it is encloses within the pair of curly braces.
• The main( ) function can be anywhere in the program but
in general practice it is placed in the first position.
• Syntax :
• main()
• {
• ……..
• ……..
• ……..
• }
Downloaded from www.schoolnetwork.io 19
Structure of a C Program
• The main( ) function return value when it declared by data
type as
• int main( )
• {
• return 0
• }
• The main function does not return any value when void
(means null/empty) as
• void main(void ) or void main()
• {
• printf (“C language”);
• }
• Output: C language
Downloaded from www.schoolnetwork.io 20
Structure of a C Program
• The program execution start with opening braces
and end with closing brace.
• And in between the two braces declaration part as
well as executable part is mentioned.
• And at the end of each line, the semi-colon is
given which indicates statement termination.
Downloaded from www.schoolnetwork.io 21
Practice Exercise
One(1)
Downloaded from www.schoolnetwork.io 22
A Simple C Program:
Printing a Line of Text
1 /* Fig. 2.1: fig02_01.c
2 A first program in C */
3 #include <stdio.h>
4
5 int main()
6 {
7 printf( "Welcome to C!\n" );
8
9 return 0;
10 }
Welcome to C!
• Comments
– Text surrounded by /* and */ is ignored by computer
– Used to describe program
• #include <stdio.h>
– Preprocessor directive
• Tells computer to load contents of a certain file
– <stdio.h> allows standard input/output operations
Downloaded from www.schoolnetwork.io 23
A Simple C Program:
Printing a Line of Text
• int main()
– C++ programs contain one or more functions, exactly one of
which must be main
– Parenthesis used to indicate a function
– int means that main "returns" an integer value
– Braces ({ and }) indicate a block
• The bodies of all functions must be contained in braces
Downloaded from www.schoolnetwork.io 24
A Simple C Program:
Printing a Line of Text
• printf( "Welcome to C!\n" );
– Instructs computer to perform an action
• Specifically, prints the string of characters within quotes (“ ”)
– Entire line called a statement
• All statements must end with a semicolon (;)
– Escape character (\)
• Indicates that printf should do something out of the ordinary
• \n is the newline character
Downloaded from www.schoolnetwork.io 25
A Simple C Program:
Printing a Line of Text
• return 0;
– A way to exit a function
– return 0, in this case, means that the program terminated
normally
• Right brace }
– Indicates end of main has been reached
• Linker
– When a function is called, linker locates it in the library
– Inserts it into object program
– If function name is misspelled, the linker will produce an
error because it will not be able to find function in the
library
Downloaded from www.schoolnetwork.io 26
Practice Exercise
Two(2)
1 /* Fig. 2.5:
Downloaded fig02_05.c
from www.schoolnetwork.io 27
2 Addition program */ Outline
3 #include <stdio.h>
4 1. Initialize variables
5 int main()
6 { 2. Input
7 int integer1, integer2, sum; /* declaration */
8 2.1 Sum
9 printf( "Enter first integer\n" ); /* prompt */
10 scanf( "%d", &integer1 ); /* read an integer */
3. Print
11 printf( "Enter second integer\n" ); /* prompt */
12 scanf( "%d", &integer2 ); /* read an integer */
13 sum = integer1 + integer2; /* assignment of sum */
14 printf( "Sum is %d\n", sum ); /* print sum */
15
16 return 0; /* indicate that program ended successfully */
17 }
Memory Concepts
• Variables
– Variable names correspond to locations in the computer's
memory
– Every variable has a name, a type, a size and a value
– Whenever a new value is placed into a variable (through
scanf, for example), it replaces (and destroys) the previous
value
– Reading variables from memory does not change them
• A visual representation
integer1 45
Downloaded from www.schoolnetwork.io 32
Arithmetic
• Arithmetic calculations
– Use * for multiplication and / for division
– Integer division truncates remainder
• 7 / 5 evaluates to 1
– Modulus operator(%) returns the remainder
• 7 % 5 evaluates to 2
• Operator precedence
– Some arithmetic operators act before others (i.e.,
multiplication before addition)
• Use parenthesis when needed
– Example: Find the average of three variables a, b and c
• Do not use: a + b + c / 3
• Use: (a + b + c ) / 3
Downloaded from www.schoolnetwork.io 33
Arithmetic
• Arithmetic operators:
C op era tion Arithm etic Alg eb ra ic C exp ression
op era tor exp ression
Addition + f+7 f + 7
Subtraction - p–c p - c
Multiplication * bm b * m
Division / x/y x / y
Modulus % r mod s r % s
• Rules of operator precedence:
Operator(s) Operation(s) Order of evaluation (precedence)
() Parentheses Evaluated first. If the parentheses are nested, the
expression in the innermost pair is evaluated first. If there
are several pairs of parentheses “on the same level” (i.e.,
not nested), they are evaluated left to right.
*, /, or % Multiplication,Divi Evaluated second. If there are several, they are
sion, Modulus evaluated left to right.
+ or - Addition Evaluated last. If there are several, they are
Subtraction evaluated left to right.
Downloaded from www.schoolnetwork.io 34
Decision Making: Equality and Relational
Operators
• Executable statements
– Perform actions (calculations, input/output of data)
– Perform decisions
• May want to print "pass" or "fail" given the value of a
test grade
• if control structure
– Simple version in this section, more detail later
– If a condition is true, then the body of the if statement
executed
• 0 is false, non-zero is true
– Control always resumes after the if structure
• Keywords
– Special words reserved for C
– Cannot be used as identifiers or variable names
Downloaded from www.schoolnetwork.io 35
Decision Making: Equality and Relational
Operators
Keyw ord s
auto double int struct
break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while
Downloaded from www.schoolnetwork.io 37
Practice Exercise
Three(3)
1 /* Fig. 2.13:
Downloaded fromfig02_13.c
www.schoolnetwork.io 38
2 Using if statements, relational Outline
3 operators, and equality operators */
4 #include <stdio.h>
1. Declare variables
5
6 int main()
7 { 2. Input
8 int num1, num2;
9
2.1 if statements
10 printf( "Enter two integers, and I will tell you\n" );
11 printf( "the relationships they satisfy: " );
12 scanf( "%d%d", &num1, &num2 ); /* read two integers */ 3. Print
13
14 if ( num1 == num2 )
15 printf( "%d is equal to %d\n", num1, num2 );
16
17 if ( num1 != num2 )
18 printf( "%d is not equal to %d\n", num1, num2 );
19
20 if ( num1 < num2 )
21 printf( "%d is less than %d\n", num1, num2 );
22
23 if ( num1 > num2 )
24 printf( "%d is greater than %d\n", num1, num2 );
25
26 if ( num1 <= num2 )
27 printf( "%d is less than or equal to %d\n",
28 num1, num2 );
29
Downloaded from www.schoolnetwork.io 39
30 if ( num1 >= num2 ) Outline
31 printf( "%d is greater than or equal to %d\n",
3.1 Exit main
32 num1, num2 );
33
35 }
Practice Exercise
Four(4)
Downloaded from www.schoolnetwork.io 41
#include <stdio.h>
int main (void)
{
int v1, v2, sum; //v1,v2,sum are variables and int is data type declared
v1 = 150;
v2 = 25;
sum = v1 + v2;
printf ("The sum of %i and %i is= %i\n", v1, v2, sum);
return 0;
}
Output: The sum of 150 and 25 is=175
Downloaded from www.schoolnetwork.io 1
ELE 276
• This lecture material and other distributed materials for this ELE276
course are not for sale.
• This lecture material is largely based on the programming text “C
How To Program” by Paul Deitel and Harvey Deitel.
• This lecture material is by no means a substitute for the
aforementioned programming text which students of this ELE276
course are advised to get a copy at the University Library, University
e-Library or University Resource Center.
• Students are also advised to get their system installed with C/C++
compiler for hands-on/practical programming exercises. You may
check (http://www.stroustrup.com/compilers.html) for suitable
compilers.
• For additional technical details, students are advised to consult the C
Standard Documentation or you may check
(http://www.gnu.org/software/gnu-c-manual/gnu-c-manual.html).
Downloaded from www.schoolnetwork.io 2
Introduction
• Before writing a program:
– Have a thorough understanding of the problem
– Carefully plan an approach for solving it
• While writing a program:
– Know what “building blocks” are available
– Use good programming principles
Downloaded from www.schoolnetwork.io 3
Algorithms
• Computing problems
– All can be solved by executing a series of actions in a
specific order
• Algorithm: procedure in terms of
– Actions to be executed
– The order in which these actions are to be executed
• Program control
– Specify order in which statements are to executed
Downloaded from www.schoolnetwork.io 4
Pseudocode
• Pseudocode
– Artificial, informal language that helps us develop
algorithms
– Similar to everyday English
– Not actually executed on computers
– Helps us “think out” a program before writing it
• Easy to convert into a corresponding C++ program
• Consists only of executable statements
Downloaded from www.schoolnetwork.io 5
Control Structures
• Sequential execution
– Statements executed one after the other in the order written
• Transfer of control
– When the next statement executed is not the next one in
sequence
– Overuse of goto statements led to many problems
• Bohm and Jacopini
– All programs written in terms of 3 control structures
• Sequence structures: Built into C. Programs executed
sequentially by default
• Selection structures: C has three types: if, if/else, and
switch
• Repetition structures: C has three types: while, do/while
and for
Downloaded from www.schoolnetwork.io 6
Control Structures
• Flowchart
– Graphical representation of an algorithm
– Drawn using certain special-purpose symbols connected by
arrows called flowlines
– Rectangle symbol (action symbol):
• Indicates any type of action
– Oval symbol:
• Indicates the beginning or end of a program or a section of code
• Single-entry/single-exit control structures
– Connect exit point of one control structure to entry point of
the next (control-structure stacking)
– Makes programs easy to build
Downloaded from www.schoolnetwork.io 7
false true
grade >= 60
true
product <= 1000 product = 2 * product
false
Downloaded from www.schoolnetwork.io 18
Formulating Algorithms
(Counter-Controlled Repetition)
• Counter-controlled repetition
– Loop repeated until counter reaches a certain value
– Definite repetition: number of repetitions is known
– Example: A class of ten students took a quiz. The grades
(integers in the range 0 to 100) for this quiz are available to
you. Determine the class average on the quiz
– Pseudocode:
Set total to zero
Set grade counter to one
While grade counter is less than or equal to ten
Input the next grade
Add the grade into the total
Add one to the grade counter
Set the class average to the total divided by ten
Print the class average
Downloaded from www.schoolnetwork.io 19
Practice Exercise
One(1)
Downloaded
1 /* Fig. from
3.6: www.schoolnetwork.io
fig03_06.c 20
2 Class average program with Outline
3 counter-controlled repetition */
4 #include <stdio.h> 1. Initialize Variables
5
6 int main()
2. Execute Loop
7 {
8 int counter, grade, total, average;
9
3. Output results
10 /* initialization phase */
11 total = 0;
12 counter = 1;
13
14 /* processing phase */
15 while ( counter <= 10 ) {
16 printf( "Enter grade: " );
17 scanf( "%d", &grade );
18 total = total + grade;
19 counter = counter + 1;
20 }
21
22 /* termination phase */
23 average = total / 10;
24 printf( "Class average is %d\n", average );
25
26 return 0; /* indicate program ended successfully */
27 }
Downloaded from www.schoolnetwork.io 21
Enter grade: 98
Outline
Enter grade: 76
Enter grade: 71
Enter grade: 87
Program Output
Enter grade: 83
Enter grade: 90
Enter grade: 57
Enter grade: 79
Enter grade: 82
Enter grade: 94
Class average is 81
Downloaded from www.schoolnetwork.io 22
Formulating Algorithms with Top-Down,
Stepwise Refinement
• Problem becomes:
Develop a class-averaging program that will process an
arbitrary number of grades each time the program is run.
– Unknown number of students
– How will the program know to end?
• Use sentinel value
– Also called signal value, dummy value, or flag value
– Indicates “end of data entry.”
– Loop ends when user inputs the sentinel value
– Sentinel value chosen so it cannot be confused with a regular
input (such as -1 in this case)
Downloaded from www.schoolnetwork.io 23
Formulating Algorithms with Top-Down,
Stepwise Refinement
• Top-down, stepwise refinement
– Begin with a pseudocode representation of the top:
Determine the class average for the quiz
– Divide top into smaller tasks and list them in order:
Initialize variables
Input, sum and count the quiz grades
Calculate and print the class average
• Many programs have three phases:
– Initialization: initializes the program variables
– Processing: inputs data values and adjusts program variables
accordingly
– Termination: calculates and prints the final results
Downloaded from www.schoolnetwork.io 24
Formulating Algorithms with Top-Down,
Stepwise Refinement
• Refine the initialization phase from Initialize
variables to:
Initialize total to zero
Initialize counter to zero
• Refine Input, sum and count the quiz grades to
Input the first grade (possibly the sentinel)
While the user has not as yet entered the sentinel
Add this grade into the running total
Add one to the grade counter
Input the next grade (possibly the sentinel)
Downloaded from www.schoolnetwork.io 25
Formulating Algorithms with Top-Down,
Stepwise Refinement
• Refine Calculate and print the class average to
If the counter is not equal to zero
Set the average to the total divided by the counter
Print the average
else
Print “No grades were entered”
Downloaded from www.schoolnetwork.io 26
Practice Exercise
Two(2)
Downloaded
1 /* Fig. from
3.8: www.schoolnetwork.io
fig03_08.c 27
2 Class average program with Outline
3 sentinel-controlled repetition */
4 #include <stdio.h> 1. Initialize Variables
5
6 int main() 2. Get user input
7 {
8 float average; /* new data type */ 2.1 Perform Loop
9 int counter, grade, total;
10
11 /* initialization phase */
12 total = 0;
13 counter = 0;
14
15 /* processing phase */
16 printf( "Enter grade, -1 to end: " );
17 scanf( "%d", &grade );
18
19 while ( grade != -1 ) {
20 total = total + grade;
21 counter = counter + 1;
22 printf( "Enter grade, -1 to end: " );
23 scanf( "%d", &grade );
24 }
Downloaded
25 from www.schoolnetwork.io 28
26 /* termination phase */ Outline
27 if ( counter != 0 ) {
28 average = ( float ) total / counter;
3. Calculate Average
29 printf( "Class average is %.2f", average );
30 }
31 else 3.1 Print Results
32 printf( "No grades were entered\n" );
33
34 return 0; /* indicate program ended successfully */
35 }
Practice Exercise
Three(3)
Downloaded
1 /* Fig. from
3.10:www.schoolnetwork.io
fig03_10.c 33
2 Analysis of examination results */ Outline
3 #include <stdio.h>
4
5 int main() 1. Initialize variables
6 {
7 /* initializing variables in declarations */ 2. Input data and
8 int passes = 0, failures = 0, student = 1, result; count passes/failures
9
10 /* process 10 students; counter-controlled loop */
11 while ( student <= 10 ) { 3. Print results
12 printf( "Enter result ( 1=pass,2=fail ): " );
13 scanf( "%d", &result );
14
15 if ( result == 1 ) /* if/else nested in while */
16 passes = passes + 1;
17 else
18 failures = failures + 1;
19
20 student = student + 1;
21 }
22
23 printf( "Passed %d\n", passes );
24 printf( "Failed %d\n", failures );
25
26 if ( passes > 8 )
27 printf( "Raise tuition\n" );
28
29 return 0; /* successful termination */
30 }
Downloaded from www.schoolnetwork.io 34
Enter Result (1=pass,2=fail): 1
Outline
Enter Result (1=pass,2=fail): 2
Enter Result (1=pass,2=fail): 2
Enter Result (1=pass,2=fail): 1
Program Output
Enter Result (1=pass,2=fail): 1
Enter Result (1=pass,2=fail): 1
Enter Result (1=pass,2=fail): 2
Enter Result (1=pass,2=fail): 1
Enter Result (1=pass,2=fail): 1
Enter Result (1=pass,2=fail): 2
Passed 6
Failed 4
Downloaded from www.schoolnetwork.io 35
Assignment Operators
• Assignment operators abbreviate assignment
expressions
c = c + 3;
can be abbreviated as c += 3; using the addition assignment
operator
• Statements of the form
variable = variable operator expression;
can be rewritten as
variable operator= expression;
• Examples of other assignment operators:
d -= 4 (d = d - 4)
e *= 5 (e = e * 5)
f /= 3 (f = f / 3)
g %= 9 (g = g % 9)
Downloaded from www.schoolnetwork.io 36
COMPUTER
PROGRAMMING II
ELE 276
DEFINITIONS OF USEFUL
TERMS AND CONCEPTS
FOR LECTURE THREE (3)
This lecture material and
other distributed materials
for this ELE276 course are
not for sale.
Downloaded from www.schoolnetwork.io
Character set:
A character denotes any alphabet, digit or special symbol used to represent information. Valid
alphabets, numbers and special symbols allowed in C are as shown below:
The alphabets, numbers and special symbols when properly combined form constants, variables
and keywords.
Identifiers:
Identifiers are user defined word used to name of entities like variables, arrays, functions,
structures etc. Rules for naming identifiers are:
1) name should only consists of alphabets (both upper and lower case), digits and underscore (_)
sign.
2) first characters should be alphabet or underscore
3) name should not be a keyword
4) since C is a case sensitive, the upper case and lower case considered differently, for example
code, Code, CODE etc. are different identifiers.
5) identifiers are generally given in some meaningful name such as value, net_salary, age, data
etc.
An identifier name may be long, some implementation recognizes only first eight characters,
most recognize 31 characters. ANSI standard compiler recognize 31 characters. Some invalid
identifiers are 5cb, int, res#, avg no etc.
Keyword:
There are certain words reserved for doing specific task, these words are known as reserved word
or keywords. These words are predefined and always written in lower case or small letter. These
Downloaded from www.schoolnetwork.io
keywords can’t be used as a variable name as it assigned with fixed meaning. Some examples are
int, short, signed, unsigned, default, volatile, float, long, double, break, continue, typedef, static,
do, for, union, return, while, do, extern, register, enum, case, goto, struct, char, auto, const etc.
Data types:
Data types refer to an extensive system used for declaring variables or functions of different
types before its use. The type of a variable determines how much space it occupies in storage and
how the bit pattern stored is interpreted. The value of a variable can be changed any time.
C has the following 4 types of data types:
Basic built-in data types: int, float, double, char
Enumeration data type: enum
Derived data type: pointer, array, structure, union
Void data type: void
A variable declared to be of type int can be used to contain integral values only—that is, values
that do not contain decimal places. A variable declared to be of type float can be used for storing
floating- point numbers (values containing decimal places). The double type is the same as type
float, only with roughly twice the precision. The char data type can be used to store a single
character, such as the letter a, the digit character 6, or a semicolon similarly A variable declared
char can only store character type value.
There are two types of type qualifier in c:
Size qualifier: short, long
Sign qualifier: signed, unsigned
When the qualifier unsigned is used the number is always positive, and when signed is used
number may be positive or negative. If the sign qualifier is not mentioned, then by default sign
qualifier is assumed. The range of values for signed data types is less than that of unsigned data
type. Because in signed type, the left most bit is used to represent sign, while in unsigned type
this bit is also used to represent the value. The size and range of the different data types on a 16
bit machine is given below:
Downloaded from www.schoolnetwork.io
Constants:
Constant is a any value that cannot be changed during program execution. In C, any number,
single character, or character string is known as a constant. A constant is an entity that doesn’t
change whereas a variable is an entity that may change.
For example, the number 50 represents a constant integer value. The character string
"Programming in C is fun.\n" is an example of a constant character string. C constants can be
divided into two major categories:
Primary Constants
Secondary Constants
These constants are further categorized as (Numeric, Character and String Constants) shown in
the figure below:
Downloaded from www.schoolnetwork.io
Numeric constant:
Numeric constant consists of digits. It required minimum size of 2 bytes and max 4 bytes. It may
be positive or negative but by default sign is always positive. No comma or space is allowed
within the numeric constant and it must have at least 1 digit. The allowable range for integer
constants is -32768 to 32767. Truly speaking the range of an Integer constant depends upon the
compiler.
For a 16-bit compiler like Turbo C or Turbo C++ the range is –32768 to 32767. For a 32-bit
compiler the range would be even greater. Mean by a 16-bit or a 32-bit compiler, what range of
an Integer constant has to do with the type of compiler.
It is categorized a integer constant and real constant. An integer constants are whole number
which have no decimal point. Types of integer constants are:
Decimal constant: 0-------9(base 10)
Octal constant: 0-------7(base 8)
Hexa decimal constant: 0----9, A------F(base 16)
In decimal constant first digit should not be zero unlike octal constant first digit must be zero(as
076, 0127) and in hexadecimal constant first two digit should be 0x/ 0X (such as 0x24, 0x87A).
By default type of integer constant is integer but if the value of integer constant is exceeds range
then value represented by integer type is taken to be unsigned integer or long integer. It can also
be explicitly mention integer and unsigned integer type by suffix l/L and u/U.
Real constant:
Downloaded from www.schoolnetwork.io
It is also called floating point constant. To construct real constant we must follow these rules:
-real constant must have at least one digit.
-It must have a decimal point.
-It could be either positive or negative.
-Default sign is positive.
-No commas or blanks are allowed within a real constant. Ex.: +325.34
426.0
-32.76
To express small/large real constant exponent(scientific) form is used where number is written in
mantissa and exponent form separated by e/E. Exponent can be positive or negative integer but
mantissa can be real/integer type, for example 3.6*105=3.6e+5. By default type of floating point
constant is double, it can also be explicitly defined it by suffix of f/F.
Character Constant:
Character constant represented as a single character enclosed within a single quote. These can be
single digit, single special symbol or white spaces such as ‘9’,’c’,’$’, ‘ ’ etc. Every character
constant has a unique integer like value in machine’s character code as if machine using ASCII
(American standard code for information interchange). Some numeric value associated with each
upper and lower case alphabets and decimal integers are as:
A------------ Z ASCII value (65-90)
a-------------z ASCII value (97-122)
0-------------9 ASCII value (48-59)
; ASCII value (59)
String constant:
Set of characters are called string and when sequence of characters are enclosed within a double
quote (it may be combination of all kind of symbols) is a string constant. String constant has
zero, one or more than one character and at the end of the string null character(\0) is
automatically placed by compiler. Some examples are “,sarathina” , “908”, “3”,” ”, “A” etc. In C
although same characters are enclosed within single and double quotes it represents different
meaning such as “A” and ‘A’ are different because first one is string attached with null character
at the end but second one is character constant with its corresponding ASCII value is 65.
Symbolic constant:
Symbolic constant is a name that substitute for a sequence of characters and, characters may be
numeric, character or string constant.
Downloaded from www.schoolnetwork.io
Variables:
Variable is a data name which is used to store some data value or symbolic names for storing
program computations and results. The value of the variable can be change during the execution.
The rule for naming the variables is same as the naming identifier. Before used in the program it
must be declared. Declaration of variables specify its name, data types and range of the value
that variables can store depends upon its data types.
Variable initialization:
When we assign any initial value to variable during the declaration, is called initialization of
variables. When variable is declared but contain undefined value then it is called garbage value.
Expressions:
An expression is a combination of variables, constants, operators and function call. Expressions
consisting entirely of constant values are called constant expressions.
Operator:
This is a symbol use to perform some operation on variables, operands or with the constant.
Some operator required 2 operand to perform operation or some required single operation.
Several operators are there those are, arithmetic operator, assignment, increment, decrement,
logical, conditional, comma, size of , bitwise and others.
Arithmetic Operator:
This operator used for numeric calculation. These are of either Unary arithmetic operator, Binary
arithmetic operator. Where Unary arithmetic operator required only one operand such as +,-, ++,
--,!, tiled. And these operators are addition, subtraction, multiplication, division. Binary
arithmetic operator on other hand required two operand and its operators are +(addition), -
(subtraction), *(multiplication), /(division), %(modulus). But modulus cannot applied with
floating point operand as well as there are no exponent operator in c. Unary (+) and Unary (-) is
different from addition and subtraction. When both the operand are integer then it is called
integer arithmetic and the result is always integer. When both the operand are floating point then
it is called floating arithmetic and when operand is of integer and floating point then it is called
mix type or mixed mode arithmetic . And the result is in float type.
Assignment Operator:
A value can be stored in a variable with the use of assignment operator. The assignment
operator(=) is used in assignment statement and assignment expression. Operand on the left hand
side should be variable and the operand on the right hand side should be variable or constant or
any expression. When variable on the left hand side is occur on the right hand side then we can
avoid by writing the compound statement.
Increment and Decrement:
Downloaded from www.schoolnetwork.io
The Unary operator ++, --, is used as increment and decrement which acts upon single operand.
Increment operator increases the value of variable by one. Similarly decrement operator decrease
the value of the variable by one. And these operator can only used with the variable, but cann't
use with expression and constant as ++6.
It again categories into prefix post fix . In the prefix the value of the variable is incremented 1st,
then the new value is used, where as in postfix the operator is written after the operand (such as
m++, m--). Similarly in the postfix increment and decrement operator is used in the operation.
And then increment and decrement is perform.
Relational Operator:
It is use to compared value of two expressions depending on their relation. Expression that
contain relational operator is called relational expression. Here the value is assign according to
true or false value.
Conditional Operator:
It sometimes called as ternary operator. Since it required three expressions as operand and it is
represented as (? , :).
SYNTAX
exp1 ? exp2 :exp3
Here exp1 is first evaluated. It is true then value return will be exp2 . If false then exp3.
Comma Operator:
Comma operator is use to permit different expression to be appear in a situation where only one
expression would be used. All the expression are separator by comma and are evaluated from left
to right.
Sizeof Operator:
Size of operator is a Unary operator, which gives size of operand in terms of byte that occupied
in the memory. An operand may be variable, constant or data type qualifier. Generally it is used
make portable program(program that can be run on different machine) . It determines the length
of entities, arrays and structures when their size are not known to the programmer. It is also use
to allocate size of memory dynamically during execution of the program.
Bitwise Operator:
Bitwise operator permit programmer to access and manipulate of data at bit level.
Various bitwise operator enlisted are:
one's complement (~)
bitwise AND (&)
Downloaded from www.schoolnetwork.io
bitwise OR (|)
bitwise XOR (^)
left shift (<<)
right shift (>>)
These operator can operate on integer and character value but not on float and double. In bitwise
operator the function showbits( ) function is used to display the binary representation of any
integer or character value.
In one's complement all 0 changes to 1 and all 1 changes to 0. In the bitwise OR its value would
obtaining by 0 to 2 bits.
As the bitwise OR operator is used to set on a particular bit in a number. Bitwise AND the
logical AND.
It operate on 2operands and operands are compared on bit by bit basic. And hence both the
operands are of same type.
Logical or Boolean Operator:
Operator used with one or more operand and return either value zero (for false) or one (for true).
The operand may be constant, variables or expressions. And the expression that combines two or
more expressions is termed as logical expression.
C has three logical operators:
Operator Meaning
&& AND
|| OR
! NOT
Where logical NOT is a unary operator and other two are binary operator. Logical AND gives
result true if both the conditions are true, otherwise result is false. And logial OR gives result
false if both the condition false, otherwise result is true.
Downloaded from www.schoolnetwork.io
Downloaded from www.schoolnetwork.io
Downloaded from www.schoolnetwork.io 1
ELE 276
• This lecture material and other distributed materials for this ELE276
course are not for sale.
• This lecture material is largely based on the programming text “C
How To Program” by Paul Deitel and Harvey Deitel.
• This lecture material is by no means a substitute for the
aforementioned programming text which students of this ELE276
course are advised to get a copy at the University Library, University
e-Library or University Resource Center.
• Students are also advised to get their system installed with C/C++
compiler for hands-on/practical programming exercises. You may
check (http://www.stroustrup.com/compilers.html) for suitable
compilers.
• For additional technical details, students are advised to consult the C
Standard Documentation or you may check
(http://www.gnu.org/software/gnu-c-manual/gnu-c-manual.html).
Downloaded from www.schoolnetwork.io 2
Introduction
• This chapter introduces
– Additional repetition control structures
• for
• do/while
– switch multiple selection structure
– break statement
• Used for exiting immediately and rapidly from certain control
structures
– continue statement
• Used for skipping the remainder of the body of a repetition
structure and proceeding with the next iteration of the loop
Downloaded from www.schoolnetwork.io 3
Practice Exercise
One(1)
Download the Example source codes from http://snet.io/t397 to copy and paste easily.
1 /* Fig. 4.5:
Downloaded fromfig04_05.c
www.schoolnetwork.io 10
2 Summation with for */ Outline
3 #include <stdio.h>
4 1. Initialize variables
5 int main()
2. for repetition
6 { structure
7 int sum = 0, number;
8
9 for ( number = 2; number <= 100; number += 2 )
10 sum += number;
11
12 printf( "Sum is %d\n", sum );
13
14 return 0;
15 }
true
case a case a action(s) break
false
true
case b case b action(s) break
false
.
.
.
true
case z case z action(s) break
false
default action(s)
Downloaded from www.schoolnetwork.io 13
Practice Exercise
Two(2)
1 /* Fig. 4.7:
Downloaded fromfig04_07.c
www.schoolnetwork.io 14
2 Counting letter grades */ Outline
3 #include <stdio.h>
4
5 int main() 1. Initialize variables
6 {
7 int grade;
2. Input data
8 int aCount = 0, bCount = 0, cCount = 0,
9 dCount = 0, fCount = 0;
10 2.1 Use switch loop to
11 printf( "Enter the letter grades.\n" ); update count
12 printf( "Enter the EOF character to end input.\n" );
13
14 while ( ( grade = getchar() ) != EOF ) {
15
16 switch ( grade ) { /* switch nested in while */
17
18 case 'A': case 'a': /* grade was uppercase A */
19 ++aCount; /* or lowercase a */
20 break;
21
22 case 'B': case 'b': /* grade was uppercase B */
23 ++bCount; /* or lowercase b */
24 break;
25
26 case 'C': case 'c': /* grade was uppercase C */
27 ++cCount; /* or lowercase c */
28 break;
29
30 case 'D': case 'd': /* grade was uppercase D */
31 ++dCount; /* or lowercase d */
32 break;
33
Downloaded from www.schoolnetwork.io 15
34 case 'F': case 'f': /* grade was uppercase F */ Outline
35 ++fCount; /* or lowercase f */
36 break; 2.1 Use switch loop to
37 update count
38 case '\n': case' ': /* ignore these in input */
39 break; 3. Print results
40
41 default: /* catch all other characters */
42 printf( "Incorrect letter grade entered." );
43 printf( " Enter a new grade.\n" );
44 break;
45 }
46 }
47
48 printf( "\nTotals for each letter grade are:\n" );
49 printf( "A: %d\n", aCount );
50 printf( "B: %d\n", bCount );
51 printf( "C: %d\n", cCount );
52 printf( "D: %d\n", dCount );
53 printf( "F: %d\n", fCount );
54
55 return 0;
56 }
Downloaded from www.schoolnetwork.io 16
Enter the letter grades.
Outline
Enter the EOF character to end input.
A
B
Program Output
C
C
A
D
F
C
E
Incorrect letter grade entered. Enter a new grade.
D
A
B
action(s)
true
condition
false
Downloaded from www.schoolnetwork.io 20
Practice Exercise
Three(3)
1 /* Fig. 4.9:
Downloaded fromfig04_09.c
www.schoolnetwork.io 21
2 Using the do/while repetition structure */
Outline
3 #include <stdio.h>
1. Initialize variable
4
9 do {
12
13 return 0;
14 }
1 2 3 4 5 6 7 8 9 10 Program Output
Downloaded from www.schoolnetwork.io 22
Practice Exercise
Four(4)
1 /* Fig. 4.12:
Downloaded fig04_12.c
from www.schoolnetwork.io 25
2 Using the continue statement in a for structure */ Outline
3 #include <stdio.h>
4 1. Initialize variable
5 int main()
6 {
2. Loop
7 int x;
8
9 for ( x = 1; x <= 10; x++ ) { 3. Print
10
11 if ( x == 5 )
12 continue; /* skip remaining code in loop only
13 if x == 5 */
14
15 printf( "%d ", x );
16 }
17
18 printf( "\nUsed continue to skip printing the value 5\n" );
19 return 0;
20 }
1 2 3 4 6 7 8 9 10
Used continue to skip printing the value 5
Program Output
Downloaded from www.schoolnetwork.io 26
Logical Operators
• && ( logical AND )
– Returns true if both conditions are true
• || ( logical OR )
– Returns true if either of its conditions are true
• ! ( logical NOT, logical negation )
– Reverses the truth/falsity of its condition
– Unary operator, has one operand
• Useful as conditions in loops
Expression Result
true && false false
true || false true
!false true
Downloaded from www.schoolnetwork.io 27
Confusing Equality (==) and Assignment (=)
Operators
• Dangerous error
– Does not ordinarily cause syntax errors
– Any expression that produces a value can be used in control
structures
– Nonzero values are true, zero values are false
– Example using ==:
if ( payCode == 4 )
printf( "You get a bonus!\n" );
• Checks paycode, if it is 4 then a bonus is awarded
Downloaded from www.schoolnetwork.io 28
Confusing Equality (==) and Assignment (=)
Operators
– Example, replacing == with =:
if ( payCode = 4 )
printf( "You get a bonus!\n" );
• This sets paycode to 4
• 4 is nonzero, so expression is true, and bonus awarded no
matter what the paycode was
– Logic error, not a syntax error
Downloaded from www.schoolnetwork.io 29
Confusing Equality (==) and Assignment (=)
Operators
• lvalues
– Expressions that can appear on the left side of an equation
– Their values can be changed, such as variable names
• x = 4;
• rvalues
– Expressions that can only appear on the right side of an
equation
– Constants, such as numbers
• Cannot write 4 = x;
• Must write x = 4;
– lvalues can be used as rvalues, but not vice versa
• y = x;
Downloaded from www.schoolnetwork.io 30
Structured-Programming Summary
• Structured programming
– Easier than unstructured programs to understand, test,
debug and, modify programs
• Rules for structured programming
– Rules developed by programming community
– Only single-entry/single-exit control structures are used
– Rules:
1. Begin with the “simplest flowchart”
2. Any rectangle (action) can be replaced by two rectangles
(actions) in sequence
3. Any rectangle (action) can be replaced by any control
structure (sequence, if, if/else, switch, while,
do/while or for)
4. Rules 2 and 3 can be applied in any order and multiple times
Downloaded from www.schoolnetwork.io 31
Structured-Programming Summary
.
.
.
Downloaded from www.schoolnetwork.io 32
Structured-Programming Summary
Rule 3 - Replace any rectangle with a control structure
Rule 3
Rule 3
Rule 3
Downloaded from www.schoolnetwork.io 33
Structured-Programming Summary
• All programs can be broken down into 3 controls
– Sequence – handled automatically by compiler
– Selection – if, if/else or switch
– Repetition – while, do/while or for
• Can only be combined in two ways
– Nesting (rule 3)
– Stacking (rule 2)
– Any selection can be rewritten as an if statement, and any
repetition can be rewritten as a while statement
1
ELE 276
• This lecture material and other distributed materials for this ELE276
course are not for sale.
• This lecture material is largely based on the programming text “C
How To Program” by Paul Deitel and Harvey Deitel.
• This lecture material is by no means a substitute for the
aforementioned programming text which students of this ELE276
course are advised to get a copy at the University Library, University
e-Library or University Resource Center.
• Students are also advised to get their system installed with C/C++
compiler for hands-on/practical programming exercises. You may
check (http://www.stroustrup.com/compilers.html) for suitable
compilers.
• For additional technical details, students are advised to consult the C
Standard Documentation or you may check
(http://www.gnu.org/software/gnu-c-manual/gnu-c-manual.html).
Downloaded from www.schoolnetwork.io
Introduction
• Divide and conquer
– Construct a program from smaller pieces or components
• These smaller pieces are called modules
– Each piece more manageable than the original program
Practice Exercise
One(1)
Practice Exercise
Two(2)
Enter seed: 67
6 1 4 6 2
1 6 1 6 4
Practice Exercise
Three(3)
Player rolled 1 + 3 = 4
Point is 4
Player rolled 1 + 4 = 5
Player rolled 5 + 4 = 9
Player rolled 4 + 6 = 10
Player rolled 6 + 3 = 9
Player rolled 1 + 2 = 3
Player rolled 5 + 2 = 7
Player loses
Practice Exercise
Four(4)
global x is 1 on entering c
global x is 10 on exiting c
global x is 10 on entering c
global x is 100 on exiting c
local x in main is 5
return f( 2 ) + f( 1 )
return f( 1 ) + f( 0 ) return 1
return 1 return 0
Practice Exercise
Five(5)
Enter an integer: 1
Fibonacci(1) = 1
Enter an integer: 5
Fibonacci(5) = 5
Enter an integer: 6
Fibonacci(6) = 8
Enter an integer: 10
Fibonacci(10) = 55
Enter an integer: 20
Fibonacci(20) = 6765
Enter an integer: 30
Fibonacci(30) = 832040
Enter an integer: 35
Fibonacci(35) = 9227465
ELE 276
• This lecture material and other distributed materials for this ELE276
course are not for sale.
• This lecture material is largely based on the programming text “C
How To Program” by Paul Deitel and Harvey Deitel.
• This lecture material is by no means a substitute for the
aforementioned programming text which students of this ELE276
course are advised to get a copy at the University Library, University
e-Library or University Resource Center.
• Students are also advised to get their system installed with C/C++
compiler for hands-on/practical programming exercises. You may
check (http://www.stroustrup.com/compilers.html) for suitable
compilers.
• For additional technical details, students are advised to consult the C
Standard Documentation or you may check
(http://www.gnu.org/software/gnu-c-manual/gnu-c-manual.html).
Downloaded for FREE at www.schoolnetwork.io
2
Introduction
• Arrays
– Structures of related data items
– Static entity – same size throughout program
– Dynamic data structures discussed in Chapter 12
• c[ 0 ], c[ 1 ]...c[ n – 1 ]
Position number
of the element
within array c
Downloaded for FREE at www.schoolnetwork.io
4
Arrays
• Array elements are like normal variables
c[ 0 ] = 3;
printf( "%d", c[ 0 ] );
– Perform operations in subscript. If x equals 3
c[ 5 - 2 ] == c[ 3 ] == c[ x ]
Declaring Arrays
• When declaring arrays, specify
– Name
– Type of array
– Number of elements
arrayType arrayName[ numberOfElements ];
– Examples:
int c[ 10 ];
float myArray[ 3284 ];
Practice Exercise
One(1)
Practice Exercise
Two(2)
Practice Exercise
Three(3)
Sorting Arrays
• Sorting data
– Important computing application
– Virtually every organization must sort some data
• Bubble sort (sinking sort)
– Several passes through the array
– Successive pairs of elements are compared
• If increasing order (or identical ), no change
• If decreasing order, elements exchanged
– Repeat
• Example:
– original: 3 4 2 6 7
– pass 1: 3 2 4 6 7
– pass 2: 2 3 4 6 7
– Small elements "bubble" to the top
Downloaded for FREE at www.schoolnetwork.io
19
Case Study: Computing Mean, Median and
Mode Using Arrays
• Mean – average
• Median – number in middle of sorted list
– 1, 2, 3, 4, 5
– 3 is the median
• Mode – number that occurs most often
– 1, 1, 1, 2, 3, 3, 4, 5
– 1 is the mode
Practice Exercise
Four(4)
********
Median
********
The unsorted array of responses is
7 8 9 8 7 8 9 8 9 7 8 9 5 9 8 7 8 7 8
6 7 8 9 3 9 8 7 8 7 7 8 9 8 9 8 9 7 8 9
6 7 8 7 8 7 9 8 9 2 7 8 9 8 9 8 9 7 5 3
5 6 7 2 5 3 9 4 6 4 7 8 9 6 8 7 8 9 7 8
7 4 4 2 5 3 8 7 5 6 4 5 6 1 6 5 7 8 7
1 1 *
2 3 ***
3 4 ****
4 5 *****
5 8 ********
6 9 *********
7 23 ***********************
8 27 ***************************
9 19 *******************
The mode is the most frequent value.
For this run the mode is 8 which occurred 27 times.
Multiple-Subscripted Arrays
• Multiple subscripted arrays
– Tables with rows and columns (m by n array)
– Like matrices: specify row, then column
Column subscript
Array name
Row subscript
Multiple-Subscripted Arrays
• Initialization
1 2
– int b[ 2 ][ 2 ] = { { 1, 2 }, { 3, 4 } };
3 4
– Initializers grouped by row in braces
– If not enough, unspecified elements set to zero
int b[ 2 ][ 2 ] = { { 1 }, { 3, 4 } }; 1 0
• Referencing elements 3 4
Practice Exercise
Five(5)
Lowest grade: 68
Highest grade: 96
The average grade for student 0 is 76.00
The average grade for student 1 is 87.50
The average grade for student 2 is 81.75