64
Bismillah hir Rehman nir Raheem ------------------------------------Assalat o Wasalam o Allika Ya RasoolALLAH To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN Programming Fundamental Notes Sir Umair Babar-PUCIT Published By: Muhammad Hassan Riaz Yousufi

Programming Fundamentals

Embed Size (px)

DESCRIPTION

Programming Fundamentals by Sir Umair Babar for BSSE

Citation preview

Page 1: Programming Fundamentals

Bismillah hir Rehman nir Raheem ------------------------------------Assalat o Wasalam o Allika Ya RasoolALLAH

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN

Programming Fundamental Notes

Sir Umair Babar-PUCIT

Published By: Muhammad Hassan Riaz Yousufi

Page 2: Programming Fundamentals

Contents Pg #

00 – Introduction 3

01 - What is a computer 7

02 - Pseudo Code 9

03 - Flow Charting 15

04 - Pseudo Code Examples 19

05 - Software Development Life Cycle 23

06 - Introduction to C CPP 29

07 - History and Introduction to C CPP 40

08 - Compiler Terminology 47

09 - Data Types and Variables 52

10 - Data Types, Variables and Operators 59

Page 3: Programming Fundamentals

00 - INTRODUCTION

Muh

ammad

Has

san R

iaz Y

ousu

fi

Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN

Page 4: Programming Fundamentals

3/6/2013

1

Umair Babar

[email protected]

Punjab University College of Information Technology.

University of the Punjab, Lahore.

Welcome!� Programming Fundamentals is a course that introduces

students to some fundamental concepts in programming languages.

� The primary goal of the course is to allow students who complete this subject to have� a good feel for the elements of style and aesthetics of programming.

� a strong command to expresses and master the constructs of programming those are unavoidable for any computer science student.

© Umair Babar. PUCIT, Lahore.Programming Fundamentals 2

What is this course not like?� It requires that you do a significant amount of programming

� You need to program in C/C++ programming languages.

� You are expected to read the documentation and learn some essential programming skills.

� You are to be given about 6 home work/Assignments, all of which involve some amount of programming.

Programming Fundamentals © Umair Babar. PUCIT, Lahore. 3

What is this course not like?� It proceeds in a fast pace

� You are expected to read the text that we may not have time to cover in class

� You are expected to try programming examples that we may not have time to explain in class

� You may need to take notes on the materials we cover that are not in the textbook, though I will minimize the need for note-taking by providing you with as many notes as possible

Programming Fundamentals © Umair Babar. PUCIT, Lahore. 4

Muh

ammad

Has

san R

iaz Y

ousu

fi

Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN

Page 5: Programming Fundamentals

3/6/2013

2

What is this course not like?� This may not be a course about your top 10 favorite

computer related disciplines

� We are interested in fundamental concepts of programming.

� We are not so concerned with “fads”

� This course, can certainly be of great help for you to take later programming courses such as OOP etc.

Programming Fundamentals © Umair Babar. PUCIT, Lahore. 5

Warnings� This is likely a challenging course for you as many new and

unfamiliar fundamental concepts in programming languages are to be introduced rapidly

� You may need to give some time for certain concepts to “sink in”.

� You may find that some programming assignments are difficult and demanding.

� Please ask for help if you need it: ask it sooner rather than (too much) later.

Programming Fundamentals © Umair Babar. PUCIT, Lahore. 6

Please� I am likely to be a bit overly ambitious.

� I am certain to make (quite a few) mistakes, but

� I will do my best to make the course run as smoothly as possible.

� Please be patient and ask (a lot of) questions! ☺

Programming Fundamentals © Umair Babar. PUCIT, Lahore. 7

Academic Integrity� Strict adherence to the university guidelines

� All work you turn in must be solely your own unless specified otherwise.

� You are allowed to discuss problems with your classmates but you need to write your own code and solutions.

� Please always remember that every student deserves a chance to achieve a fair grade.

� There will be “No Making Up Quiz” in any case.

� The dead lines of “Home Works” and “Assignments” will strictly be followed.

Programming Fundamentals © Umair Babar. PUCIT, Lahore. 8

Muh

ammad

Has

san R

iaz Y

ousu

fi

Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN

Page 6: Programming Fundamentals

3/6/2013

3

Best Of Luck

☺☺☺☺☺

Programming Fundamentals © Umair Babar. PUCIT, Lahore. 9

The End

Programming Fundamentals © Umair Babar. PUCIT, Lahore. 10

Questions?

Muh

ammad

Has

san R

iaz Y

ousu

fi

Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN

Page 7: Programming Fundamentals

01 - WHAT IS A COMPUTER

Muh

ammad

Has

san R

iaz Y

ousu

fi

Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN

Page 8: Programming Fundamentals

Programming Fundamentals What is a computer?

P a g e | 1 © Umair Babar, PUCIT. Lahore.

WHAT IS A COMPUTER?

We are all familiar with what a computer is in a specific, contemporary sense. Personal computers are found in

most aspects of daily life, and for some it is hard to even imagine a world without them. But the term computer

means more than simply the Macs and PCs we are familiar with. A computer is, at its most basic, a machine which

can take instructions, and perform computations based on those instructions.

It is the ability to take instructions — often known as programs in the parlance of computers — and execute them

that distinguishes a computer from a mechanical calculator. While both are able to make computations, a

calculator responds simply to immediate input. In fact, most modern calculators are actually computers, with a

number of pre-installed programs to help aid in complex tasks.

Computers range from the very small to the very large. Some are capable of doing millions of calculations in a

single second, while others may take long periods of time to do even the most simple calculations. But

theoretically, anything one computer is capable of doing; another computer will also be able to do. Given the right

instructions, and sufficient memory, a computer found in a wristwatch should be able to accomplish anything a

supercomputer can — although it might take thousands of years for the wristwatch to complete the operation.

At one time, computers were extremely large, and required enormous amounts of power. This made them useful

only for a small amount of tasks — computing trajectories for astronomical or military applications, for example, or

code breaking. Over time, with technological advances, the computer was scaled down and its energy

requirements lowered immensely. This allowed the power of the computer to be harnessed for a staggering array

of uses.

As prevalent as personal computers are, they do not nearly begin to scratch the surface of computer use in our

world. Interactive devices of all sorts contain their own computers. Cellular telephones, GPS units, portable

organizers, ATM machines, gas pumps, and millions of other devices all make use of computers to streamline their

operations, and to offer features which would be impossible without a computer.

A computer like this is often referred to as an embedded computer. An embedded computer is differentiated from

a personal computer because it is essentially static in its function. While a personal computer, or some cellular

telephones, or some personal organizers are able to have new software installed, and make use of a wide range of

features, an embedded computer usually has only a few purposes, which are relatively fixed once the computer is

manufactured.

Embedded systems vary in the amount of change that can happen to them after production. An MP3 player, for

example, is an embedded computer, but can have quite a bit of interaction and changes made to it. It may allow

the user to alter the colors used, change the clock, update firmware, and change the songs or playlists in memory.

An embedded computer within a traffic light, to take another example, is probably quite fixed. It is set to respond

to a few certain programs — time of day, a trigger when a car approaches, and perhaps input from a central

database in the case of more advanced systems. These programs are not built for interactivity, and will likely never

be changed over the system’s life.

The computer is one of the most powerful innovations in human history. With the use of computers, people are

suddenly able to perform a staggering amount of computations at dazzling speeds. Information can be crunched,

organized, and displayed in the blink of an eye. As technology continues to advance, the computer will no doubt

become even more pervasive — and in many cases, likely even less recognizable.

Muh

ammad

Has

san R

iaz Y

ousu

fi

Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN

Page 9: Programming Fundamentals

02 - PSEUDO CODE

Muh

ammad

Has

san R

iaz Y

ousu

fi

Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN

Page 10: Programming Fundamentals

3/6/2013

1

Umair Babar

[email protected]

Punjab University College of Information Technology.

University of the Punjab, Lahore.

ALGORITHM� A step by step outline or flowchart how to solve a

problem.

� A sequence of finite instructions, often used for calculation and data processing.

� Examples

� Adding two integers.

� Sorting a list of 5 numbers.

Programming Fundamentals © Umair Babar. PUCIT - PU, Lahore. 2

PROGRAM� Is an implemented coding of a solution to a problem

based on the algorithm.

� Is a set of instructions which were written to perform specific task.

Programming Fundamentals © Umair Babar. PUCIT - PU, Lahore. 3

PROCESS� Is an operation which takes the instructions given and

does the manipulations.

� Any thing that is instructed in the code itself. In other words "EXECUTION OF INSTRUCTIONS".

Programming Fundamentals © Umair Babar. PUCIT - PU, Lahore. 4

Muh

ammad

Has

san R

iaz Y

ousu

fi

Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN

Page 11: Programming Fundamentals

3/6/2013

2

Pseudo Code� An outline of a program, written in a form that can

easily be converted into real programming statements.

� Pseudo code cannot be compiled nor executed, and there are no real formatting or syntax rules.

� You can write pseudo code without even knowing what programming language you will use for the final implementation.

Programming Fundamentals © Umair Babar. PUCIT - PU, Lahore. 5

Basic Operations of Computer� There are six basic computer operations

1. A computer can receive information

Read (information from a file)

Get (information from the keyboard)

2. A computer can put out informationWrite (information to a file)

Display (information to the screen)

Programming Fundamentals © Umair Babar. PUCIT - PU, Lahore. 6

Basic Operations of Computer3. A computer can perform arithmetic

Use actual mathematical symbols or the words for the symbols.

Add number to total

Total = total + number

+, -, *, /

Calculate, Compute also used

Programming Fundamentals © Umair Babar. PUCIT - PU, Lahore. 7

Basic Operations of Computer4. A computer can assign a value to a piece of data

3 cases

to give data an initial value

Initialize, Set

To assign a value as a result of some processing

‘=’

* x = 5 + y

to keep a piece of information for later use

Save, Store

Programming Fundamentals © Umair Babar. PUCIT - PU, Lahore. 8

Muh

ammad

Has

san R

iaz Y

ousu

fi

Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN

Page 12: Programming Fundamentals

3/6/2013

3

Basic Operations of Computer5. A computer can compare two piece of information and

select one of two alternative actions

IF condition THEN

some action

ELSE

alternative action

ENDIF

Programming Fundamentals © Umair Babar. PUCIT - PU, Lahore. 9

Basic Operations of Computer6. A computer can repeat a group of actions

WHILE condition (is true)

some action

ENDWHILE

FOR a number of times

some action

ENDFOR

Programming Fundamentals © Umair Babar. PUCIT - PU, Lahore. 10

The Structure Theorem�We write the pseudo code to represent the control

structures that may or may not cover all the basic operations of computer.

� Any computer program can be written by using only three basic control structures:

1. Sequence

2. Selection

3. Repetition

Programming Fundamentals © Umair Babar. PUCIT - PU, Lahore. 11

Sequence� Execution of one step after another. This is represented

as a sequence of pseudo code statements.

Statement 1

Statement 2

Statement 3

� Example

Read three numbers

Add three numbers

Display total of three numbers

Programming Fundamentals © Umair Babar. PUCIT - PU, Lahore. 12

Muh

ammad

Has

san R

iaz Y

ousu

fi

Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN

Page 13: Programming Fundamentals

3/6/2013

4

Selection� Presentation of a condition and the choice between

two actions, the choice depending on whether the condition is true or false. This construct represents the decision making abilities of the computer to compare two pieces of information and select one of two alternative actions.

� In pseudo code, selection is represented by the keywords IF, THEN, ELSE and ENDIF.

Programming Fundamentals © Umair Babar. PUCIT - PU, Lahore. 13

SelectionIF condition p is true THEN

statement(s) in true case

ELSE

statement(s) in false case

ENDIF

� ExampleIF student is part_time THEN

Add one to part_time_count

ELSE

Add one to full_time_count

ENDIFProgramming Fundamentals © Umair Babar. PUCIT - PU, Lahore. 14

Selection� A variation

� We don’t need the ELSE structure.

� The null ELSE.

IF condition p is true THEN

statement(s) in true case

ENDIF

Programming Fundamentals © Umair Babar. PUCIT - PU, Lahore. 15

Repetition� Presentation of a set of instructions to be performed

repeatedly, as long as a condition is true.

WHILE condition p is true

Statement(s) to execute

ENDWHILE

� The condition is tested before any statements are executed. It is imperative that at lease one statement within the statement block alter the condition and eventually render it false, otherwise the logic may result in an endless loop.

Programming Fundamentals © Umair Babar. PUCIT - PU, Lahore. 16

Muh

ammad

Has

san R

iaz Y

ousu

fi

Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN

Page 14: Programming Fundamentals

3/6/2013

5

RepetitionExample:

Set student_total to o

WHILE student_total < 50

Read student record

Print student name and address

Add 1 to student_total

ENDWHILE

Note: The variable student_total is initialized before the loop condition is executed. The student_total variable is incremented within the body of the loop so it will eventually stop. These are both essential feature of the WHILE construct.

Programming Fundamentals © Umair Babar. PUCIT - PU, Lahore. 17

The End

Programming Fundamentals © Umair Babar. PUCIT - PU, Lahore. 18

Questions?

Muh

ammad

Has

san R

iaz Y

ousu

fi

Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN

Page 15: Programming Fundamentals

03 - FLOW CHARTING

Muh

ammad

Has

san R

iaz Y

ousu

fi

Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN

Page 16: Programming Fundamentals

3/6/2013

1

Umair Babar

[email protected]

Punjab University College of Information Technology.

University of the Punjab, Lahore.

Flowchart� Is common type of chart used to represents an algorithm or

process.

� The steps are shown in boxes of various kinds, and their order by connecting these with arrows.

� Flowcharts are used in analyzing, designing, documenting or managing a process or program in various fields.

Programming Fundamentals © Umair Babar. PUCIT, Lahore. 2

Flowchart� The two most common types of boxes in a flowchart

are:

� a processing step, usually called activity, and denoted as a rectangular box.

� a decision, usually denoted as a diamond.

Programming Fundamentals © Umair Babar. PUCIT, Lahore. 3

Add 1 to student_count

ISA = B?

Flowchart: Symbols� Start and End

� Represented as ovals or rounded rectangles, usually containing the word "Start" or "End“.

� Arrows

� An arrow coming from one symbol and ending at another symbol represents that control passes to the symbol the arrow points to.

Programming Fundamentals © Umair Babar. PUCIT, Lahore. 4

Start Start

Muh

ammad

Has

san R

iaz Y

ousu

fi

Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN

Page 17: Programming Fundamentals

3/6/2013

2

Flowchart: Symbols� Processing steps

� Represented as rectangles.

� Input/Output

� Represented as a parallelogram.

Programming Fundamentals © Umair Babar. PUCIT, Lahore. 5

Add 1 to X Save Changes

Get X from user Display X

Flowchart: Symbols� Conditional or Decision

� Represented as a diamond. These typically contain a Yes/No question or True/False test.

Programming Fundamentals © Umair Babar. PUCIT, Lahore. 6

Is a<5

No Yes

The Three Programming Control Structures

Programming Fundamentals © Umair Babar. PUCIT, Lahore. 7

� All programs can be described by combining the following 3 control structures:

Simple Sequence

Simple Selection(IF-THEN-ELSE) Simple Repitition

(Loop)

Flowchart� A simple flowchart representing a process for dealing

with a broken lamp.

Programming Fundamentals © Umair Babar. PUCIT, Lahore. 8

Wikipedia

Muh

ammad

Has

san R

iaz Y

ousu

fi

Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN

Page 18: Programming Fundamentals

3/6/2013

3

Flowchart� Draw a flowchart that’ll compute the sum, average and

product of three numbers.

Programming Fundamentals © Umair Babar. PUCIT, Lahore. 9

Start

Read A, B, C

S = A + B + CAvg = S/3

P = A * B * C

Write S, Avg, P

Stop

Pseudo Code

Read A, B, C

Compute Sum (S) as A + B + C

Compute Average (Avg) as S / 3

Compute Product (P) as A x B x C

Write (Display) the Sum, Average and Product

Flowchart� Draw a flowchart that’ll read 2 numbers and displays

the numbers read in decreasing order.

Programming Fundamentals © Umair Babar. PUCIT, Lahore. 10

Start

Read A, B

A < B ?BIG = A

SMALL = BBIG = B

SMALL = A

Write BIG, SMALL

End

yesno

Pseudo Code

Read A, B

If A is less than BBIG = BSMALL = A

elseBIG = ASMALL = B

Write (Display) BIG, SMALL

Flowchart� Draw a flowchart that’ll count from 1 to 10.

Programming Fundamentals © Umair Babar. PUCIT, Lahore. 11

C = 1

Procedure

C = C + 1

K > 10 ?

Enter Loop

yesExit from loop

no

Pseudo Code

?

The End

Programming Fundamentals © Umair Babar. PUCIT, Lahore. 12

Questions?

Muh

ammad

Has

san R

iaz Y

ousu

fi

Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN

Page 19: Programming Fundamentals

04 - PSEUDO CODE EXAMPLES

Muh

ammad

Has

san R

iaz Y

ousu

fi

Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN

Page 20: Programming Fundamentals

Programming Fundamentals Pseudo Code Examples

P a g e | 1 © Umair Babar, PUCIT. Lahore.

PSEUDO CODE EXAMPLES

An algorithm is a procedure for solving a problem in terms of the actions to be executed and the order in which

those actions are to be executed. An algorithm is merely the sequence of steps taken to solve a problem. The steps

are normally "sequence," "selection," "iteration," and a case-type statement.

In C, "sequence statements" are imperatives. The "selection" is the "if then else" statement, and the iteration is

satisfied by a number of statements, such as the "while," " do," and the "for," while the case-type statement is

satisfied by the "switch" statement.

Pseudo code is an artificial and informal language that helps programmers develops algorithms. Pseudo code is a

"text-based" detail (algorithmic) design tool.

The rules of Pseudo code are reasonably straightforward. All statements showing "dependency" are to be

indented. These include while, do, for, if, switch. Examples below will illustrate this notion.

EXAMPLES:

1.

If student's grade is greater than or equal to 60

Print "passed"

else

Print "failed"

2.

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

Set the class average to the total divided by ten

Print the class average.

M

uham

mad H

assa

n Riaz

You

sufi

Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN

Page 21: Programming Fundamentals

Programming Fundamentals Pseudo Code Examples

P a g e | 2 © Umair Babar, PUCIT. Lahore.

3.

Initialize total to zero

Initialize counter to zero

Input the first grade

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)

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'

Muh

ammad

Has

san R

iaz Y

ousu

fi

Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN

Page 22: Programming Fundamentals

Programming Fundamentals Pseudo Code Examples

P a g e | 3 © Umair Babar, PUCIT. Lahore.

4.

initialize passes to zero

initialize failures to zero

initialize student to one

while student counter is less than or equal to ten

input the next exam result

if the student passed

add one to passes

else

add one to failures

add one to student counter

print the number of passes

print the number of failures

if eight or more students passed

print "raise tuition"

Some Keywords that should be used

For looping and selection, the keywords that are to be used include Do While...EndDo; Do Until...Enddo;

Case...EndCase; If...Endif; Call ... with (parameters); Call; Return ....; Return; When; Always use scope terminators

for loops and iteration.

As verbs, use the words Generate, Compute, Process, etc. Words such as set, reset, increment, compute, calculate,

add, sum, multiply, ... print, display, input, output, edit, test , etc. with careful indentation tend to foster desirable

pseudo code.

Do not include data declarations in your pseudo code.

M

uham

mad H

assa

n Riaz

You

sufi

Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN

Page 23: Programming Fundamentals

05 - SOFTWARE DEVELOPMENT LIFE CYCLE

Muh

ammad

Has

san R

iaz Y

ousu

fi

Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN

Page 24: Programming Fundamentals

3/6/2013

1

Umair Babar

[email protected]

Punjab University College of Information Technology.

University of the Punjab, Lahore.

Software Development Life Cycle (SDLC)

“You’ve got to be very careful if you don’t know Where you’re going, because you might not get there.”

Yogi Berra

Programming Fundamentals 2© Umair Babar. PUCIT, Lahore.

Software Process� Software Process defines the way to produce software.

It includes

� Software life-cycle model

� Tools to use

� Individuals building software

� Software life-cycle model defines how different phases of the life cycle are managed.

Programming Fundamentals 3© Umair Babar. PUCIT, Lahore.

Phases of Software Life-cycle� Requirements

� Specification (Analysis)

� Design

� Implementation

� Integration

� Maintenance

� Retirement

Programming Fundamentals 4© Umair Babar. PUCIT, Lahore.

Muh

ammad

Has

san R

iaz Y

ousu

fi

Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN

Page 25: Programming Fundamentals

3/6/2013

2

Requirements� Assumption� The software being considered is considered

economically justifiable.

� Concept exploration� Determine what the client needs, not what the client

wants

� Document - Requirements Document

5Programming Fundamentals © Umair Babar. PUCIT, Lahore.

Specification (Analysis) Phase� From the customer requirements identify what to

build.

� Specifications must not be� Ambiguous

� Incomplete

� Contradictory

� Document – Specification Document

6Programming Fundamentals © Umair Babar. PUCIT, Lahore.

Design Phase� From the specification identify how to build.

� Design involves two steps

� Architectural Design – Identify modules

� Detailed Design – Design each modules

� Document – Architecture Document, Design Document

7Programming Fundamentals © Umair Babar. PUCIT, Lahore.

Implementation Phase� Implement the detailed design in code.

� Developer testing

�Unit testing

�Module testing

� Document – Commented source code

8Programming Fundamentals © Umair Babar. PUCIT, Lahore.

Muh

ammad

Has

san R

iaz Y

ousu

fi

Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN

Page 26: Programming Fundamentals

3/6/2013

3

Integration Phase� Combine the modules and test the product as a whole.

� Testing includes

�Product testing

�Acceptance testing

� Document – Test cases and test results

9Programming Fundamentals © Umair Babar. PUCIT, Lahore.

Maintenance Phase� Any changes after the customer accepts the

system.

�Maintenance phase is the most expensive

� Lack of documentation

� Regression testing

� Document – Documented Changes, Regression test cases

10Programming Fundamentals © Umair Babar. PUCIT, Lahore.

Retirement Phase� Good software is maintained

� Sometimes software is rewritten from scratch� Software is now un-maintainable because� A drastic change in design has occurred

� The product must be implemented on a totally new

� hardware/operating system

� Documentation is missing or inaccurate

� Hardware is to be changed—it may be cheaper to rewrite

� the software from scratch than to modify it

� True retirement is a rare event

11Programming Fundamentals © Umair Babar. PUCIT, Lahore.

Life-Cycle Models� Build-and-fix model

�Waterfall model

� Rapid prototyping model

� Incremental model

� Extreme programming

� Synchronize-and-stabilize model

� Spiral model

� Object-oriented life-cycle models

� Comparison of life-cycle models

12Programming Fundamentals © Umair Babar. PUCIT, Lahore.

Muh

ammad

Has

san R

iaz Y

ousu

fi

Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN

Page 27: Programming Fundamentals

3/6/2013

4

Build and Fix Model

13Programming Fundamentals © Umair Babar. PUCIT, Lahore.

Notes� Most software is developed using build-and-fix model.

Basically there is no model.

� No specifications

� No design

� This model is completely unsatisfactory and should not be adopted.

� Need life-cycle model

� “Game plan”

� Phases

� Milestones

14Programming Fundamentals © Umair Babar. PUCIT, Lahore.

Waterfall Model

15Programming Fundamentals © Umair Babar. PUCIT, Lahore.

Notes� Output from one phase is fed as input to the next phase.

� One phase is completed, documented and signed-off before the next phase begins.

� Advantages� Each phase is well documented.

� Maintenance easier.

� Disadvantages� If there is a mismatch between what the client wanted and was is

built this will not be known till the product is delivered.

16Programming Fundamentals © Umair Babar. PUCIT, Lahore.

Muh

ammad

Has

san R

iaz Y

ousu

fi

Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN

Page 28: Programming Fundamentals

3/6/2013

5

Rapid Prototyping Model

17Programming Fundamentals © Umair Babar. PUCIT, Lahore.

Notes

� A prototype of the product is build rapidly and shown to the client before the product is completely built.

� Advantages :

� Any mismatches between requirement and the product can be found early.

� Disadvantages :

� Sometimes the prototype ends up being the final product which results in quality, maintenance problems.

18Programming Fundamentals © Umair Babar. PUCIT, Lahore.

Summary

�Software Engineering is an important discipline due to various aspects.

�Analysis and Design are two very important phases in the software development lifecycle.

19Programming Fundamentals © Umair Babar. PUCIT, Lahore.

The End

Questions?

Programming Fundamentals 20© Umair Babar. PUCIT, Lahore.

Muh

ammad

Has

san R

iaz Y

ousu

fi

Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN

Page 29: Programming Fundamentals

06 - INTRODUCTION TO C CPP

Muh

ammad

Has

san R

iaz Y

ousu

fi

Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN

Page 30: Programming Fundamentals

3/6/2013

1

Umair Babar

[email protected]

Punjab University College of Information Technology.

University of the Punjab, Lahore.

Writing C/C++ Programs� A programmer uses a text editor to create or

modify files containing C/C++ code.

� Code is also known as source code.

� A file containing source code is called a source file.

� After a C/C++ source file has been created, the programmer must invoke the C/C++ compiler before the program can be executed (run).

Programming Fundamentals 2© Umair Babar. PUCIT, Lahore.

Using the C/C++ Compiler� Invoking the compiler is system dependent.

� We have variety of C/C++ compilers available to date, like gcc, g++, turbo C/C++, Borland C/C++, Microsoft C/C++.

� For this class, we will use the Microsoft C++ compiler.

� All grading is down on Microsoft C++. You are free to use any other compiler if you like to.

� There are differences between the compilers and we only support Microsoft C++ compiler available on MS Windows!

Programming Fundamentals 3© Umair Babar. PUCIT, Lahore.

Invoking the Borland C++ Compiler� Press F7 to build (compile) the code.

� Press ctrl + f5 to compile and run the program.

� Press f5 to compile and run the program in debug mode.

Programming Fundamentals 4© Umair Babar. PUCIT, Lahore.

Muh

ammad

Has

san R

iaz Y

ousu

fi

Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN

Page 31: Programming Fundamentals

3/6/2013

2

The Result

� If there are no errors in file.cpp, than an executable file,which is one that can be executed (run) will begenerated.

Programming Fundamentals 5© Umair Babar. PUCIT, Lahore.

3 Stages of Compilation

� Stage 1: Preprocessing

� Performed by a program called the preprocessor.

� Modifies the source code (in RAM) according to preprocessor directives (preprocessor commands) embedded in the source code.

� Strips comments and white space from the code.

� The source code as stored on disk is not modified.

Programming Fundamentals 6© Umair Babar. PUCIT, Lahore.

3 Stages of Compilation

� Stage 2: Compilation

� Performed by a program called the compiler.

� Translates the preprocessor-modified source code into object code (machine code).

� Checks for syntax errors and warnings.

� Saves the object code to a disk file, if instructed to do so.

o If any compiler errors are received, no object code file will be generated.

o An object code file will be generated if only warnings, not errors, are received.

Programming Fundamentals 7© Umair Babar. PUCIT, Lahore.

3 Stages of Compilation� Stage 3: Linking

� Combines the program object code with other object code to produce the executable file.

� The other object code can come from the Run-Time Library, other libraries, or object files that you have created.

� Saves the executable code to a disk file. On the Windows system, that file is called file.exe.

o If any linker errors are received, no executable file will be generated.

Programming Fundamentals 8© Umair Babar. PUCIT, Lahore.

Muh

ammad

Has

san R

iaz Y

ousu

fi

Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN

Page 32: Programming Fundamentals

3/6/2013

3

Program Development

Source File hello.cpp

Program Object Code File hello.obj

Executable File hello.exe

Preprocessor

Modified Source Code in RAM

Compiler

Linker

Other Object Code Files (if any)

Editor

Programming Fundamentals 9© Umair Babar. PUCIT, Lahore.

A Simple C++ Program/* Filename: hello.cpp

Author: Umair Babar

Date written: dd-mm-yyyy

Description: This program prints the greeting “Hello Class”

*/

# include <iostream>

using namespace std;

int main()

{

cout<<"Hello Class";

return 0;

}Programming Fundamentals 10© Umair Babar. PUCIT, Lahore.

Anatomy of a C Programprogram header comment

preprocessor directives (if any)

int main ()

{

statement(s)

return 0;

}Programming Fundamentals 11© Umair Babar. PUCIT, Lahore.

Program Header Comment� A comment is descriptive text used to help a reader of

the program understand its content.

� Single line comment must begin with the characters //

� //this is a single line comment

� Multiline comments start with the character /* end with the characters */

� /*

This is a multiline comments

Name: hello.cpp

*/

Programming Fundamentals 12© Umair Babar. PUCIT, Lahore.

Muh

ammad

Has

san R

iaz Y

ousu

fi

Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN

Page 33: Programming Fundamentals

3/6/2013

4

Program Header Comment� // and /* … */ are called comment delimiters.

� The program header comment always comes first.

Programming Fundamentals © Umair Babar. PUCIT, Lahore. 13

Preprocessor Directives

� Lines that begin with a # in column 1 are called preprocessor directives (commands).

� Example

� The #include <iostream> directive causes the preprocessor to include a copy of the input/output stream header file at this point in the code.

� This header file was included because it contains information about the cout operator that is used in this program to display “Hello Class”.

Programming Fundamentals 14© Umair Babar. PUCIT, Lahore.

iostream.h�When we write our programs, there are libraries of

functions to help us so that we do not have to write the same code over and over.

� Some of the functions are very complex and long. Not having to write them ourselves make it easier and faster to write programs.

� Using the functions will also make it easier to learn to program!

Programming Fundamentals 15© Umair Babar. PUCIT, Lahore.

int main ()� Every program must have a function called main.

This is where program execution begins.

�main() is placed in the source code file as the first function for readability.

� There must be a function with this name or compiler can not successfully compile and link your program.

Programming Fundamentals 16© Umair Babar. PUCIT, Lahore.

Muh

ammad

Has

san R

iaz Y

ousu

fi

Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN

Page 34: Programming Fundamentals

3/6/2013

5

int main ()� The reserved word “int” indicates that main()

returns an integer value.

� The parentheses following the reserved word “main” indicate that it is a function.

� You can use another reserve word “void” instead of “int” . The reserved word “void” means nothing is there and when you use it no return statement is required.

Programming Fundamentals © Umair Babar. PUCIT, Lahore. 17

The Function Body

� A left brace (curly bracket) { begins the body of every function. A corresponding right brace } ends the function body.

� The style is to place these braces on separate lines in column 1 and to indent the entire function body 3 to 5 spaces.

Programming Fundamentals 18© Umair Babar. PUCIT, Lahore.

cout << “Hello Class”;� This line is a C++ statement.

� It is a call to the operator cout with a single argument (parameter), namely the string “Hello, Class”.

� Even though a string may contain many characters, the string itself should be thought of as a single quantity.

� Notice that this line ends with a semicolon. All statements in C/C++ end with a semicolon.

Programming Fundamentals 19© Umair Babar. PUCIT, Lahore.

Another C++ Program/*****************************************

** File: product.cpp

** Author: Umair Babar

** Date: dd-mm-yyyy

** Roll #: BITFOTXYZ

** Section: Morning

** E-mail: [email protected]

**

** This program prompts the user for two integer values then displays their product.

**

***********************************************/

Programming Fundamentals 20© Umair Babar. PUCIT, Lahore.

Muh

ammad

Has

san R

iaz Y

ousu

fi

Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN

Page 35: Programming Fundamentals

3/6/2013

6

Another C++ Program (cont…)# include <iostream>using namespace std;

int main(){

int value1, value2, product;

cout<<"Enter First Integer: ";cin>>value1;

cout<<"Enter Second Integer: ";cin>>value2;

cout<<"Product = "<<value1 * value2;return 0;}

Programming Fundamentals 21© Umair Babar. PUCIT, Lahore.

Another C++ Program (Output)

Programming Fundamentals © Umair Babar. PUCIT, Lahore. 22

Good Programming Practices� C/C++ programming standards and indentation

styles are available on many web sites.

� You are expected to conform to these standards for all programming projects in this class.

� This will be part of your grade for each project!

� The program just shown conforms to these standards, but is uncommented (later).

� Subsequent lectures will include more “Good Programming Practices” slides.

Programming Fundamentals 23© Umair Babar. PUCIT, Lahore.

Programming Style and Documentation

�Appropriate Comments

�Naming Conventions

�Proper Indentation and Spacing Lines

�Block Styles

Internet Programming 24© Umair Babar. PUCIT, Lahore.

Muh

ammad

Has

san R

iaz Y

ousu

fi

Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN

Page 36: Programming Fundamentals

3/6/2013

7

Appropriate Comments� Include a summary at the beginning of the program to

explain what the program does, its key features, itssupporting data structures, and any unique techniques ituses.

� Include your name, class section, instruction, date, and abrief description at the beginning of the program.

Internet Programming 25© Umair Babar. PUCIT, Lahore.

Naming Conventions� Choose meaning and descriptive names.

� Variables and method names:

� Use lowercase. If the name consists of several words,concatenate all in one, use lowercase for the firstword, and capitalize the first letter of eachsubsequent word in the name.

Internet Programming 26© Umair Babar. PUCIT, Lahore.

Naming Conventions (cont…)

� Constants

� Capitalize all letters in constants.

� For example, the constant PI.

Internet Programming 27© Umair Babar. PUCIT, Lahore.

Proper Indentation and Spacing

� Indentation

� Indent two spaces.

� Spacing

� Use blank line to separate segments of the code.

Internet Programming 28© Umair Babar. PUCIT, Lahore.

Muh

ammad

Has

san R

iaz Y

ousu

fi

Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN

Page 37: Programming Fundamentals

3/6/2013

8

Block Styles

� Use next-line style for braces.

Internet Programming 29© Umair Babar. PUCIT, Lahore.

Programming Errors� Syntax Errors

� Detected by the compiler

� Runtime Errors

� Causes the program to abort

� Logic Errors

� Produces incorrect result

Internet Programming 30© Umair Babar. PUCIT, Lahore.

Tokens� The smallest element in the C/C++ language is the

token.

� It may be a single character or a sequence of characters to form a single item.

Programming Fundamentals 31© Umair Babar. PUCIT, Lahore.

Tokens are:� Tokens can be:

� Numeric constants

� Character constants

� String constants

� Keywords

� Names (identifiers)

� Punctuation

� Operators

Programming Fundamentals 32© Umair Babar. PUCIT, Lahore.

Muh

ammad

Has

san R

iaz Y

ousu

fi

Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN

Page 38: Programming Fundamentals

3/6/2013

9

Numeric Constants� Numeric constants are an uninterrupted sequence of

digits (and may contain a period). They never contain a comma.

� Examples

� 123

� 98.6

� 1000000

Programming Fundamentals 33© Umair Babar. PUCIT, Lahore.

Character Constants� Singular!

� One character defined character set.

� Surrounded on the single quotation mark.

� Examples

� ‘A’

� ‘a’

� ‘$’

� ‘4’

Programming Fundamentals 34© Umair Babar. PUCIT, Lahore.

String Constants� A sequence characters surrounded by double

quotation marks.

� Considered a single item.

� Examples

� “PUCIT”

� “I like ice cream.”

� “I LOVE FRUIT CHAAT ☺”

� “CAR”

� “car”

Programming Fundamentals 35© Umair Babar. PUCIT, Lahore.

Keywords� Sometimes called reserved words.

� Are defined as a part of the language.

� Can not be used for anything else!

� Examples

� int

� while

� for

� void

� return

Programming Fundamentals 36© Umair Babar. PUCIT, Lahore.

Muh

ammad

Has

san R

iaz Y

ousu

fi

Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN

Page 39: Programming Fundamentals

3/6/2013

10

Names� Sometimes called identifiers or labels.

� Can be of anything length, but on the first 31 are significant (too long is as bad as too short).

� Are case sensitive:� abc is different from ABC

� Must begin with a letter and the rest can be letters, digits, and underscores.

� Must follow the standards for this course!

Programming Fundamentals 37© Umair Babar. PUCIT, Lahore.

Punctuation� Semicolons, colons, commas, apostrophes, quotation

marks, braces, brackets, and parentheses.

� ;

� :

� ,

� ‘

� “

� [ ]

� { }

� ( )

Programming Fundamentals 38© Umair Babar. PUCIT, Lahore.

Operators� There are operators for:� assignments

� mathematical operations

� relational operations

� Boolean operations

� bitwise operations

� shifting values

Programming Fundamentals 39© Umair Babar. PUCIT, Lahore.

� calling functions

� subscripting

� obtaining the size of an object

� obtaining the address of an object

� referencing an object through its address

� choosing between alternate subexpressions

The End

Questions?

Programming Fundamentals 40© Umair Babar. PUCIT, Lahore.

Muh

ammad

Has

san R

iaz Y

ousu

fi

Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN

Page 40: Programming Fundamentals

07 - HISTORY AND INTRODUCTION TO C CPP

Muh

ammad

Has

san R

iaz Y

ousu

fi

Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN

Page 41: Programming Fundamentals

Programming Fundamentals History and Introduction to C/C++

P a g e | 1 ©Umair Babar, PUCIT. Lahore.

INTRODUCTION TO C/C++ PROGRAMMING

Why use C?

C has been used successfully for every type of programming problem imaginable from operating systems to

spreadsheets to expert systems - and efficient compilers are available for machines ranging in power from the

Apple Macintosh to the Cray supercomputers. The largest measure of C's success seems to be based on purely

practical considerations:

• The portability of the compiler;

• The standard library concept;

• A powerful and varied repertoire of operators;

• An elegant syntax;

• Ready access to the hardware when needed;

• The ease with which applications can be optimized by hand-coding isolated procedures

C is often called a "Middle Level" programming language. This is not a reflection on its lack of programming power

but more a reflection on its capability to access the system's low level functions. Most high-level languages (e.g.

Fortran) provides everything the programmer might want to do already built into the language. A low level

language (e.g. assembler) provides nothing other than access to the machines basic instruction set. A middle level

language, such as C, probably doesn't supply all the constructs found in high-languages - but it provides you with

all the building blocks that you will need to produce the results you want!

Uses of C

C was initially used for system development work, in particular the programs that make-up the operating system.

Why use C? Mainly because it produces code that runs nearly as fast as code written in assembly language. Some

examples of the use of C might be:

• Operating Systems

• Language Compilers

• Assemblers

• Text Editors

• Print Spoolers

• Network Drivers

• Modern Programs

• Data Bases

• Language Interpreters

• Utilities

In recent years C has been used as a general-purpose language because of its popularity with programmers. It is

not the world's easiest language to learn and you will certainly benefit if you are not learning C as your first

programming language! C is trendy- many well established programmers are switching to C for all sorts of reasons,

but mainly because of the portability that writing standard C programs can offer.

A Brief History of C

C is a general-purpose language which has been closely associated with the UNIX operating system for which it was

developed - since the system and most of the programs that run it are written in C.

Many of the important ideas of C stem from the language BCPL, developed by Martin Richards. The influence of

BCPL on C proceeded indirectly through the language B, which was written by Ken Thompson in 1970 at Bell Labs, Muh

ammad

Has

san R

iaz Y

ousu

fi

Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN

Page 42: Programming Fundamentals

Programming Fundamentals History and Introduction to C/C++

P a g e | 2 ©Umair Babar, PUCIT. Lahore.

for the first UNIX system on a DEC PDP-7. BCPL and B are "type less" languages whereas C provides a variety of

data types.

In 1972 Dennis Ritchie at Bell Labs writes C and in 1978 the publication of The C Programming Language by

Kernighan & Ritchie caused a revolution in the computing world.

In 1983, the American National Standards Institute (ANSI) established a committee to provide a modern,

comprehensive definition of C. The resulting definition, the ANSI standard, or "ANSI C", was completed late 1988.

C for Personal Computers

With regards to personal computers Microsoft C for IBM (or clones) PC's. and Borlands C are seen to be the two

most commonly used systems. However, the latest version of Microsoft C is now considered to be the most

powerful and efficient C compiler for personal computers.

RUNNING C PROGRAMS

The Edit-Compile-Link-Execute Process

Developing a program in a compiled language such as C requires at least four steps:

1. Editing (or writing) the program

2. Compiling it

3. Linking it

4. Executing it

Editing

You write a computer program with words and symbols that are understandable to human beings. This is the

editing part of the development cycle. You type the program directly into a window on the screen and save the

resulting text as a separate file. This is often referred to as the source file. The custom is that the text of a program

is stored in a file with the extension .c and .cpp for programming language c and c++ respectively.

Compiling

You cannot directly execute the source file. To run on any computer system, the source file must be translated into

binary numbers understandable to the computer's Central Processing Unit. This process produces an intermediate

object file - with the extension .obj, the .obj stands for Object.

Linking

The first question that comes to most peoples minds is Why is linking necessary? The main reason is that many

compiled languages come with library routines which can be added to your program. Theses routines are written

by the manufacturer of the compiler to perform a variety of tasks, from input/output to complicated mathematical

functions. In the case of C the standard input and output functions are contained in a library (stdio.h) so even the

most basic program will require a library function on the other hand C++ standard input and output functions are

contained in a library (iostream.h). After linking the file extension is .exe which is an executable file.

Executable Files

Thus the text editor produces .c or .cpp source files, which go to the compiler, which produces .obj object files,

which go to the linker, which produces .exe executable file. You can then run .exe files as you can other

applications, simply by typing their names at the DOS prompt or run using windows menu.

Muh

ammad

Has

san R

iaz Y

ousu

fi

Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN

Page 43: Programming Fundamentals

Programming Fundamentals History and Introduction to C/C++

P a g e | 3 ©Umair Babar, PUCIT. Lahore.

Using Microsoft Visual C++

Edit stage

Type program in using one of the C++ editing windows.

Compile and link

Select Build Solution from Build menu. Build Solution option allows you to both compile and link in the same

option.

Execute

Use the Debug menu and select Start Without Debugging option.

Errors

If you get an error message, or you find that the program doesn't work when you finally run it (at least not in the

way you anticipated) you will have to go back to the source file - the .c or .cpp file - to make changes and go

through the whole development process again!

STRUCTURE OF C/C++ PROGRAM

Character Set

C/C++ does not use, nor requires the use of, every character found on a modern computer keyboard. The only

characters required by the C Programming Language are as follows:

• A - Z • a -z • 0 - 9 • space . , : ; ' $ " • # % & ! _ {} [] () < > | • + - / * =

The form of a Program

All programs will consist of at least one function, but it is usual to write a C/C++ program that comprises several

functions. The only function that has to be present is the function called main. For more advanced programs the

main function will act as a controlling function calling other functions in their turn to do the dirty work! The main

function is the first function that is called when your program executes.

C/C++ makes use of only 32 keywords in common (C++ have more) which combine with the formal syntax to the

form the C programming language. Note that all keywords are written in lower case - C, like UNIX, uses upper and

lowercase text to mean different things. If you are not sure what to use then always use lowercase text in writing

your C/C++ programs. A keyword may not be used for any other purposes. For example, you cannot have a

variable called auto.

Reserved Keywords

auto const double float int short s truct unsigned break continue else for long signed s witch void case default enum goto register sizeof t ypedef volatile char do extern if return static u nion while

Muh

ammad

Has

san R

iaz Y

ousu

fi

Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN

Page 44: Programming Fundamentals

Programming Fundamentals History and Introduction to C/C++

P a g e | 4 ©Umair Babar, PUCIT. Lahore.

The layout of C/C++ Programs

The general form of a C/C++ program is as follows:

pre-processor directives

global declarations

main()

{

local variables to function main ;

statements associated with function main ;

}

function1()

{

local variables to function 1 ;

statements associated with function 1 ;

}

function2()

{

local variables to function f2 ;

statements associated with function 2 ;

}

.

.

.

Etc

Note the use of the bracket set () and {} . () are used in conjunction with function names whereas {} are used

as to delimit the C/C++ statements that are associated with that function. Also note the semicolon - yes it is there,

but you might have missed it! a semicolon (;) is used to terminate C/C++ statements. C is a free format language

and long statements can be continued, without truncation, onto the next line. The semicolon informs the compiler

that the end of the statement has been reached. Free format also means that you can add as many spaces as you

like to improve the look of your programs.

A very common mistake made by everyone, who is new to the C programming language, is to miss off the

semicolon. The compiler will concatenate the various lines of the program together and then tries to understand

them - which it will not be able to do. The error message produced by the compiler will relate to a line of your

program which could be some distance from the initial mistake.

Pre-processor Directives

C/C++ provides the programmer with all the tools to be able to write powerful programs. Some people don't like

C/C++ because it is too primitive! Look again at the set of keywords that comprises the language and see if you can

find a command that allows you to print to the computer's screen the result of, say, a simple calculation. Don't

look too hard because it doesn't exist.

It would be very tedious, for all of us, if every time we wanted to communicate with the computer we all had to

write our own output functions. Fortunately, we do not have to. C/C++ uses libraries of standard functions which

are included when we build our programs. For the novice programmer one of the many questions always asked is

does a function already exist for what I want to do?

Muh

ammad

Has

san R

iaz Y

ousu

fi

Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN

Page 45: Programming Fundamentals

Programming Fundamentals History and Introduction to C/C++

P a g e | 5 ©Umair Babar, PUCIT. Lahore.

All programs you will write will need to communicate to the outside world - I don't think I can think of a program

that doesn't need to tell someone an answer. So all our programs will need at least one of C/C++’s standard

libraries which deals with standard inputting and outputting of data. This library is called stdio.h in C and

iostream.h in C++ and it is declared in our programs before the main function. The .h extension indicates that this

is a header file.

C is a free format language and that you can layout your programs how you want to use as much white space as

you like. The only exceptions are statements associated with the pre-processor.

All pre-processor directives begin with a # and the must start in the first column. The commonest directive to all

C/C++ programs is:

#include <stdio.h> #include <iostream.h>

Note the use of the angle brackets (< and >) around the header's name. These indicate that the header file is to be

looked for on the system disk which stores the rest of the program application. Some text books will show the

above statement as follows:

#include "stdio.h" #include “iostream.h ” The double quotes indicate that the current working directory should be searched for the required header file. This

will be true when you write your own header files but the standard header files should always have the angle

brackets around them.

Pre-processor statements, such as include, DO NOT use semi-colons as delimiters! But don't forget the # must be in

the first column.

FIRST PROGRAM

It's time for you to write your very own first C/C++ program. You can probably guess what it's going to be - the

program that everyone writes just to check they understand the very, very, very basics of what is going on in a new

language.

Yes - it's the ubiquitous "Hello World" program. All your first program is going to do is print the message "Hello

World" on the screen.

The program is a short one, to say the least. Here it is:

#include <iostream.h> using namespace std;

void main() { cout<< ”Hello World ”; }

The first line is the standard start for all C/C++ programs - main() . After this comes the program's only instruction

enclosed in curly brackets {} . The curly brackets mark the start and end of the list of instructions that make up the

program - in this case just one instruction.

Notice the semicolon marking the end of the instruction. You might as well get into the habit of ending every

instruction with a semicolon - it will save you a lot of trouble! Also notice that the semicolon marks the end of an

instruction - it isn't a separator as is the custom in other languages. Muh

ammad

Has

san R

iaz Y

ousu

fi

Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN

Page 46: Programming Fundamentals

Programming Fundamentals History and Introduction to C/C++

P a g e | 6 ©Umair Babar, PUCIT. Lahore.

If you're puzzled about why the curly brackets are on separate lines, so doesn’t panic it's just a layout convention

to help you spot matching brackets. C/C++ is very modest about the way you lay it out. For example, you could

enter the Hello World program as:

void main(){cout<< “Hello World\n”;}

But this is unusual.

The cout operator does what its name suggest it does: it prints, on the screen, whatever you tell it to. The "\n" is a

special symbol that forces a new line on the screen.

Type it in and save it as Hello.cpp. Then use the compiler to compile it, then the linker to link it and finally run it.

The output is as follows:

Hello World

Add Comments to a Program

A comment is a note to yourself (or others) that you put into your source code. All comments are ignored by the

compiler. They exist solely for your benefit. Comments are used primarily to document the meaning and purpose

of your source code, so that you can remember later how it functions and how to use it. You can also use a

comment to temporarily remove a line of code. Simply surround the line(s) with the comment symbols.

In C/C++, the start of a comment is signaled by the /* character pair. A comment is ended by */. For example, this

is a syntactically correct C/C++ comment:

/* This is a comment. */

Comments can extend over several lines and can go anywhere except in the middle of any keyword, function name

or variable name. In C/C++ you can't have one comment within another comment. That is comments may not be

nested. Let’s now look at our first program one last time but this time with comments:

/* main function heading */ void main() { // Display message on the screen cout<< ”Hello World\n ”; }

This program is not large enough to warrant comment statements but the principle is still the same.

Muh

ammad

Has

san R

iaz Y

ousu

fi

Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN

Page 47: Programming Fundamentals

08 - COMPILER TERMINOLOGY

Muh

ammad

Has

san R

iaz Y

ousu

fi

Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN

Page 48: Programming Fundamentals

Programming Fundamentals Compiler Terminology

P a g e | 1 ©Umair Babar, PUCIT. Lahore.

COMPILER TERMINOLOGY

C is a compiled language. This means that the programs you write are translated, by a program called a compiler, into executable machine-language programs which you can actually run. Executable machine-language programs are self-contained and run very quickly. Since they are self-contained, you don't need copies of the source code (the original programming-language text you composed) or the compiler in order to run them; you can distribute copies of just the executable and that's all someone else needs to run it. Since they run relatively quickly, they are appropriate for programs which will be written once and run many times.

A compiler is a special kind of program: it is a program that builds other programs. What happens is that you invoke the compiler (as a program), and it reads the programming language statements that you have written and turns them into a new, executable program. When the compiler has finished its work, you then invoke your program (the one the compiler just built) to see if it works.

The main alternative to a compiled computer language or program is an interpreted one, such as BASIC. An interpreted language is interpreted (by, not surprisingly, a program called an interpreter) and its actions performed immediately. If you gave a copy of an interpreted program to someone else, they would also need a copy of the interpreter to run it. No standalone executable machine-language binary program is produced.

In other words, for each statement that you write, a compiler translates into a sequence of machine language instructions which does the same thing, while an interpreter simply does it (where ``it'' is whatever the statement that you wrote is supposed to do).

The big advantage of an interpreted language is that your program runs right away; you don't have to perform--and wait for--the separate tasks of compiling and then running your program. (Actually, on a modern computer, neither compiling nor interpreting takes much time, so some of these distinctions become less important.)

Actually, whether a language is compiled or interpreted is not always an inherent part of the language. There are interpreters for C, and there are compilers for BASIC. However, most languages were designed with one or the other mechanism in mind, and there are usually a few difficulties when trying to compile a language which is traditionally interpreted, or vice versa.

The distinction between compilation and interpretation, while it is very significant and can make a big difference, is not one to get worked up over. Most of the time, once you get used to the details of how you get your programs to run, you don't need to worry about the distinction too much. But it is a useful distinction to have a basic understanding of, and to keep in the back of your mind, because it will help you understand why certain aspects of computer programming (and particular languages) work the way they do.

When you're working with a compiled language, there are several mechanical details which you'll want to be aware of. You create one or more source files which are simple text files containing your program, written in whatever language you're using. You typically use a text editor to work with source files (typically you don't want to use a full-fledged word processor, since the compiler won't understand its formatting codes). You supply each source file (you may have one or more than one) to the compiler, which creates an object file containing machine-language instructions corresponding to your program. Your program is not ready to run yet, however: if you called any functions which you didn't write (such as the standard library functions provided as part of a programming language environment), you must arrange for them to be inserted into your program, too. The task of combining object files together, while M

uham

mad H

assa

n Riaz

You

sufi

Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN

Page 49: Programming Fundamentals

Programming Fundamentals Compiler Terminology

P a g e | 2 ©Umair Babar, PUCIT. Lahore.

also locating and inserting any library functions, is the job of the linker. The linker puts together the object files you give it, noticing if you call any functions which you haven't supplied and which must therefore be library functions. It then searches one or more library files (a library file is simply a collection of object files) looking for definitions of the still-unresolved functions, and pulls in any that it finds. When it's done, it either builds the final, executable file, or, if there were any errors (such as a function called but not defined anywhere) complains.

If you're using some kind of an integrated programming environment, many of these steps may be taken care of for you so automatically and seamlessly that you're hardly aware of them.

Typical Phases of Compiler

High Level View

The C source cod that you write is converted to object code by the compiler and then to an executable file by the linker.

Use Editor

Source

Code

Compile Source

File

Object

Code

Link Object File Library Files Executable

Program

Muh

ammad

Has

san R

iaz Y

ousu

fi

Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN

Page 50: Programming Fundamentals

Programming Fundamentals Compiler Terminology

P a g e | 3 ©Umair Babar, PUCIT. Lahore.

Steps Involved in C Program Development

Begin

Edit Source Code

Compiler Source Code

Any Errors?

Link Program

Any Errors?

Execute Program

Any Errors?

End

YES

YES

YES

NO

NO

NO

Muh

ammad

Has

san R

iaz Y

ousu

fi

Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN

Page 51: Programming Fundamentals

Programming Fundamentals Compiler Terminology

P a g e | 4 ©Umair Babar, PUCIT. Lahore.

Low Level View

(Wikipedia)

Home Work

1. What do you mean by compiler?

2. What is the purpose of library file?

3. What is the role of linker?

4. What is the difference between Syntax and Semantic?

5. What is the difference between Lexical Analyzer and Parser?

6. Differentiate among source, intermediate and machine code.

Muh

ammad

Has

san R

iaz Y

ousu

fi

Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN

Page 52: Programming Fundamentals

09 - DATA TYPES AND VARIABLES

Muh

ammad

Has

san R

iaz Y

ousu

fi

Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN

Page 53: Programming Fundamentals

3/11/2013

1

Umair Babar

[email protected]

Punjab University College of Information Technology.

University of the Punjab, Lahore.

What Are Variables in C?� Variables in C & C++ have the same meaning as variables

in algebra.

� They represent some unknown, or variable, value.

� x = a + b

� z + 2 = 3(y - 5)

� Remember that variables in algebra are represented by a single alphabetic character.

Programming Fundamentals 2© Umair Babar. PUCIT, Lahore.

Naming Variables� Variables in C & C++ may be given representations

containing multiple characters. But there are rules for these representations.

� Variable names in C & C++

� May only consist of letters, digits, and underscores

� May be as long as you like, but only the first 31 characters are significant

� May not begin with a number

� May not be a C/C++ reserved word (keyword)

Programming Fundamentals 3© Umair Babar. PUCIT, Lahore.

Reserved Words (Keywords) in C� auto break

� case char

� const continue

� default do

� double else

� enum extern

� float for

� goto if

int longregister returnshort signedsizeof staticstruct switchtypedef unionunsigned voidvolatile while

Programming Fundamentals 4© Umair Babar. PUCIT, Lahore.

Muh

ammad

Has

san R

iaz Y

ousu

fi

Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN

Page 54: Programming Fundamentals

3/11/2013

2

Naming Conventions� C/C++ programmers generally agree on the following

conventions for naming variables.

� Begin variable names with lowercase letters

� Use meaningful identifiers

� Separate “words” within identifiers with underscores or mixed upper and lower case.

� Examples:

� surfaceArea

� surface_Area

� surface_area

� Be consistent!Programming Fundamentals 5© Umair Babar. PUCIT, Lahore.

Naming Conventions (con’t)� Use all uppercase for symbolic constants.

� Used in #define preprocessor directives.

� Examples:

#define PI 3.14159

#define AGE 52

Programming Fundamentals 6© Umair Babar. PUCIT, Lahore.

Case Sensitivity� C & C++ are case sensitive

� It matters whether an identifier, such as a variable name, is uppercase or lowercase.

� Example:

� Area

� area

� AREA

� ArEa

are all seen as different variables by the compiler.

Programming Fundamentals 7© Umair Babar. PUCIT, Lahore.

Which Are Legal Identifiers?AREA area_under_the_curve int

3D num45 float

Last-Chance #values catch

x_yt3 pi void

num$ %done main

lucky*** string define

Programming Fundamentals 8© Umair Babar. PUCIT, Lahore.

Muh

ammad

Has

san R

iaz Y

ousu

fi

Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN

Page 55: Programming Fundamentals

3/11/2013

3

Data TypesType Length Range

unsigned char 8 bits 0 to 255

char 8 bits -128 to 127

enum 16 bits -32,768 to 32, 767

unsigned int 16 bits 0 to 65, 535

short int 16 bits -32,768 to 32,767

int 16 bits -32,768 to 32,767

unsigned long 32 bits 0 to 4,294,967,295

long 32 bits -2,147,483,648 to 2,147,483,647

float 32 bits 3.4 * (10**-38) to 3.4 * (10**+38)

double 64 bits 1.7 * (10**-308) to 1.7 * (10**+308)

long double 80 bits 3.4 * (10**-4932) to 1.1 * (10**+4932)

Programming Fundamentals © Umair Babar. PUCIT, Lahore. 9

Declaring Variables� Before using a variable, you must give the compiler

some information about the variable

� You must declare it.

� The declaration statement includes the data type of the variable.

� Examples of variable declarations:

� int meatballs ;

� float area ;

Programming Fundamentals 10© Umair Babar. PUCIT, Lahore.

Declaring Variables (con’t)�When we declare a variable

� Space is set aside in memory to hold a value of the specified data type.

� That space is associated with the variable name.

� That space is associated with a unique address.

� Visualization of the declaration

int meatballs ; meatballs

FE07

garbage

Programming Fundamentals 11© Umair Babar. PUCIT, Lahore.

More About Variables� C/C++ has three basic predefined data types:

� Integers (whole numbers)

� int, long, short, unsigned int

� Floating point (real numbers)

� float, double

� Characters

� char

Programming Fundamentals 12© Umair Babar. PUCIT, Lahore.

Muh

ammad

Has

san R

iaz Y

ousu

fi

Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN

Page 56: Programming Fundamentals

3/11/2013

4

Using Variables: Initialization� Variables may be be given initial values, or initialized,

when declared.

� Examples:

int length = 7 ;

float diameter = 5.9 ;

char initial = ‘A’ ;

7

5.9

‘A’

length

diameter

initial

Programming Fundamentals 13© Umair Babar. PUCIT, Lahore.

Using Variables: Initialization (con’t)� Do not “hide” the initialization

� put initialized variables on a separate line

� a comment is always a good idea

� Example:

int height ; /* rectangle height */

int width = 6 ; /* rectangle width */

int area ; /* rectangle area */

Programming Fundamentals 14© Umair Babar. PUCIT, Lahore.

Using Variables: Assignment� Variables may have values assigned to them through the

use of an assignment statement.

� Such a statement uses the assignment operator =

� This operator does not denote equality. It assigns the value of the righthand side of the statement (the expression) to the variable on the lefthand side.

� Examples:

diameter = 5.9 ;

area = length * width ;

Note that only single variables may appear on the lefthand side of the assignment operator.

Programming Fundamentals 15© Umair Babar. PUCIT, Lahore.

Example: Declarations and Assignments

int main( ){

int inches, feet, fathoms ;

fathoms = 7 ; feet = 6 * fathoms ;inches = 12 * feet ;�

inches

feet

fathoms

garbage

fathoms

7

garbagefeet

42

garbage

504

inches

Programming Fundamentals 16© Umair Babar. PUCIT, Lahore.

Muh

ammad

Has

san R

iaz Y

ousu

fi

Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN

Page 57: Programming Fundamentals

3/11/2013

5

Example: Declarations and Assignments�

cout<< “Its depth at sea: \n” ;cout<<“Fathoms = ”<< fathoms ;cout<<“Feet = ”<< feet ;cout<<“Inches = ”<<inches ;

return 0 ;}

Programming Fundamentals 17© Umair Babar. PUCIT, Lahore.

Enhancing Our Example�What if the depth were really 5.75 fathoms?

� Our program, as it is, couldn’t handle it.

� Unlike integers, floating point numbers can contain decimal portions.

� Let’s use floating point, rather than integer.

� Let’s also ask the user to enter the number of fathoms, rather than “hard-coding” it in.

Programming Fundamentals 18© Umair Babar. PUCIT, Lahore.

Enhanced Program

int main ( ){

float inches, feet, fathoms ;

cout<<“Enter the depth in fathoms : ” ;cin>>fathoms ;feet = 6 * fathoms ;inches = 12 * feet ; cout<<“Its depth at sea: \n” ;cout<<“Fathoms = ”<< fathoms ;cout<<“Feet = ”<< feet ;cout<<“Inches = ”, inches) ;return 0 ;

} Programming Fundamentals 19© Umair Babar. PUCIT, Lahore.

Final “Clean” Program

int main( ){

float inches ; /* number of inches deep */float feet ; /* number of feet deep */float fathoms ; /* number of fathoms deep */

/* Get the depth in fathoms from the user */

cout<<“Enter the depth in fathoms : ” ;cin>>fathoms;

/* Convert the depth to inches */

feet = 6 * fathoms ;inches = 12 * feet ;

Programming Fundamentals 20© Umair Babar. PUCIT, Lahore.

Muh

ammad

Has

san R

iaz Y

ousu

fi

Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN

Page 58: Programming Fundamentals

3/11/2013

6

Final “Clean” Program (con’t)

/* Display the results */

cout<<“Its depth at sea: \n” ;cout<<“Fathoms = ”<< fathoms) ;cout<<“Feet = ”, Feet);cout<<“Inches = ”, inches);

return 0 ;}

Programming Fundamentals 21© Umair Babar. PUCIT, Lahore.

Good Programming Practices� Place each variable declaration on its own line with a

descriptive comment.

� Place a comment before each logical “chunk” of code describing what it does.

� Do not place a comment on the same line as code (with the exception of variable declarations).

� Use spaces around all arithmetic and assignment operators.

� Use blank lines to enhance readability.

Programming Fundamentals 22© Umair Babar. PUCIT, Lahore.

Good Programming Practices (con’t)� Place a blank line between the last variable declaration

and the first executable statement of the program.

� Indent the body of the program 3 to 4 tab stops -- be consistent!

Programming Fundamentals 23© Umair Babar. PUCIT, Lahore.

The End

Questions?

Programming Fundamentals 24© Umair Babar. PUCIT, Lahore.

Muh

ammad

Has

san R

iaz Y

ousu

fi

Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN

Page 59: Programming Fundamentals

10 - DATA TYPES, VARIABLES AND OPERATORS

Muh

ammad

Has

san R

iaz Y

ousu

fi

Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN

Page 60: Programming Fundamentals

Programming Fundamentals Data Types, Variables and Operators

Umair Babar, PUCIT – PU. Lahore. Page 1 of 5

DATA TYPES, VARIABLES AND OPERATORS

You can create variables to store values in. A variable is just a named area of storage that can hold a single value (numeric or

character). C is very fussy about how you create variables and what you store in them. It demands that you declare the name of

each variable that you are going to use and its type, or class, before you actually try to do anything with it.

In this section we are only going to be discussing local variables. These are variables that are used within the current program unit

(or function) in a later section we will look at global variables - variables that are available to all the program's functions.

There are five basic data types associated with variables:

• int - integer: a whole number.

• float - floating point value: a number with a fractional part.

• double - a double-precision floating point value.

• char - a single character.

• void - valueless special purpose type.

One of the confusing things about the C language is that the range of values and the amount of storage that each of these types

takes is not defined. This is because in each case the 'natural' choice is made for each type of machine. You can call variables what

you like, although it helps if you give them sensible names that give you a hint of what they're being used for - names like sum,

total, average and so on. C programmers tend to prefer short names!

Note: all C's variables must begin with a letter or a "_" (underscore) character.

Integer Number Variables

The first type of variable we need to know about is of class type int - short for integer. An int variable can store a value in the

range -32768 to +32767. You can think of it as a largish positive or negative whole number: no fractional part is allowed. To

declare an int you use the instruction:

int variable name;

For example:

int a; declares that you want to create an int variable called a.

To assign a value to our integer variable we would use the following C statement:

a = 10;

The C programming language uses the "=" character for assignment. A statement of the form a=10; should be interpreted as take

the numerical value 10 and store it in a memory location associated with the integer variable a. The "=" character should not be

seen as an equality otherwise writing statements of the form:

a = a + 10;

will get mathematicians blowing fuses! This statement should be interpreted as take the current value stored in a memory location

associated with the integer variable a; add the numerical value 10 to it and then replace this value in the memory location

associated with a.

Decimal Number Variables

As described above, an integer variable has no fractional part. Integer variables tend to be used for counting, whereas real

numbers are used in arithmetic. C uses one of two keywords to declare a variable that is to be associated with a decimal number:

float and double. They are each offer a different level of precision as outlined below.

float

A float, or floating point, number has about seven digits of precision and a range of about 1.E-36 to 1.E+36. A float takes

four bytes to store.

double

A double, or double precision, number has about 13 digits of precision and a range of about 1.E-303 to 1.E+303. A double

takes eight bytes to store.

For example:

float total;

double sum;

Muh

ammad

Has

san R

iaz Y

ousu

fi

Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN

Page 61: Programming Fundamentals

Programming Fundamentals Data Types, Variables and Operators

Umair Babar, PUCIT – PU. Lahore. Page 2 of 5

To assign a numerical value to our floating point and double precision variables we would use the following C statement:

total = 0.0;

sum = 12.50;

Character Variables

C only has a concept of numbers and characters. It very often comes as a surprise to some programmers who learnt a beginner's

language such as BASIC that C has no understanding of strings but a string is only an array of characters and C does have a concept

of arrays.

To declare a variable of type character we use the keyword char. - A single character stored in one byte.

For example:

char c;

To assign, or store, a character value in a char data type is easy - a character variable is just a symbol enclosed by single quotes.

For example, if c is a char variable you can store the letter A in it using the following C statement:

c='A'

Notice that you can only store a single character in a char variable. Later we will be discussing using character strings, which has a

very real potential for confusion because a string constant is written between double quotes. But for the moment remember that

a char variable is 'A' and not "A".

Assignment Statement

Once you've declared a variable you can use it, but not until it has been declared - attempts to use a variable that has not been

defined will cause a compiler error. Using a variable means storing something in it. You can store a value in a variable using:

name = value;

For example:

a = 10;

stores the value 10 in the int variable a. What could be simpler? Not much, but it isn't actually very useful! Who wants to store a

known value like 10 in a variable so you can use it later? It is 10, always was 10 and always will be 10. What makes variables useful

is that you can use them to store the result of some arithmetic.

Consider four very simple mathematical operations: add, subtract, multiply and divide. Let us see how C would use these

operations on two float variables a and b.

add

a + b

subtract

a – b

multiply

a * b

divide

a / b

Note that we have used the following characters from C's character set:

+ for addition

- for subtract

* for multiply

/ for divide

BE CAREFUL WITH ARITHMETIC!!! What is the answer to this simple calculation?

a = 10/3

The answer depends upon how a was declared. If it was declared as type int the answer will be 3; if a is of type float then the

answer will be 3.333. It is left as an exercise to the reader to find out the answer for a of type char.

Two points to note from the above calculation:

1. C ignores fractions when doing integer division!

2. When doing float calculations integers will be converted into float.

Muh

ammad

Has

san R

iaz Y

ousu

fi

Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN

Page 62: Programming Fundamentals

Programming Fundamentals Data Types, Variables and Operators

Umair Babar, PUCIT – PU. Lahore. Page 3 of 5

Arithmetic Ordering

Whilst we are dealing with arithmetic we want to remind you about something that everyone learns at junior school but then we

forget it. Consider the following calculation:

a = 10.0 + 2.0 * 5.0 - 6.0 / 2.0

What is the answer? If you think its 27 go to the bottom of the class! Perhaps you got that answer by following each instruction as

if it was being typed into a calculator. A computer doesn't work like that and it has its own set of rules when performing an

arithmetic calculation. All mathematical operations form a hierarchy which is shown here.

Character Set, Arithmetic, Relational & Logical Operators

The C Programming Language Character Set is as follows:

• A - Z

• a - z • 0 - 9

• (space) . , : ; ' $ " • # % & ! _ {} [] < > |

• + - / * =

The C Programming Language Arithmetic set:

• () Brackets

• ++ Increment • -- Decrements

• * Multiplication • / Division • + Addition

• - Subtraction • % Modulus

• = Assignment

The C Programming Language has the following Relational and Logical Operators:

Relational

• > Greater than

• >= Greater than or equal to • < Less than

• <= Less than or equal to • == Equal to

• != Not equal to

Logical

• && AND

• || OR • ! NOT

In the above calculation the multiplication and division parts will be evaluated first and then the addition and subtraction parts.

This gives an answer of 17.

Note: To avoid confusion use brackets. The following are two different calculations:

a = 10.0 + (2.0 * 5.0) - (6.0 / 2.0)

a = (10.0 + 2.0) * (5.0 - 6.0) / 2.0

You can freely mix int, float and double variables in expressions. In nearly all cases the lower precision values are converted to the

highest precision values used in the expression. For example, the expression f * i, where f is a float and i is an int, is evaluated by

converting the int to a float and then multiplying. The final result is, of course, a float but this may be assigned to another data

type and the conversion will be made automatically. If you assign to a lower precision type then the value is truncated and not

rounded. In other words, in nearly all cases you can ignore the problems of converting between types.

This is very reasonable but more surprising is the fact that the data type char can also be freely mixed with ints, floats and doubles.

This will shock any programmer who has used another language, as it's another example of C getting us closer than is customary

Muh

ammad

Has

san R

iaz Y

ousu

fi

Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN

Page 63: Programming Fundamentals

Programming Fundamentals Data Types, Variables and Operators

Umair Babar, PUCIT – PU. Lahore. Page 4 of 5

to the way the machine works. A character is represented as an ASCII or some other code in the range O to 255, and if you want

you can use this integer code value in arithmetic. Another way of thinking about this is that a char variable is just a single-byte

integer variable that can hold a number in the range O to 255, which can optionally be interpreted as a character. Notice,

however, that C gives you access to memory in the smallest chunks your machine works with, i.e. one byte at a time, with no

overheads.

ASCII (American Standard Code for Information Interchange)

A standard arrangement of seven binary digits (an eighth can be added as an error check) used to represent the characters to be entered into a computer,

for example from the keyboard. A semi-standardised extended 8-bit code incorporating Ascii, more commonly used today for text interchange, is often referred to as '8-bit Ascii'.

Something to Declare

Before you can use a variable you have to declare it. As we have seen above, to do this you state its type and then give its name.

For example, int i; declares an integer variable. You can declare any number of variables of the same type with a single

statement. For example:

int a, b, c;

declares three integers: a, b and c. You have to declare all the variables that you want to use at the start of the program. Later you

will discover that exactly where you declare a variable makes a difference, but for now you should put variable declarations after

the opening curly bracket of the main program.

Here is an example program that includes some of the concepts outlined above.

/*

Program int.cpp

Simple program

using int and cout

*/

# include <iostream.h>

using namespace std;

int main()

{

int a, b, average;

a=10;

b=6;

average = ( a+b ) / 2 ;

cout<<"The average of two numbers "<<a<<" and "<<b;

cout<<" is "<<average;

}

Output

More on Initialising Variables

You can assign an initial value to a variable when you declare it. For example:

int i = 1;

sets the int variable to one as soon as it's created. This is just the same as:

int i;

i = l;

But the compiler may be able to speed up the operation if you initialize the variable as part of its declaration. Don't assume that

an uninitialized variable has a sensible value stored in it. Some C compilers store 0 in newly created numeric variables but nothing

in the C language compels them to do so.

Muh

ammad

Has

san R

iaz Y

ousu

fi

Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN

Page 64: Programming Fundamentals

Programming Fundamentals Data Types, Variables and Operators

Umair Babar, PUCIT – PU. Lahore. Page 5 of 5

Summary

Variable names:

• should be lowercase for local variables

• should be UPPERCASE for symbolic constants (to be discussed later)

• only the first 31 characters of a variables name are significant

• must begin with a letter or _ (under score) character

Muh

ammad

Has

san R

iaz Y

ousu

fi

Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN