Professional Documents
Culture Documents
SPG 0412
PROGRAMMING IN C
GERMAN-MALAYSIAN INSTITUTE
SPG
Submodule
PROGRAMMING IN C
Submodule Code
SPG 0412
Pre requisites
NIL
Semester
Weightage
Hours
72 hours
Laboratory / Workshop
Computer Lab.
Machines / Equipments
Prepared By
1)
2)
3)
4)
Personal Computer
LCD Projeector
Scanner
Printer
Page 1
G M I/ I SC /C L5 /R E V00 /0 2
HANDOUT
SPG 0412
PROGRAMMING IN C
1.
2.
3.
4.
REFERENCES :
1.
C How to Program, 2nd Edition, H.M Deitel & P.J. Deitel, Prentice Hall,
1994
2.
3.
Page 2
GM I/ IE/ C L5/ REV00/05
HANDOUT
SPG 0412
PROGRAMMING IN C
CHAPTER 1
Page 3
GM I/ IE/ C L5/ REV00/05
HANDOUT
SPG 0412
PROGRAMMING IN C
Analysis
Design
CodingImplementation
Maintenance
A set of things or processes that are linked together by rules to form a unified
process.
A system has boundaries & interacts with the universe beyond the boundary,
by passing data across the boundary
3. The person
figures are people and organizations with whom the
analyst may interact.
4. The shaded diamonds
indicate checkpoints at which the end-user
should reevaluate feasibility.
Page 4
GM I/ IE/ C L5/ REV00/05
HANDOUT
SPG 0412
PROGRAMMING IN C
1
2
Feasibility assessment
Project
request
Study
current
system
Survey
project
scope &
feasibility
Problem statement
Facts
START
3
Define the
end-users
requirements
Requirements
FINISH
Requirements statement
Opinions
Delivered
system &
enhancements
Select a
feasible
solution
( from
candidate
solutions)
9
Maintain
and
improve the
system
New information
system
Approved
system
proposal
5
End-user
training
Design the
new system
Configuration
Design specification
Request for
proposals
6
Acquire
computer
hardware
and
software
Proposals
Deliver the
new system
Computer
software
Construct
the new
system
Page 5
GM I/ IE/ C L5/ REV00/05
Vendors
HANDOUT
SPG 0412
PROGRAMMING IN C
Given the project request (e.g to develop a software program, to build a house, etc.)
The
phases of a SDLC are:
1. Survey project scope and feasibility
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.
Page 6
GM I/ IE/ C L5/ REV00/05
HANDOUT
SPG 0412
PROGRAMMING IN C
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 7
GM I/ IE/ C L5/ REV00/05
HANDOUT
SPG 0412
PROGRAMMING IN C
2
Lot location
Survey the
situation
Study current
environment
Dream
house
idea
Current environment
& constraints
START
3
Homeowners requirements
Define the
end-users'
requirements
Homeowners opinions
FINISH
Homeowners requirements
Architectural possibilities
Mortgage
& furnishing
Evaluate
architects
alternatives
Decision
Design the
new house
Select
materials &
subcontractors
Bid request
Configuration
Blueprints
Bids
Move into
new house
House
Construct
the new
house
Page 8
GM I/ IE/ C L5/ REV00/05
Subcontractors
and suppliers
HANDOUT
SPG 0412
PROGRAMMING IN C
2
Study
Survey
3
Definition
4
Selection
9
Maintain
and
improve
6
Acquisition
Design
Delivery
Construction
Vendors
Page 9
GM I/ IE/ C L5/ REV00/05
HANDOUT
SPG 0412
PROGRAMMING IN C
Please be informed that the phases are not really sequential. A non-sequential
view of the life cycle is illustrated in figure 1. 5
Phase
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
Time(Week)
Figure 1.5 Gantt Chart
Although the SDLC is not strictly sequential, most phases do have some
prerequisites.
P a g e 10
GM I/ IE/ C L5/ REV00/05
HANDOUT
SPG 0412
PROGRAMMING IN C
a model that describes the flows of data & the process that change/transform
data throughout the system
DFD properties:
On page
Off
page
Process
Material Flow
Source/data
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.
P a g e 11
GM I/ IE/ C L5/ REV00/05
HANDOUT
SPG 0412
PROGRAMMING IN C
The origin of data is called a source and the recipient is called a sink.
Examples :
4
Materials
Process
shipment
Shipping documents
Shipping data
2
1
Customer
Order
Process
order
Order data
Process
shipping
data
Invoice
Payment
Process
invoice
P a g e 12
GM I/ IE/ C L5/ REV00/05
HANDOUT
SPG 0412
PROGRAMMING IN C
In stock
To
4
Process
Pricing
To
2
Customer
1.1
1.2
Order
entry
Check
inventory
Quantities
Pricing data
Out of stock
1.4
Inventory
Backorders
Backorder items
Backorder data
Process boxes can be repeatedly exploded or decomposed until each lowestlevel process box represents functions equivalent to a module of programming code
(i.e 50 to 100 lines of programming instructions).
P a g e 13
GM I/ IE/ C L5/ REV00/05
HANDOUT
SPG 0412
PROGRAMMING IN C
3. 4 Flowchart
Flowcharts graphically illustrate how input, processes and output interact with
each other
Flowcharts
System
Program
Decision
Online
Storage
Process
Document
I/O
Termination
Manual Operation
Manual
Input
Offline
Off-page connector
P a g e 14
GM I/ IE/ C L5/ REV00/05
HANDOUT
SPG 0412
PROGRAMMING IN C
Record
Customer
Orders
Customer orders
Keying
operation
inventory
master file
sales report
Process
Customer order
Shipping
documents
customer
master file
invoices
P a g e 15
GM I/ IE/ C L5/ REV00/05
backorders
HANDOUT
SPG 0412
PROGRAMMING IN C
Illustrates flow of data flow of data and how they are processed.
Process
I/O
Begin/Termination
Y
Take a
bus?
N
Take own vehicle
to GMI
Walk to the
nearest bus stop
N
Walk to GMI
1
P a g e 16
GM I/ IE/ C L5/ REV00/05
HANDOUT
SPG 0412
PROGRAMMING IN C
Determine the
level of lecture
hall
Take
a lift?
N
N
Lift
open
Go inside and
press the
Take the
N
Arriv
ed?
Y
Go out of lift
Walk to the
lecture hall
End
P a g e 17
GM I/ IE/ C L5/ REV00/05
Wait
HANDOUT
SPG 0412
PROGRAMMING IN C
SINGLE-ENTRY
Activity
SMALL SEQUENCE
SINGLE-EXIT
SINGLE-ENTRY
SINGLE-EXIT
Activity
Yes
Decision
Activity
No
SELECTION
Activity
Activity
SINGLE-ENTRY
Activity
SINGLE-EXIT
No
Decision
Yes
SINGLE-EXIT
Activity
P a g e 18
GM I/ IE/ C L5/ REV00/05
ITERATION
HANDOUT
SPG 0412
PROGRAMMING IN C
Flexible & powerful, to create software products. but then it reached its limits.
Today, the window base operating system enable programmers to carry out
programming tasks by using Borland C++ or Microsoft Visual C++.
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.
2. Draw a flowchart on how to buy a drink from a vending machine.
3. Draw a flowchart that can accept input in cent and change it to Ringgit as
output.
Example:
Input : 1150
Output: RM11.50
905
RM9.05
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.
P a g e 19
GM I/ IE/ C L5/ REV00/05
HANDOUT
SPG 0412
PROGRAMMING IN C
Price(RM)
30.00
35.00
40.00
90.00
120.00
When a customer order an item, they will give the items 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.
8. 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.
P a g e 20
GM I/ IE/ C L5/ REV00/05
HANDOUT
SPG 0412
PROGRAMMING IN C
CHAPTER 2
P a g e 21
GM I/ IE/ C L5/ REV00/05
HANDOUT
SPG 0412
PROGRAMMING IN C
Basic structures of C
language
P a g e 22
GM I/ IE/ C L5/ REV00/05
HANDOUT
SPG 0412
PROGRAMMING IN C
ELEMENTS OF C PROGRAM
Preprocessor Directives
Variable declaration
Functions
main( )
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
Num1
Num2
18
Sum
The reason memory locations are called variables is that their contents can
change(vary) as the program is running.
P a g e 23
GM I/ IE/ C L5/ REV00/05
HANDOUT
SPG 0412
PROGRAMMING IN C
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)
{
}
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 indicates that there are no data types specified.
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.
P a g e 24
GM I/ IE/ C L5/ REV00/05
HANDOUT
SPG 0412
PROGRAMMING IN C
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
void main( ) { printf(Hello World!); }
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;
P a g e 25
GM I/ IE/ C L5/ REV00/05
HANDOUT
SPG 0412
PROGRAMMING IN C
Example: wrtmore.c
Output:
main( )
{
printf("This is a line of text to output.\n");
printf("And this is another ");
printf("line of text.\n\n");
printf("This is a third line.\n");
}
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.
P a g e 26
GM I/ IE/ C L5/ REV00/05
HANDOUT
SPG 0412
PROGRAMMING IN C
[]
{}
<> ()
! * + = . ?
# / \ & % - _ ^
~ | ; : , @ $ `
3) Comments
e.g:
/* This is and introduction to c */
4) Semicolon
Every statement in a C program is terminated with a semicolon( ; ), a character
P a g e 27
GM I/ IE/ C L5/ REV00/05
HANDOUT
SPG 0412
PROGRAMMING IN C
/***********************************************/
/* THIS IS COMMENTS FOR COMMENTS.CPP FILE */
/***********************************************/
#include <stdio.h>
int main( )
{
printf("This program demonstrates comments\n");
/*"\n" is newline*/
return 0;
}
Output
This program demonstrates comments
/*********************************************/
/* addition program
*/
/********************************************/
#include <stdio.h>
void main( )
/*there is no return if using void */
{
int integer1, integer2, sum;
printf("Enter first integer\n");
scanf("%d", &integer1);
printf("Enter second integer\n");
scanf("%d", &integer2);
sum = integer1 + integer2;
printf("Sum is %d", sum);
/*Prompt*/
/*Input using scanf( )*/
/*process*/
/*display output*/
}
Output
Enter first integer
23
Enter second integer
12
Sum is 35
P a g e 28
GM I/ IE/ C L5/ REV00/05
HANDOUT
SPG 0412
PROGRAMMING IN C
integers consist of any valid combination of digits along with a plus or minus
sign.
Every int variable requires 2 bytes of memory & hold numbers in the range
32,768 to 32, 767
P a g e 29
GM I/ IE/ C L5/ REV00/05
HANDOUT
SPG 0412
PROGRAMMING IN C
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
P a g e 30
GM I/ IE/ C L5/ REV00/05
HANDOUT
SPG 0412
PROGRAMMING IN C
e.g :
const int SPEED = 75;
const float PI = 3.1415927;
const double DIAMETER = 899.567;
const char CH = P;
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;
P a g e 31
GM I/ IE/ C L5/ REV00/05
HANDOUT
SPG 0412
PROGRAMMING IN C
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.
Example:
int num; \* num is an identifier with type int *\
num = 1; \*Assigning the variable a value *\
result = 365/5;
value = 99 previous;
P a g e 32
GM I/ IE/ C L5/ REV00/05
HANDOUT
SPG 0412
PROGRAMMING IN C
Operator(s)
()
Operation(s)
Parentheses
*, / , or %
Multiplication
Division
Modulus
Addition
Subtraction
+ or -
Algebra:
z=pr%q+w/x-y
c:
z = p * r % q + w / x y;
1
Example #2
Algebra:
m= a + b + c + d + e
5
c:
m = (a + b + c + d + e) / 5;
1
P a g e 33
GM I/ IE/ C L5/ REV00/05
HANDOUT
SPG 0412
PROGRAMMING IN C
== Equal to
!= Not equal to
<= LS/ET
&& (AND)
||
(OR) !
(NOT) -
result=true IF expressions=true
result=true IF either expressions=true
reverse the expressions condition
P a g e 34
GM I/ IE/ C L5/ REV00/05
HANDOUT
SPG 0412
PROGRAMMING IN C
when file is included, the contents of the include file are inserted at the the
current location of source file.
Example :
#include <stdio.h>
#include <math.h>
Example :
#define PI 3.15
#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
P a g e 35
GM I/ IE/ C L5/ REV00/05
HANDOUT
SPG 0412
PROGRAMMING IN C
Exercise
1. Fill in the blanks with the correct answer.
a) Every C program begins execution at function _______________.
b) The _____________standard library function displays information on the
screen.
c) A function is invoked with a ______________________.
d) A variable declared inside a function and can only be used by statements
inside the function is called a ______________ variable.
e) The keyword ______________ is used in a function header to indicate that a
function does not return a value or to indicate that a function contains no
parameter.
(5 Marks)
2. Identify and correct errors in each of the following statements.
a) */ Program to determine the largest of three integers /*
3. Find the error in the following program segments and explain how the error
can be corrected.
void product (void) {
int a, b, c, result;
printf (Enter three integers: )
scanf (%d%d%d, &a, &b, &c);
result = a* b * c;
printf(Result is %d, result);
return result; }
P a g e 36
GM I/ IE/ C L5/ REV00/05
HANDOUT
SPG 0412
PROGRAMMING IN C
4. Debug the program below and briefly identify and correct the errors in it.
Hint : There are 6 errors in the program below
/* Program that calculate 2 numbers and verify the correct answer/*
#include <stdio.h>
void main( ) {
int num1, num2, add;
int answer;
printf (***Maths Excercise***\n)
printf ( \n\n);
printf(Enter first number : );
scanf ( %d, &num1);
printf(Enter second number : );
scanf ( %d, num2);
num1 + num2 = add;
printf ( \nWhat is the answer? );
scanf( %d, &answer);
if (answer = add)
printf( You are right\n);
else {
printf (You are wrong. Try again\n);
printf (The correct answer is %d\n, &add);
}
P a g e 37
GM I/ IE/ C L5/ REV00/05
HANDOUT
SPG 0412
PROGRAMMING IN C
CHAPTER 3
Function
P a g e 38
GM I/ IE/ C L5/ REV00/05
HANDOUT
SPG 0412
PROGRAMMING IN C
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.
The standard C function library provides routine for the most common
programming tasks.
For example, the standard I/O library includes functions that control computer
input & output.
P a g e 39
GM I/ IE/ C L5/ REV00/05
HANDOUT
SPG 0412
PROGRAMMING IN C
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.
P a g e 40
GM I/ IE/ C L5/ REV00/05
HANDOUT
SPG 0412
PROGRAMMING IN C
If the function returns a value, put the function on the right side of an
assignment statement.
/*f.declaration of circle*/
/*f.declaration of cross*/
/*f.declaration of Base*/
/*f.declaration of Triangle*/
/*f.definition of circle*/
/*f.definition of Triangle*/
/*f.definition of Cross*/
/*f.definition of Base*/
Output
P a g e 41
GM I/ IE/ C L5/ REV00/05
HANDOUT
SPG 0412
PROGRAMMING IN C
**
*
**
/\
/ \
/ \
-----/\
/ \
/ \
P a g e 42
GM I/ IE/ C L5/ REV00/05
HANDOUT
SPG 0412
PROGRAMMING IN C
/* prototype/declaration*/
/* call add */
Output
Enter number 1 : 12
Enter number 2 : 34
The sum of 2 numbers is 46
P a g e 43
GM I/ IE/ C L5/ REV00/05
HANDOUT
SPG 0412
PROGRAMMING IN C
Output
Please enter the base and side of
the right-angled triangle to calculate
the hypotenuse
Base : 3
Side : 4
The hypotenuse of a triangle with base = 3.00
and side = 4.00 is = 5.00
P a g e 44
GM I/ IE/ C L5/ REV00/05
HANDOUT
SPG 0412
PROGRAMMING IN C
int main( )
{
hypotenuse( ); /*f.call*/
return 0;
}
float hypotenuse( ) /*f.definition with no argument*/
{
float base, side, hypot;
printf("\nPlease enter the base and side of\n");
printf(" the right-angled triangle to calculate\n");
printf(" the hypotenuse\n");
printf("Base : "); scanf("%f",&base);
printf("Side : "); scanf("%f",&side);
hypot = sqrt(base*base + side*side);
printf("\nThe hypotenuse of a triangle with base = %.2f\n",base);
printf(" and side = %.2f is = %.2f\n",side,hypot);
}
P a g e 45
GM I/ IE/ C L5/ REV00/05
HANDOUT
SPG 0412
PROGRAMMING IN C
Exercise
1. Write and compile a program that does the following:
a) Convert the value of temperature in Celcius to Fahrenheit. The formula is:
Fahrenheit = Celcius x 9/5 + 32
Output
Converting Celcius to Fahrenheit
=======================
Please enter the temperature in Celcius: 100
Celcius is equal to 212 Fahrenheit
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)
P a g e 46
GM I/ IE/ C L5/ REV00/05
HANDOUT
SPG 0412
PROGRAMMING IN C
CHAPTER 4
P a g e 47
GM I/ IE/ C L5/ REV00/05
HANDOUT
SPG 0412
PROGRAMMING IN C
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
P a g e 48
GM I/ IE/ C L5/ REV00/05
HANDOUT
SPG 0412
PROGRAMMING IN C
#include <stdio.h>
#include <conio.h>
int main( ) {
char c;
c = getch( );
c = getche( );
return 0;
}
Output
A
P a g e 49
GM I/ IE/ C L5/ REV00/05
HANDOUT
SPG 0412
PROGRAMMING IN C
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.
Format specifier
%d
%f
Floating point
%e
%c
Single character
%s
Character string
Code
Description
\\
Backslash
\b
Backspace
\r
Carriage return
Double
\f
Formfeed
\n
Newline
\0
Null value
Single quotation
\t
Tab
\v
Vertical tab
P a g e 50
GM I/ IE/ C L5/ REV00/05
HANDOUT
SPG 0412
PROGRAMMING IN C
Description
%c
Single character
%d
Signed decimal
%e
Floating-point value
%f
in
Floating-point value
%h
Short integer
%i
Integer
%o
Octal integer
%s
String of characters
%u
Unsigned decimal
%x
Hexadecimal integer
#include <stdio.h>
int main( ) {
int octal,hexa;
float ex;
printf("Enter a number : ");
scanf("%d", &octal);
printf("The octal number is %o\n", octal);
printf("Enter another number : ");
scanf("%d", &hexa);
printf("The hexadecimal number is %x\n", hexa);
printf("Enter a float number : ");
scanf("%f", &ex);
printf("The number in exponent is %e\n", 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
P a g e 51
HANDOUT
SPG 0412
PROGRAMMING IN C
P a g e 52
GM I/ IE/ C L5/ REV00/05
HANDOUT
SPG 0412
PROGRAMMING IN C
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);
}
P a g e 53
GM I/ IE/ C L5/ REV00/05
HANDOUT
SPG 0412
PROGRAMMING IN C
CHAPTER 5
Decision Structure
P a g e 54
GM I/ IE/ C L5/ REV00/05
HANDOUT
SPG 0412
PROGRAMMING IN C
general sintax
if (expression)
statement;
the if statement enables you to test an expression and act according to how the
expression is evaluated.
start
step a
Input num
True
condition
False
True
step 1 .. k
if num
%2
False
step k + 1
Even
end
Single if structure
P a g e 55
GM I/ IE/ C L5/ REV00/05
Odd
HANDOUT
SPG 0412
PROGRAMMING IN C
step a
step k + 1..n
True
False
condition
step 1 .. k
step n + 1
Multiple if structure
Start
Input mark
Failed
True
False
If mark
>= 50
Passed
End
P a g e 56
GM I/ IE/ C L5/ REV00/05
HANDOUT
SPG 0412
PROGRAMMING IN C
#include <stdio.h>
/*Printing distinction / Passed / Failed according to mark*/
#include <stdio.h>
void main( )
{
int mark;
printf("Enter marks : ");
scanf("%d", &mark);
if (mark >= 80)
printf("Distinction\n");
else if(mark >= 50)
printf("Passed\n");
else
printf("Failed\n");
}
Output
Enter marks : 55
Passed
P a g e 57
GM I/ IE/ C L5/ REV00/05
HANDOUT
SPG 0412
PROGRAMMING IN C
Output
Input a character : #
This is a special character
general syntax
if (expression)
if (another expression)
statement;
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( )
{
int number, secretnumber = 25;
if (number != secretnumber)
/* the symbol for not equal != */
{
if(number > secretnumber)
/*nested if*/
printf("You guess too high\n");
else
printf("You guess too low\n");
}
return 0;
}
P a g e 58
GM I/ IE/ C L5/ REV00/05
HANDOUT
SPG 0412
PROGRAMMING IN C
Output
Please enter a number to guess
34
You guess too high
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.
P a g e 59
GM I/ IE/ C L5/ REV00/05
HANDOUT
SPG 0412
PROGRAMMING IN C
True
case 1
steps 1 .. k
False
case 2
True
steps k+1..m
True
steps n+1..p
False
case n
False
steps q.. r
Start
case 1
True
print 1
False
case 2
True
print 2
False
case n
True
print n
False
default
End
P a g e 60
GM I/ IE/ C L5/ REV00/05
HANDOUT
SPG 0412
PROGRAMMING IN C
#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;
case 2 : printf("Two\n");
break;
P a g e 61
GM I/ IE/ C L5/ REV00/05
HANDOUT
SPG 0412
PROGRAMMING IN C
P a g e 62
GM I/ IE/ C L5/ REV00/05
HANDOUT
SPG 0412
PROGRAMMING IN C
printf("\tChoice: ");
scanf("%s", &pilih);
P a g e 63
GM I/ IE/ C L5/ REV00/05
HANDOUT
SPG 0412
PROGRAMMING IN C
Output
Welcome to this unit converter
===================================
I CHOOSE UNIT TO CHANGE
I
I=================================I
1. Time : minute -> hour
2. Distance : feet -> meter
3. Temperature
4. End
Choice: 1
Input time in minute: 120
120 Minute = 2.00 Hour
Welcome to this unit converter
===================================
I CHOOSE UNIT TO CHANGE
I
I=================================I
1. Time : minute -> hour
2. Distance : feet -> meter
3. Temperature
4. End
Choice: 2
Input distance in feet: 100
100.00 Feet = 30.4800 Meter
Welcome to this unit converter
===================================
I CHOOSE UNIT TO CHANGE
I
I=================================I
1. Time : minute -> hour
2. Distance : feet -> meter
3. Temperature
4. End
Choice: 3
CHOOSE UNIT TO CHANGE
=====================
1. Celcius -> Fahrenheit
2. Fahrenheit -> Celcius
3. End
Choice: 1
Input temperature in celcius: 100
100 Celcius = 212 fahrenheit
Thank you for using this program
Welcome to this unit converter
===================================
I CHOOSE UNIT TO CHANGE
I
I=================================I
1. Time : minute -> hour
2. Distance : feet -> meter
3. Temperature
4. End
Choice: 4
Thank you for using this program
P a g e 64
GM I/ IE/ C L5/ REV00/05
HANDOUT
SPG 0412
PROGRAMMING IN C
Exercise
1. What is the output for each of the following programs below:-
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)
P a g e 65
GM I/ IE/ C L5/ REV00/05
HANDOUT
SPG 0412
PROGRAMMING IN C
Input a character (a z) : a
a is a vocal
(5 Marks)
P a g e 66
GM I/ IE/ C L5/ REV00/05
HANDOUT
SPG 0412
PROGRAMMING IN C
CHAPTER 6
Loop Structure
P a g e 67
GM I/ IE/ C L5/ REV00/05
HANDOUT
SPG 0412
PROGRAMMING IN C
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.
-there are 3 major loop statements in the C programming language: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.
P a g e 68
GM I/ IE/ C L5/ REV00/05
HANDOUT
SPG 0412
PROGRAMMING IN C
initial value i
checks
condition
of i
True
steps 1 .. n
update i value
False
Start
i=0
if
i >= 10
True
print the
value of i
False
End
P a g e 69
GM I/ IE/ C L5/ REV00/05
i++
HANDOUT
SPG 0412
PROGRAMMING IN C
10
{
for(int column = 1; column <=3; column++) /*Loop from 1 to 3*/
{
printf(" \t");
/*print the asterisk*/
}
printf("\n");
}
return 0;
}
Output
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
P a g e 70
GM I/ IE/ C L5/ REV00/05
HANDOUT
SPG 0412
PROGRAMMING IN C
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.
Con dition
True
Steps 1 .. n
False
Start
n=1
n >=
5
True
print the
value of n
False
End
P a g e 71
GM I/ IE/ C L5/ REV00/05
HANDOUT
SPG 0412
PROGRAMMING IN C
10
P a g e 72
GM I/ IE/ C L5/ REV00/05
HANDOUT
SPG 0412
PROGRAMMING IN C
unlike the for and while loops, which test the loop condition at the top of the
loop, the dowhile loop checks its condition at the end of the loop.
this means that a dowhile 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
Example: printing 1 to 9 with do..while loop
End
P a g e 73
GM I/ IE/ C L5/ REV00/05
HANDOUT
SPG 0412
PROGRAMMING IN C
return 0;
Output
1
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);
}
P a g e 74
GM I/ IE/ C L5/ REV00/05
HANDOUT
SPG 0412
PROGRAMMING IN C
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.
P a g e 75
GM I/ IE/ C L5/ REV00/05
HANDOUT
SPG 0412
PROGRAMMING IN C
forces the iteration of the loop to take place and skips any code in between.
printf("%d", x);
}
printf("\nUsed continue to skip printing the value 5\n");
return 0;
}
Output
1
2
3
4
6
7
8
9
Used continue to skip printing the value 5
10
P a g e 76
GM I/ IE/ C L5/ REV00/05
HANDOUT
SPG 0412
PROGRAMMING IN C
Exercise
1. What is the output for each of the following programs below: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.
Hint : There are 6 errors in the program below
P a g e 77
GM I/ IE/ C L5/ REV00/05
(6 Marks)
HANDOUT
SPG 0412
PROGRAMMING IN C
3. Find the error in each of the following code segments and explain how to correct it.
a. x = 1;
while (x <= 10);
x++;
b) for (y = .1; y != 1.0; y += .1)
printf (%f\n, y);
(2 Marks)
P a g e 78
GM I/ IE/ C L5/ REV00/05
HANDOUT
SPG 0412
PROGRAMMING IN C
CHAPTER 7
Array
P a g e 79
GM I/ IE/ C L5/ REV00/05
HANDOUT
SPG 0412
PROGRAMMING IN C
1.0 Array
o
The common array operation e.g are scanning, sorting and writing vector.
To define marks we use square bracket [ ] to write the number of elements that
it will contains.
P a g e 80
GM I/ IE/ C L5/ REV00/05
HANDOUT
SPG 0412
PROGRAMMING IN C
/*array.c*/
/* calculate the average of an array of numbers*/
#include <stdio.h>
const int MAX = 5; /*size of array*/
int main( )
{
int age[ ] = {19,17,18,20,22}; /*initialization of an
array*/
for(int i =0; i <MAX; i++)
printf("\nElement [%d] = %d\n",i,age[i]); /*output all
the array elements of age[ ] with its array index*/
float marks[MAX]; /*define array of 5 elements*/
float sum = 0.0;
for(int j=0; j <MAX; j++)
{
printf("\nEnter Mark %d: ", j+1);
scanf("%f", &marks);
sum += marks[j];
/*sum the marks*/
}
float average = sum/MAX;
printf("\nThe average of the marks is = %.2f",
average);
return 0;
}
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
The average of the marks is 20.00
P a g e 81
GM I/ IE/ C L5/ REV00/05
HANDOUT
SPG 0412
PROGRAMMING IN C
{{ 1,2,3,4,5 },
{ 6,7,8,9,10 },
{ 11,12,13,14,15,16}};
/*matintro.c*/
/*introduction to 2-dimensional arrays(matrices)*/
#include <stdio.h>
const int ROWS = 2, COLS = 3;
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*/
for(int i=0; i <ROWS; ++i)
{
printf( "\n");
/*start a new line for each row*/
for(int j=0; j<COLS;j++)
{
mat1[i][j] = mat2[i][j];
/*Assigning values to
mat1 matrix*/
printf(" %d " , mat1[i][j]);
}
}
return 0;
}
Output
123
456
P a g e 82
GM I/ IE/ C L5/ REV00/05
HANDOUT
SPG 0412
PROGRAMMING IN C
Exercise
2. #include <stdio.h>
#define N10
void main( ) {
int value[N] = {1, 1};
int i;
P a g e 83
GM I/ IE/ C L5/ REV00/05
HANDOUT
SPG 0412
PROGRAMMING IN C
3. Use a one dimensional array to solve the following problem. Read in 20
numbers, each of which is between 10 and 100, inclusive. As each number is
read, print it only if it is not a duplicate of a number already read. Provide the
worst case in which all 20 numbers are different. Use the smallest possible
array to solve this problem.
4. Find the error in each of the following program segments and correct the
error.
P a g e 84
GM I/ IE/ C L5/ REV00/05
HANDOUT
SPG 0412
PROGRAMMING IN C
CHAPTER 8
Pointer
P a g e 85
GM I/ IE/ C L5/ REV00/05
HANDOUT
SPG 0412
PROGRAMMING IN C
1.0
POINTER
1.1
Like other variable, it must be declared before they can be used. E.g: int *aPtr. It
means that the variable *aPtr to be of type int *(i.e. a pointer to an integer value) and
is read as aPtr is a pointer to int or aPtr points to an object of type integer.
The &(address operator) is a unary operator that returns the address of its
operand. For example, assuming the declarations
int y = 5;
int *yPtr;
yPtr = &y;
The operator * returns the value of the object to which the pointer points to.
5
yPtr
Assume that the int variable y is stored at location 600000, and pointer
variable yPtr is stored at location 500000.
yPtr
500000
600000
y
600000
P a g e 86
GM I/ IE/ C L5/ REV00/05
HANDOUT
SPG 0412
PROGRAMMING IN C
#include <stdio.h>
/*This program tells you about simple pointer*/
int main( )
{
int ali = 100;
int *aliPtr;
aliPtr = &ali;
P a g e 87
GM I/ IE/ C L5/ REV00/05
HANDOUT
SPG 0412
PROGRAMMING IN C
Output
The address of a is 1245064
The value of aPtr is 1245064
The value of a is 7
The value of aPtr is 7
Proving that * and & are compliments of each other.
&*aPtr = 1245064
*&aPtr = 1245064
P a g e 88
GM I/ IE/ C L5/ REV00/05
HANDOUT
SPG 0412
PROGRAMMING IN C
#include <stdio.h>
void printCharacters(const char *);
int main( ){
char string[] = "print characters of a string";
printf("the string is:\n");
printCharacters(string);
putchar('\n');
return 0;
}
void printCharacters(const char *s)
{
for(;*s != '\0'; s++)
putchar(*s);
}
Output
the string is:
print characters of a string
Dynamically allocated variables are variables that do not exist when the program is
loaded, but are created dynamically as they are needed.
It is possible, using these techniques, to create as many variables as needed, use them,
and deallocate their space for use by other variables.
In the example dynlist.c below, we do not define any variables of this type, only three
pointers.
If you search through the remainder of the program, you will find no variables defined so
have nothing to store data in.
All we have to work with are three pointers, each of which point to the defined structure.
P a g e 89
GM I/ IE/ C L5/ REV00/05
HANDOUT
SPG 0412
PROGRAMMING IN C
// dynlist.c
#include<stdio.h>
#include <string.h>
#include<malloc.h>
void main( )
{
struct animal {
char name[25];
char breed[25];
int age;
} *pet1, *pet2, *pet3;
pet1 = (struct animal *)malloc(sizeof(struct animal));
strcpy(pet1->name,"General");
strcpy(pet1->breed,"Mixed Breed");
pet1->age = 1;
pet2 = pet1; /* pet2 now points to the above data structure */
pet1 = (struct animal *)malloc(sizeof(struct animal));
strcpy(pet1->name,"Frank");
strcpy(pet1->breed,"Labrador Retriever");
pet1->age = 3;
pet3 = (struct animal *)malloc(sizeof(struct animal));
strcpy(pet3->name,"Krystal");
strcpy(pet3->breed,"German Shepherd");
pet3->age = 4;
/* now print out the data described above */
printf("%s is a %s, and is %d years old.\n", pet1->name,
pet1->breed, pet1->age);
printf("%s is a %s, and is %d years old.\n", pet2->name,
pet2->breed, pet2->age);
printf("%s is a %s, and is %d years old.\n", pet3->name,
pet3->breed, pet3->age);
pet1 = pet3; /* pet1 now points to the same structure that
pet3 points to
*/
free(pet3); /* this frees up one structure
*/
free(pet2); /* this frees up one more structure
*/
}
P a g e 90
GM I/ IE/ C L5/ REV00/05
HANDOUT
SPG 0412
PROGRAMMING IN C
output
Frank is a Labrador Retriever, and is 3 years old.
General is a Mixed Breed, and is 1 years old.
Krystal is a German Shepherd, and is 4 years old.
The first program statement, which assigns something to the pointer "pet1" will create a
dynamic structure containing three variables.
The heart of the statement is the "malloc" function buried in the middle of the statement.
This is a "memory allocate" function that needs the other things to completely define it.
The "malloc" function, by default, will allocate a piece of memory on a "heap" that is "n"
characters in length and will be of type character. The "n" must be specified as the only
argument to the function.
A heap is an area which can be accessed by the program to store data and variables.
The data and variables are put on the "heap" by the system as calls to "malloc" are
made.
The system keeps track of where the data is stored. Data and variables can be
deallocated as desired leading to holes in the heap.
The system knows where the holes are and will use them for additional data storage as
more "malloc" calls are made.
The structure of the heap is therefore a very dynamic entity, changing constantly.
The keywords new and delete can be used to allocate and deallocate memory. They are
much more easier to use than the functions malloc and free from standard C. new []
and delete [] are used for arrays:
P a g e 91
GM I/ IE/ C L5/ REV00/05
HANDOUT
SPG 0412
PROGRAMMING IN C
#include <stdio.h>
#include <string.h>
int main ()
{
double *d;
d = new double;
*d = 45.3;
*d = *d + 5;
printf("Result: %.2f\n", *d);
delete d;
P a g e 92
GM I/ IE/ C L5/ REV00/05
HANDOUT
SPG 0412
PROGRAMMING IN C
4.1.2 malloc( )
malloc( ) function will allocates memory dynamically when you run the program.
the function prototype is as follows :
void *malloc ( size_t size);
4.1.3 free( )
free function will free the memory that has been allocated for malloc( ) function.
the function prototype :
void free (void *ptr);
P a g e 93
GM I/ IE/ C L5/ REV00/05
HANDOUT
SPG 0412
PROGRAMMING IN C
Output
Enter the number of data that you want: 5
69
0
34
67
41
P a g e 94
GM I/ IE/ C L5/ REV00/05
HANDOUT
SPG 0412
PROGRAMMING IN C
Exercise
1. Give the output for the program below:-
(6 Marks)
/* Using pointer */
#include <stdio.h>
main( )
{
int a, b;
int *aPtr, *bPtr;
a = 7;
aPtr = &a;
b = 5;
bPtr = &b;
/* a and b is an integer */
/* aPtr and bPtr is a pointer to an integer */
P a g e 95
GM I/ IE/ C L5/ REV00/05
HANDOUT
SPG 0412
PROGRAMMING IN C
#include <stdio.h>
int main( ) {
int a = 8;
int b = 10;
int aPtr = &a;
int bPtr = &b;
printf (\nThe address of a is %d\n, aPtr);
printf(The address of bPtr is %d\n, &bPtr);
printf(The value that aPtr pointed to is %d\n, *aPtr);
printf(The value that bPtr pointed to is %d\n, *bPtr);
return 0;
}
(4 Marks)
P a g e 96
GM I/ IE/ C L5/ REV00/05
HANDOUT
SPG 0412
PROGRAMMING IN C
CHAPTER 9
Fail Manipulation
P a g e 97
GM I/ IE/ C L5/ REV00/05
HANDOUT
SPG 0412
PROGRAMMING IN C
Disk is used to store data. Text editor can edit data file.
Data that has been saved can be read, edited, deleted or appended by using C
program.
The advantage of data file is the same program or another program can use it
repeatedly.
C Language can process 2 types of files; text file and binary file.
Text file is a file created from text editor or word processing software. The size of text
files varies. It depends to the number of characters in that file.
To mark the end of file, computer will put a special end-of-file character <eof>.
The way of accessing data determines how we read, write, edit and deleting data.
Its hard to add or access data in the middle of a file. However, many applications
used this type of accesses.
We can play any song that we want without forwarding like in a cassette player.
P a g e 98
GM I/ IE/ C L5/ REV00/05
HANDOUT
1.0
SPG 0412
PROGRAMMING IN C
fileptr is a special ponter that points to that file. It was declared as FILE *fileptr.
Below is a table showing the file access mode.
String
Meaning
r+
w+
a+
Open for append, open for update at the end of the file,
or create if the file does not exist.
FILE *fptr;
fptr = fopen(C:\\TEST.DAT, w);
if you want to test the return value to ensure the file was open correctly, use the
following code segment:
FILE *fptr
If ((fileptr = fopen(C:\\TEST.DAT, r)) == NULL)
{
printf(Error: Cannot open input file\n);
exit(0);
}
P a g e 99
GM I/ IE/ C L5/ REV00/05
HANDOUT
2.0
SPG 0412
PROGRAMMING IN C
Example:
FILE *fptr;
fptr = fopen(FILE.TXT, w);
putc(p, fptr);
fclose(fptr);
/*Writer.c - writing to a text file*/
#include <stdio.h>
#include <stdlib.h>
#include <process.h>
int main( ){
char ch, filename[85];
FILE *fileptr;
printf("\nEnter filename: ");
gets(filename);
/*create a filename*/
P a g e 100
GM I/ IE/ C L5/ REV00/05
HANDOUT
SPG 0412
PROGRAMMING IN C
P a g e 101
GM I/ IE/ C L5/ REV00/05
HANDOUT
SPG 0412
PROGRAMMING IN C
The fputs() function is use to write an entire strings at once from file.
P a g e 102
GM I/ IE/ C L5/ REV00/05
HANDOUT
SPG 0412
PROGRAMMING IN C
Output
Press Enter on a blank line to exit.
Enter filename to write to: Example.dat
Today is a beautiful day. Mary strolls in the park with her friend, Don.
P a g e 103
GM I/ IE/ C L5/ REV00/05
HANDOUT
SPG 0412
PROGRAMMING IN C
Output
P a g e 104
GM I/ IE/ C L5/ REV00/05
HANDOUT
SPG 0412
PROGRAMMING IN C
Exercise
2. Find the error in each of the following program segments. Explain how the error
can be corrected.
a) The file referred to by fPtr(payables.dat) has not been open.
fprintf (fPtr, %d%s%d\n, account, company, amount);
b) open(receive.dat, r+);
c) The file tools.dat should be opened to add data to the file without discarding the
current data.
if ((tfPtr = fopen(tools.dat, w)) != NULL)
d) The file courses.dat should be opened for appending without modifying the
contents of the file.
if ((cfPtr = fopen(courses.dat, w+)) != NULL)
P a g e 105
GM I/ IE/ C L5/ REV00/05
HANDOUT
SPG 0412
PROGRAMMING IN C
CHAPTER 10
Structure
P a g e 106
GM I/ IE/ C L5/ REV00/05
HANDOUT
SPG 0412
PROGRAMMING IN C
You have the ability to define a new type of data considerably more complex than the
types we have been using.
struct date {
int day;
int month;
int year;
};
P a g e 107
GM I/ IE/ C L5/ REV00/05
HANDOUT
SPG 0412
PROGRAMMING IN C
#include <stdio.h>
void main( )
{
struct {
char initial; /* last name initial */
int age;
/* childs age
*/
int grade;
/* childs grade in school */
} boy,girl;
boy.initial = 'R';
boy.age = 15;
boy.grade = 75;
girl.age = boy.age - 1; /* she is one year younger */
girl.grade = 82;
girl.initial = 'H';
printf("%c is %d years old and got a grade of %d\n",
girl.initial, girl.age, girl.grade);
printf("%c is %d years old and got a grade of %d\n",
boy.initial, boy.age, boy.grade);
}
Output
H is 14 years old and got a grade of 82
R is 15 years old and got a grade of 75
Press any key to continue
P a g e 108
GM I/ IE/ C L5/ REV00/05
HANDOUT
SPG 0412
PROGRAMMING IN C
e.g boy.age = 15
P a g e 109
GM I/ IE/ C L5/ REV00/05
HANDOUT
SPG 0412
PROGRAMMING IN C
Output
Id-No : 1234
Name : Aminah
Town: KL
The student is Aminah with id# 1234 from KL
Exercise
1. Write a structure definition struct for a student with the following information:
a) name
b) date of birth
c) new identity card number
d) telephone number
B.y = A.y;
C.x = B.x;
C.y = A.y + t;
D.x = A.x;
D.y = C.y;
10
b)
100
20
100
55
c)
333
222
P a g e 110
GM I/ IE/ C L5/ REV00/05