C Programming Notes With Example
C Programming Notes With Example
C PROGRAMMING
CHAPTER 1
Page 2
HLZ /RE V 2
Analysis Design
Coding-
Implementation
Maintenance
· A system has boundaries & interacts with the universe beyond the boundary, by
passing data across the boundary
2. The arrows represent inputs and outputs (working documentation) for a phase.
3. The person figures are people and organizations with whom the analyst may
interact.
Page 3
HLZ /RE V 2
1 2
Feasibility assessment
Survey Study
project current
Project scope & system
request feasibility
Problem statement
START Facts
3
Define the
Requirements end-users’
requirements
Requirements statement
Opinions
Delivered 4
system &
enhancements Select a
feasible
solution
( from
candidate
solutions) Request for
9 proposals
Maintain Approved
and system
5 proposal
6
improve the
system End-user Design the Acquire
training new system computer
Configuration
hardware
and
New information software
system Design specification
Proposals
8 7 Vendors
Page 4
HLZ /RE V 2
Given the project request (e.g to develop a software program, to build a house, etc.) The
phases of a SDLC are:
· You go to the end-users (the ones who are/will be using the system) and find
out what they need or want out of the new system.
· Essentially, the purpose of the definition phase is to define the inputs, files,
processing and outputs for the new system.
· Output : requirement statement.
· The selection phase determines how the new system is to be designed but only
at a very high level – no details included.
· After defining candidates, each candidates is evaluated for
Ø Technical feasibility – Do we have the technical know-how?
Ø Operational feasibility – Can the new system be accepted by end-
users?
Ø Economic feasibility – Is the solution cost-effective?
· Output : approved system proposal.
Page 5
HLZ /RE V 2
· You need to determine which specifications are important for the equipment
and software to be purchased.
· Output ( to vendors) : request for proposals (RPF) or request for
information(RPI)
· Input (from vendors) : proposals ( after this, you should acquire the proposed
hardware and software configuration that best meets your needs at a
reasonable cost.
· Output : proposal of configuration ( hardware and software)
· The construction phase is the most time consuming and tedious phase.
· If the preceding phases were hastily done ( example specifications are unclear,
incomplete, etc.) this phase should be even longer.
· Alternatively or additionally, the construction phase may involved the
installation and modification of purchased software packages.
· The principal person here is the programmer ( not the analyst)
· Output : software
· The new systems solution represents a departure from the way things are
currently done.
· The analyst must provide for a smooth transitions from the old system to the
new system.
· Help the users cope with normal start-up problems, training and writing of
manuals.
Page 6
HLZ /RE V 2
1 2
Lot location
Survey the
Study current
situation environment
Dream
house
idea
Current environment
Land surveys, zoning laws, & constraints
START budget, neighbourhood
3
Homeowner’s requirements
Define the
end-users'
requirements
Homeowner’s requirements
Architectural possibilities
Mortgage 4
& furnishing
Evaluate
architect’s
alternatives
Decision
5 6
Bid request
Design the Select
new house materials &
Configuration
sub-
contractors
Blueprints
Bids
8 7 Subcontractors
and suppliers
Move into Construct
new house the new
House house
Page 7
HLZ /RE V 2
1 2
Study
Survey
3
Definition
4
Selection
5 6
9
Maintain Design Acquisiti-
and on
improve
8 7
Delivery Construc-
tion
Vendors
Page 8
HLZ /RE V 2
· Please be informed that the phases are not really sequential. A non-sequential view of
the life cycle is illustrated in figure 1.1.5
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
Time(Week)
· Although the SDLC is not strictly sequential, most phases do have some prerequisites.
Page 9
HLZ /RE V 2
Process
Source/data
Material Flow destination
Data flow
· The process symbols are used to indicate those places within the system at which
incoming data flows are processed or transformed into outgoing data flows.
· Data flows are shown by arrows marking the movement of the data through the
system.
Pa g e 10
HLZ /RE V 2
· A data flow can be thought of as a pipeline transporting packets of data from source to
destination.
· An open-ended rectangle represents a logical file where data are added or retrieved.
· The origin of data is called a source and the recipient is called a sink.
· Sources and sinks can be a person, organization, or even another computer system.
· Examples :
4
Materials
Process
shipment
Shipping documents
Shipping data
2
1
Process
Customer Process shipping
order data
Order Order data
Invoice 3
Payment Process
invoice
· The order processing system is a top-down model. The DFD represents the system
boundaries, external interactions, processes and data flow. The DFD is a logical model and
therefore does not identify disks, tapes, printers, computers or any other physical devices.
Pa g e 11
HLZ /RE V 2
1 Process Order
1.3 To
4
Process
Pricing
In stock
To
2
1.1 1.2 Pricing data
Customer
Order Check
entry inventory
Out of stock
Quantities 1.4
Inventory Backorders
Backorder items
Backorder data
· Process boxes can be repeatedly exploded or decomposed until each lowest-level process
box represents functions equivalent to a module of programming code (i.e 50 to 100 lines
of programming instructions).
Pa g e 12
HLZ /RE V 2
3. 4 Flowchart
· Flowcharts graphically illustrate how input, processes and output interact with each
other
Flowcharts
System Program
Process I/O
Decision
Termination
Offline
Off-page connector
Pa g e 13
HLZ /RE V 2
Record
Customer
Orders
Customer orders
Keying
operation
Pa g e 14
HLZ /RE V 2
· Illustrates flow of data flow of data and how they are processed.
Process I/O
Decision
Begin/Termination
Y
Take a Walk to the
bus? nearest bus stop
N
Wait for the bus
Walk to GMI
Pa g e 15
HLZ /RE V 2
Y
Take a Go to the lift and press a
lift? button
N Y
Lift Go inside and press the
opens? floor/level number
Go out of lift
End
Pa g e 16
HLZ /RE V 2
SINGLE-ENTRY Activity
SMALL SEQUENCE
Activity
SINGLE-EXIT
Yes
SINGLE-ENTRY Decision
Activity SELECTION
SINGLE-EXIT No
Activity
Activity
SINGLE-ENTRY
Activity
SINGLE-EXIT
No
Decision ITERATION
Yes
Activity
SINGLE-EXIT
Pa g e 17
HLZ /RE V 2
· Flexible & powerful, to create software products. but then it reached its limits.
· Turbo C/C++ provides integrated programming features for programmers to carry out
programming tasks in DOS base operating system.
· Today, the window base operating system enable programmers to carry out
programming tasks by using Borland C++ or Microsoft Visual C++.
Pa g e 18
HLZ /RE V 2
Exercise
1. Describe all the phases of system development life cycle on how to develop a GMI
Student information System that can give information about the students information
by using DFD.
3. Draw a flowchart that can accept input in cent and change it to Ringgit as output.
Example:
4. Draw a flowchart for College ABC. In order to enroll for a new semester a student
needs to choose 6 subjects, if its less than six the students cannot enroll for a new
semester. At the end of the semester the student need to sit for an examination. The
result later on will be verified and will be awarded with PASS or FAIL. If the result is
FAIL the student is required to reseat for the exam. For those that PASS the exam,
their results will be printed.
5. A program let the user input 2 integer and 1 code – a for add, s for subtract, m for
multiply and d for divide.
When the user input the code, the program will do an operation . If the code inputted
is a then the program will add the 2 integer that have been inputted. So, if you input s
then the 2 integer will be subtract. Draw a flowchart for this problem.
When a customer order an item, they will give the item’s code to the operator and
its quantity. .After that the price sub_total will be calculated. Then, the customer
can order other item. Lastly, the total will be calculated by adding all the subtotal.
Draw a flowchart for the transaction above.
Pa g e 19
HLZ /RE V 2
7. Fill in the correct phases for each box if you want to build a bar code system for GMI
library. The system will enable students to borrow and return books.
Pa g e 20
HLZ /RE V 2
CHAPTER 2
Basic structures of C
language
Pa g e 21
HLZ /RE V 2
ELEMENTS OF C PROGRAM
1) Preprocessor Directives
· They are carried out before the compiler compiles the code
· Example :
#include<stdio.h>
#include<math.h>
#define Area Width * Length
#define PI 3.1415
2) Variable declaration
· A variable is simply a memory location (inside the computer) where you can
temporarily store data.
· The user at the keyboard may enter the data, it may be read from a file or it may be the
result of a calculation made by the computer.
· All variables must be declared before they are used and they must have:-
i. an appropriate name or identifier.
ii. a data type
iii. value
· For example if you want to add 2 numbers of type integer, you can store the first value
into variable Num1, the second value into variable Num2 and the result of the
calculation into variable Sum.
10 + 8 = 18
· The reason memory locations are called variables is that their contents can
change(vary) as the program is running.
Pa g e 22
HLZ /RE V 2
3) Functions
· A function usually carries out a single tsk and each has a name and a list of values that
the function receives.
4) main( ) function
· use left brace { and right brace } to indicate the beginning and the end of the program.
Example: trivia.c
Output:
void main(void)
{
}
· You are looking at the simplest possible C program. Unfortunately, the program
doesn't do anything.
· The word "main" is very important, and must appear once, and only once in every C
program. This is the point where execution is begun when the program is run.
· The words void indicate that there are no data type specified.
· Following the "main" program name is a pair of parentheses which are an indication to
the compiler that this is a function.
· The two curly brackets({ }), properly called braces, are used to define the limits of the
program itself. The actual program statements go between the two braces and in this
case, there are no statements because the program does absolutely nothing.
Pa g e 23
HLZ /RE V 2
1) Displaying output
· to display text on the current output device e.g monitor, printf( ) function is being
used.
e.g: printf(“Welcome to GMI”);
output: Welcome to GMI
2) Getting input
· to get input from the user keyboard the scanf( ) function is being used.
· %f – format specifier
3) Body of program
· e.g
4) Returning
· In the case, the statement returns the program to the operating system, then passes a
return value to the operating system.
· e.g: return 0;
Pa g e 24
HLZ /RE V 2
· You will see that there are four program statements in this program, each one being a
call to the function "printf".
· The top line will be executed first, then the next, and so on, until the fourth line is
complete. The statements are executed in order from top to bottom.
· Notice the funny character near the end of the first line, namely the backslash( \ ). The
backslash is used in the printf statement to indicate that a special control character is
following. In this case, the "n" indicates that a "newline" is requested.
· This is an indication to return the cursor to the left side of the monitor and move down
one line. It is commonly referred to as a carriage return/line feed.
· Any place within text that you desire, you can put a newline character and start a new
line. You could even put it in the middle of a word and split the word between two
lines. The C compiler considers the combination of the backslash and letter n as one
character.
· for example TOTAL, total, Total or totaL are treated as different identifiers.
Pa g e 25
HLZ /RE V 2
[] {} <> ()
! * + = “ ‘ . ?
# / \ & % - _ ^
~ | ; : , @ $ `
3) Comments
· Comments help the person writing a program(programmer) and anyone else who must
read the source file to understand what is happening.
· e.g:
/* This is and introduction to c */
4) Semicolon
· e.g:
Pa g e 26
HLZ /RE V 2
/***********************************************/
/* THIS IS COMMENTS FOR COMMENTS.CPP FILE */
/***********************************************/
#include <stdio.h>
int main( )
{
printf("This program demonstrates comments\n");
/*"\n" is newline*/
return 0;
}
Output
/*********************************************/
/* addition program */
/********************************************/
#include <stdio.h>
Output
Pa g e 27
HLZ /RE V 2
· integers consist of any valid combination of digits along with a plus or minus sign.
int counter;
int x = 1;
int center, radius;
· Every int variable requires 2 bytes of memory & hold numbers in the range
–32,768 to 32, 767
Pa g e 28
HLZ /RE V 2
1) Float
· Variables defined as float can be in the range 3.4 X 10 to 3.4 X 10 and can occupy
4 bytes of memory.
2) Double
· Variables of type double required 8 bytes of memory to be stored and can hold
numbers in the range of 1.7 X 10 to 1.7 X 10
3) Char
· Character variables are used to hold eight-bit ASCII characters such as ‘A’, ‘P’,
‘I’or any other eight-bit quantity.
Pa g e 29
HLZ /RE V 2
· e.g :
const int SPEED = 75;
const float PI = 3.1415927;
const double DIAMETER = 899.567;
const char CH = ‘P’;
char string[size];
· In this example, size is the length of the string. Each character occupies one byte of
memory. You always make a space for the terminating null character. If you know a
string will be 10 character long you must define it as 11 characters long.
· Alternatively, you can specify the characters as a single string, using quotation marks, as
follows:
Char name[ ] = “Ali”;
Pa g e 30
HLZ /RE V 2
2.4 Operators
· Operators work so closely with variables that just as it is hard to imagine a program
without variables, it is difficult to create a useful C program that does not use
operators.
· Operators are words or symbols that cause a program to do something to its variables.
· Example:
·
int num; \* num is an identifier with type int *\
num = 1; \*Assigning the variable a value *\
identifier = expression;
Addition (+)
Subtraction (-)
Multiplication (*)
Division (/)
Remainder/Modulus operator (%)
· The operands must represent numeric values, so the operands can be integer, floating-
point or character.
Pa g e 31
HLZ /RE V 2
· The rules of operator precedence are guidelines that enable C to evaluate expressions
in correct order. Fig. 1.1 summarizes these rules of operator precedence.
Example #1
Algebra: z=pr%q+w/x-y
c: z = p * r % q + w / x – y;
1 2 4 3 5
Example #2
Algebra: m= a + b + c + d + e
5
c: m = (a + b + c + d + e) / 5;
1 2
Pa g e 32
HLZ /RE V 2
Pa g e 33
HLZ /RE V 2
· when file is included, the contents of the include file are inserted at the the current
location of source file.
#include <math.h>
· when the preprocessor encounters a macro name, it replaces the macro name with
another string that previously defined.
general format
#define square x * x
· Backslash character(\) can be used at the end of each line to extend the macro
definition to more than one line
Pa g e 34
HLZ /RE V 2
Exercise
3. Find the error in the following program segments and explain how the error can be
corrected.
Pa g e 35
HLZ /RE V 2
4. Debug the program below and briefly identify and correct the errors in it.
Hint : There are 6 errors in the program below
void main( ) {
Pa g e 36
HLZ /RE V 2
CHAPTER 3
Function
Pa g e 37
HLZ /RE V 2
1.0 Functions
· You can call the same function several times to accomplish certain tasks.
· A function is given its own name & accessed by that name. Data can be passed to a
function to operate on that data.
· Built-in library function such as printf( ) & scanf( ) comes with the compiler.
· User-defined function is named by the user himself, to carry out certain tasks.
· For example, the standard I/O library includes functions that control computer input
& output.
Pa g e 38
HLZ /RE V 2
· The declaration informs the compiler that you plan to create the function.
· type: data type the function returns. Use void if the function does not return any value.
· The first line of the function is virtually a copy of the function declaration, without
semicolon.
· The statements that form the body of the function are enclosed in braces.
Pa g e 39
HLZ /RE V 2
void main( )
{
/*other statements*/
function_name(varname1, varname2, … ..);
/*more statements*/
}
· If the function returns a value, put the function on the right side of an assignment
statement.
#include <stdio.h>
Pa g e 40
HLZ /RE V 2
Output
**
* *
**
/\
/ \
/ \
------
/\
/ \
/ \
Pa g e 41
HLZ /RE V 2
#include <stdio.h>
#include <math.h>
int num1, num2; /* Local variables - can be use only in function add()*/
return result;
int main( )
{
add( ); /* call add */
return 0;
}
Output
Enter number 1 : 12
Enter number 2 : 34
The sum of 2 numbers is 46
Pa g e 42
HLZ /RE V 2
#include <stdio.h>
#include <math.h>
int main( )
{
float base, side, hypot;
return 0;
}
return hypo;
}
Output
Pa g e 43
HLZ /RE V 2
#include <stdio.h>
#include <math.h>
int main( )
{
hypotenuse( ); /*f.call*/
return 0;
}
Pa g e 44
HLZ /RE V 2
Exercise
Output
You must use function temperature( ) to make the temperature conversion and function
volume( ) to calculate the cube’s volume.
2. Design and implement an interactive program that reads the year of birth and the
current year then calculate the age of the person. For example; if year of birth is 1991
and the current year is 1998 then age is 7. Write a function to calculate the age. Lastly
print all the input and the output.
3. Write an interactive program that reads width and length of a rectangle in meter.
Write a function to calculate the time needed to mow a lawn with the rate of 2
square meter per minute. Display the input and the result on the screen.
(5 Marks)
Pa g e 45
HLZ /RE V 2
CHAPTER 4
Pa g e 46
HLZ /RE V 2
a. Buffered I/O
b. Unbuffered I/O
c. Formatted I/O
· collecting and storing characters you typed in an area of temporary memory called a
buffer.
· you must press ENTER after typing because the character will only be sent to the
input routine after you press ENTER.
#include <stdio.h>
int main( )
{
char c;
c = getchar( );
putchar(c);
return 0;
}
Output
A
A
Pa g e 47
HLZ /RE V 2
· a program that immediately echoes input characters uses a form of unbuffered input.
· the characters entered by the user are immediately available to your program.
b. getche()
- echoes character to display
#include <stdio.h>
#include <conio.h>
int main( ) {
char c;
c = getch( );
c = getche( );
return 0;
}
Output
Pa g e 48
HLZ /RE V 2
· They are use for all types of input and output, including manipulators of data files.
· the powerful aspect of using streams with C is that the code is transferable to different
compilers on different computer platforms.
Code Description
\\ Backslash
\b Backspace
\r Carriage return
\“ Double
\f Formfeed
\n Newline
\0 Null value
\‘ Single quotation
\t Tab
\v Vertical tab
Pa g e 49
HLZ /RE V 2
Character Description
%c Single character
%d Signed decimal
%e Floating-point value
in
%f Floating-point value
%h Short integer
%i Integer
%o Octal integer
%s String of characters
%u Unsigned decimal
%x Hexadecimal integer
Pa g e 50
HLZ /RE V 2
#include <stdio.h>
int main( ) {
int octal,hexa;
float ex;
return 0;
}
Output
Enter a number : 10
The octal number is 12
Enter another number : 23
The hexadecimal number is 17
Enter a float number : 5.00
The number in exponent is 5.000000e+00
Pa g e 51
HLZ /RE V 2
#include <stdio.h>
int main( )
{
int i = 777;
float y = 123.456;
printf("%d\n%2d\n%8d\n", i, i, i);
printf("%7f %7.3f %7.1f\n", y, y, y);
printf("%12e %12.5e %12.3e", y, y, y);
return 0;
}
Output
777
777
777
123.456001 123.456 123.5
123456e+02 123456e+02 123456e+02
Pa g e 52
HLZ /RE V 2
Exercise
1. Given these initialization:
int i;
int c;
2. #include <stdio.h>
void main( ) {
char a, b, c, d, e, f,
}
Write down the output for the program above if the input is ANSI C.
printf(“%d\n%2d\n%8d\n”, i, i, i);
printf(“%f\n%6.1f\n%.4f\n%8.3f\n”, x, x, x, x);
printf(“%f\n%6.1f\n%.4f\n%8.3\n”, y, y, y, y);
}
Pa g e 53
HLZ /RE V 2
CHAPTER 5
Decision Structure
Pa g e 54
HLZ /RE V 2
· the if statement enables you to test an expression and act according to how the
expression is evaluated.
start
True True
condition step 1 .. k if num Odd
%2
False False
step k + 1 Even
end
Single if structure
Example : Determine an odd or
even number
Pa g e 55
HLZ /RE V 2
step a
False True
step k + 1..n condition step 1 .. k
step n + 1
Multiple if structure
Start
Input mark
False True
Failed If mark Passed
>= 50
End
Pa g e 56
HLZ /RE V 2
#include <stdio.h>
void main( )
{
int mark;
Output
Enter marks : 55
Passed
#include <stdio.h>
void main( )
{
char charac;
Pa g e 57
HLZ /RE V 2
Output
Input a character : #
This is a special character
· you will see that the second if statement is actually part of the body of the first if
statement.
· the inner if statement is not executed unless the outer one evaluates to true
#include <stdio.h>
int main( )
{
else
Pa g e 58
HLZ /RE V 2
Output
Please enter a number to guess
34
You guess too high
Press any key to continue
case constant2;
statement2;
break;
.
.
.
case constantX;
statementX;
break;
default :
default statement;
}
· In the switch statement, the computer tests a a variable consecutively against a list of
integer or character constants.
· After finding a match, the computer executes the statement or block of statements
that are associated with the specified constant.
· the default statement is executed if the compiler does not find a match in the list of
constants.
Pa g e 59
HLZ /RE V 2
True
case 1 steps 1 .. k
False
True steps k+1..m
case 2
False
False
steps q.. r
Start
True
case 1 print ‘ 1 ‘
False
True
case 2 print ‘ 2 ‘
False
False
default
End
An example of switch structure
Pa g e 60
HLZ /RE V 2
#include <stdio.h>
void main( )
{ int number;
printf("Enter a number : "); scanf("%d", &number);
switch(number)
{
case 1 : printf("One\n"); /*print One if number == 1*/
break;
default:
printf("Others\n");/*print Others if number is not 1,2 or 3*/
}
}
Output
Enter a number : 2
Two
· general syntax :-
switch (expression)
{
case constant1 :
statement1;
break;
case constant2 :
statement2;
break;
default :
default statement;
}
case constant2;
statement2;
break;
Pa g e 61
HLZ /RE V 2
void main( )
{
int choice; /*choice represents number 1, 2 , 3*/
char pilih; /* pilih represents character 1, 2, 3*/
int minute;
float hour, feet, meter;
int celcius, fahrenheit;
do{
printf("Welcome to this unit converter\n");
printf("\t\t===================================\n");
printf("\t\tI CHOOSE UNIT TO CHANGE I\n");
/* The outer menu*/
printf("\t\tI=================================I\n");
printf("\t1. Time : minute -> hour\n");
printf("\t2. Distance : feet -> meter\n");
printf("\t3. Temperature \n");
printf("\t4. End\n");
printf("\tChoice: ");
scanf("%d", &choice);
switch(choice) {
case 1:
printf("Input time in minute: ");
scanf("%d", &minute);
hour = (float)minute/60;
printf("%d Minute = %.2f Hour\n", minute, hour);
break;
case 2:
printf("Input distance in feet: ");
scanf("%f", &feet);
meter = feet * 0.3048;
printf("%.2f Feet = %.4f Meter\n", feet, meter);
break;
case 3:
do{
printf("\n\t\tCHOOSE UNIT TO CHANGE\n");
/*The inner/nested menu*/
printf("\t\t=====================\n");
printf("\t1. Celcius -> Fahrenheit\n");
printf("\t2. Fahrenheit -> Celcius\n");
printf("\t3. End\n");
Pa g e 62
HLZ /RE V 2
printf("\tChoice: ");
scanf("%s", &pilih);
case '1':
printf("Input temperature in celcius: ");
scanf("%d", &celcius);
fahrenheit = (celcius) * 9/5 + 32;
printf("%d Celcius = %d fahrenheit\n",
celcius, fahrenheit);
break;
case '2':
printf("Input temperature in fahrenheit: ");
scanf("%d", &fahrenheit);
celcius = ((fahrenheit)- 32) * 5/9;
printf("%d fahrenheit = %d celcius\n",
fahrenheit,celcius);
break;
case '3':
printf("End\n");
default:
printf("Invalid selection\n");
break;
}while(pilih != 3);
Pa g e 63
HLZ /RE V 2
Output
Pa g e 64
HLZ /RE V 2
Exercise
a) #include <stdio.h>
void main( ) {
int i;
i = 14;
if (i % 2 == 0)
printf (“Odd number\n”);
else
printf (“Even number\n”);
}
b) #include <stdio.h>
void main( ) {
int code;
code = 2;
if ( code = = 1)
printf (“ Male\n”);
else
printf (“ Female\n”);
}
c) #include <stdio.h>
void main( ) {
int weight;
weight = 55;
if (weight <= 55)
printf(“ Average\n”);
else
printf(“ Obese\n”);
}
(3 Marks)
2. Find the error in each of the following code segments and explain how to correct it.
a) switch (n) {
case 1:
printf(“The number is 1\n”);
case 2:
printf(“The number is 2\n”);
break;
default:
printf(“The number is not 1 or 2\n”);
break;
}
(3 Marks)
Pa g e 65
HLZ /RE V 2
3. There are two catagories of character; vocal and consonan.‘a’, ‘e’, ‘i’, ‘o’and ‘u’
are vocal. Write a C program using the switch statement to determine wheather an
input character is a vocal or consonan.
Example output:-
Input a character (a – z) : a
a is a vocal
(5 Marks)
Pa g e 66
HLZ /RE V 2
CHAPTER 6
Loop Structure
Pa g e 67
HLZ /RE V 2
· one of the strengths of a computer is its capability to perform repeated tasks rapidly,
accurately and without complaint.
· you can instruct the computer to do the same thing over and over again, millions of
times, if necessary.
a) for loop
b) while loop
c) do … while loop
· It is often used for situations in which you want to execute a specific task number of
times.
· general syntax:-
Pa g e 68
HLZ /RE V 2
initial value i
checks
condition
True
steps 1 .. n update i value
of i
False
Start
i=0
if
i >= 10
True print the
value of i i++
False
End
Pa g e 69
HLZ /RE V 2
#include <stdio.h>
int main( )
{
for(int counter = 1; counter <=10; counter++) /*The syntax of*/
/*for statement*/
printf("%d\t",counter);
return 0;
}
Output
1 2 3 4 5 6 7 8 9 10
#include <stdio.h>
int main( ) {
return 0;
}
Output
* * *
* * *
* * *
* * *
* * *
Pa g e 70
HLZ /RE V 2
· in the while loop, the body of the loop is executed as long as the expression is true.
· when the expression become false, program control passes to the line that follows the
loop.
False
Start
n=1
False
End
Pa g e 71
HLZ /RE V 2
int main( )
{
int x = 1;
return 0;
}
Output
1 2 3 4 5 6 7 8 9 10
Pa g e 72
HLZ /RE V 2
· unlike the for and while loops, which test the loop condition at the top of the loop, the
do…while loop checks its condition at the end of the loop.
· this means that a do…while loop will always execute at least once.
· the while keyword marks the end of the loop and contains the loop expression.
Steps 1 .. n
True
Conditio
-n
False
The do..while loop structure
Start
n=1
True
n > 10
False
Pa g e 73
HLZ /RE V 2
int main( )
{
int x = 1;
do {
printf("%d\t", x++);
}while(x <= 10); /*Checking the condition at the end of the loop*/
return 0;
Output
1 2 3 4 5 6 7 8 9 10
· infinite loops are useful at times to force a program to continue running for an
extended length of time.
for (; ; ;)
printf (“this will continue to print forever\n”);
while(1)
{
printf (“this will continue to print forever\n”);
}
do
{
printf (“this will continue to print forever\n”);
}
Pa g e 74
HLZ /RE V 2
· when the compiler encounters the break statement inside a loop, the computer
terminates the loop and program control resumes at the statement that follows the
loop.
#include <stdio.h>
int main( )
{
int x;
if( x == 5)
break; /*break loop only if x == 5*/
return 0;
}
Output
1234
Broke out of loop at x == 5
Pa g e 75
HLZ /RE V 2
· forces the iteration of the loop to take place and skips any code in between.
#include <stdio.h>
int main( )
{
int x;
if (x == 5)
continue; /*skip remaining code in loop only if x == 5*/
printf("%d", x);
}
Output
1 2 3 4 6 7 8 9 10
Used continue to skip printing the value 5
Pa g e 76
HLZ /RE V 2
Exercise
a) #include <stdio.h>
main( ) {
int x;
for (x = 1; x < 10; x++) {
if (x == 8)
break;
printf(“%d”, x);
}
return 0;
}
(2 Marks)
2. Debug the program below and briefly identify and correct the errors in it. (6 Marks)
Hint : There are 6 errors in the program below
int main( ) {
even = odd = 0;
printf (“ Enter a positive number (negative to end) “);
scanf (“%d”, value);
while (value > = 0) {
if (value %2 == 0)
Even++;
else
odd++;
printf (“ Enter a positive number (negative to end) “)
scanf (“%d”, value);
return 0;
Pa g e 77
HLZ /RE V 2
3. Find the error in each of the following code segments and explain how to correct it.
a. x = 1;
while (x <= 10);
x++;
(2 Marks)
Pa g e 78
HLZ /RE V 2
CHAPTER 7
Array
Pa g e 79
HLZ /RE V 2
1.0 A r r a y
o A group of items of the same type under one variable name.
o The common array operation e.g are scanning, sorting and writing vector.
1 .1 O n e - di m e n si o na l a r r a y
· an ordered set of elements where each element is of the same type.
float marks[MAX];
or
float marks[5];
· To define marks we use square bracket [ ] to write the number of elements that
it will contains.
Pa g e 80
HLZ /RE V 2
/*array.c*/
/* calculate the average of an array of numbers*/
#include <stdio.h>
int main( )
{
int age[ ] = {19,17,18,20,22}; /*initialization of an
array*/
Output:
Element[0] = 19
Element[1] = 17
Element[2] = 18
Element[3] = 20
Element[4] = 22
Enter mark 1 = 10
Enter mark 2 = 20
Enter mark 3 = 10
Enter mark 4 = 20
Enter mark 5 = 40
Pa g e 81
HLZ /RE V 2
1 .2 M ul t id im e ns io na l a r r ay
· Array dimensions can be of any dimension.
/*matintro.c*/
/*introduction to 2-dimensional arrays(matrices)*/
#include <stdio.h>
int main( )
{
int mat1[ROWS][COLS]; /*Defining a matrix of size 2 X 3*/
int mat2[ROWS][COLS] = {{1,2,3},
{4,5,6}}; /*Initialization of a matrix*/
Output
123
456
Pa g e 82
HLZ /RE V 2
Exercise
2. #include <stdio.h>
#define N10
void main( ) {
int value[N] = {1, 1};
int i;
Pa g e 83
HLZ /RE V 2
4. Find the error in each of the following program segments and correct the error.
a) #define SIZE 100;
b) SIZE = 10;
c) Assume int b[10] = {0}, i;
For ( i = 0; i <=10; i++)
B[ i ] = 1;
d) Assume int a [2][2] = {1,2}, {3,4}};
A[1,1] = 5;
Pa g e 84
HLZ /RE V 2