Top Banner
Dr. Aman-ur-Rehman Department of Nuclear Engineering, Pakistan Institute of Engineering and Applied Sciences, P.O. Nilore, Islamabad. Dr. Aman-ur- Rehman DNE, PIEAS COMPUTING FUNDAMENTALS
72

Computer Fundamental lecture 2

Oct 24, 2015

Download

Documents

saeedr337

How to interact with C environment
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Computer Fundamental lecture 2

Dr. Aman-ur-RehmanDepartment of Nuclear Engineering,

Pakistan Institute of Engineering and Applied Sciences,P.O. Nilore, Islamabad.

Dr. Aman-ur-Rehman DNE, PIEAS

COMPUTING FUNDAMENTALS

Page 2: Computer Fundamental lecture 2

COURSE CONTENTS

Basic components of a computer Programming languages Programming in C and its Applications

Dr. Aman-ur-Rehman DNE, PIEAS

Page 3: Computer Fundamental lecture 2

Lab Teachers1. Dr. Yousaf Hamza, PE, DPAM, PIEAS2. Dr. Naeem Akhtar, SE, DCIS, PIEAS3. Mr. Mazhar Husnain, SE, DMS, PIEAS4. Mrs. Romana Basit, SS, DChE, PIEAS5. Mr. Qaiser Nadeem, JE, DNE, PIEAS6. Mr. Muhammad Hur, JE, DEE, PIEAS7. Mr. Taskeen Ahmad, PhD Scholar, DEE, PIEAS8. Mr. Iftekhar Ahmad, PhD Scholar, DPAM, PIEAS

Dr. Aman-ur-Rehman DNE, PIEAS

Page 4: Computer Fundamental lecture 2

Purpose and Objectives

Why we need to study Computer languages?

Why we study C? What would be the use of this course?

Dr. Aman-ur-Rehman DNE, PIEAS

Page 5: Computer Fundamental lecture 2

Computer

Computer is an advanced electronic device that takes raw data as input from the user and processes these data under the control of set of instructions (called program) and gives the result (output) and saves output for the future use.

It can process both numerical and non-numerical (arithmetic and logical) calculations.

Dr. Aman-ur-Rehman DNE, PIEAS

Page 6: Computer Fundamental lecture 2

Functions of a Computerand Computer System

A Computer has four functionsaccepts data (Input)processes data (Processing)produces output (Output)stores results (Storage)

Computer System: All of the components of a computer system can be summarized with the simple equation

COMPUTER SYSTEM = HARDWARE + SOFTWARE+ USER

Hardware : All physical parts of the computer Software : Programs (Software gives "intelligence" to the computer)USER : Person, who operates computer

Dr. Aman-ur-Rehman DNE, PIEAS

Page 7: Computer Fundamental lecture 2

Components of a Computer

Dr. Aman-ur-Rehman DNE, PIEAS

INPUT

KeyboardMouseScannerCamera

Arithmetic Logic Unit (ALU)

Control Unit

Internal Memory Unit

OUTPUT

ScreenPrinterPlotterPhoto

Page 8: Computer Fundamental lecture 2

Components of a Computer The major components of the computer are the central processing

unit (CPU), main memory, secondary memory, and input and output devices.

The CPU is the heart of any computer. It is divided into a control unit, an arithmetic logic unit (ALU), and internal memory. The control unit of the CPU interprets the instructions of the computer

program and it controls all the other parts of the computer. It also fetches data values from input devices or main memory and stores them in the memory registers and sends data values from memory registers to output device or main memory.

The ALU performs the actual mathematical calculations. The internal memory within a CPU consists of a series of memory

registers used for the temporary storage of intermediate result during calculations.

Dr. Aman-ur-Rehman DNE, PIEAS

Page 9: Computer Fundamental lecture 2

Main and Secondary MemoryThe memory of a computer is divided into two

major types of memory: main or primary memory, and secondary memory.Main memory is very fast and relatively expensive.

Data stored in it can be fetched for use in less than nanosecond on a modern computer. It is not used for the permanent storage of programs. It is also volatile.

Secondary memory consists of devices that are slower and cheaper than the main memory. They can store much more information for much less money than the main memory can. Mostly it is nonvolatile.

Dr. Aman-ur-Rehman DNE, PIEAS

Page 10: Computer Fundamental lecture 2

Input and Output devicesData is entered into a computer through an input

device and is output through an output device. The most common input device on a modern

computer is a keyboard. Other types of input devices found on some computers are scanners and microphones.

Output devices permits us to use the data stored in a computer. The most common output devices on today’s computers are monitors and printers. Other types of output devices include plotters and speakers.

Dr. Aman-ur-Rehman DNE, PIEAS

Page 11: Computer Fundamental lecture 2

Computer Program

A computer program is a sequence of instructions that are executed by a CPU.

Superscalar processors are capable of executing several instructions at once.

Program flow may be influenced by special 'jump' instructions that transfer execution to an instruction other than the following one.

Dr. Aman-ur-Rehman DNE, PIEAS

Page 12: Computer Fundamental lecture 2

Computer Languages(Low Level Languages)

Low Level Languages: low-level languages are described as being “close to the hardware”.

Low-level languages can be converted to machine code without using a compiler or interpreter, and the resulting code runs directly on the processor.

A program written in a low-level language can be made to run very fast, and with a very small memory; an equivalent program in a high-level language will be more heavyweight.

Low-level languages are simple, but are considered difficult to use, due to the numerous technical details which must be remembered.

Examples are Machine Level Language and Assembly language

Dr. Aman-ur-Rehman DNE, PIEAS

Page 13: Computer Fundamental lecture 2

Machine Level Language The fundamental language of any computer is machine

language which essentially consists of zeros and ones. Every processor or processor family has its own machine

code instruction set. Instructions are patterns of bits that by physical design

correspond to different commands to the machine. The instruction set is thus specific to a class of processors

using (much) the same architecture. Writing a program using a series of zeros and ones is

extremely tedious and time consuming, so few people program in machine language.

Dr. Aman-ur-Rehman DNE, PIEAS

Page 14: Computer Fundamental lecture 2

Assembly Language To relieve the frustration of programming in machine

language, assembly language was developed. Assembly language allows the programmer to represent

machine language instructions by means of mnemonic words and symbols.

Mnemonic: For example, to remember the colours of the rainbow, use the mnemonic "Richard Of York Gave Battle In Vain"

An ‘Assembler’ is needed for conversion to machine code Although assembly language is a significant improvement over

machine language programming, it is still a low level language.

Dr. Aman-ur-Rehman DNE, PIEAS

Page 15: Computer Fundamental lecture 2

Merits and Demerits of Low Level Languages

Merits: Extremely Fast executable Best resource utilization Customized coding

Demerits: Programs are machine dependent and cannot be easily transferred from one

computer system to another. Programming is very time consuming to learn. It requires considerable experience to

become proficient Most of the program is occupied with internal details which have very little to do

with the actual task to be accomplished. Programs are difficult to alter due to their complexity. Debugging is not easy. It is very easy to introduce errors. Suitable for small programs

Dr. Aman-ur-Rehman DNE, PIEAS

Page 16: Computer Fundamental lecture 2

Computer Languages(High Level Languages)

High Level Languages: Programming languages that are closer to human (English) language are called High Level Languages (HLLs).

Machine IndependentPortableEasy to Program / Debug / Extend / ModifyCompact code (smaller no. of lines)

Dr. Aman-ur-Rehman DNE, PIEAS

Page 17: Computer Fundamental lecture 2

Computer LanguagesHigh Level Languages: The user friendly

language ...more natural language than assembly language. Complier is needed to convert high level to machine language

Dr. Aman-ur-Rehman DNE, PIEAS

COBOL (COmmon Business Oriented Language), FORTRAN (FORmulaTRANslation), BASIC (Beginner's All-purpose Symbolic Instruction Code), C, C++ etc. are the examples of High Level Language.

Page 18: Computer Fundamental lecture 2

Examples of High Level Languages

Dr. Aman-ur-Rehman DNE, PIEAS

Page 19: Computer Fundamental lecture 2

Programming Languages

Dr. Aman-ur-Rehman DNE, PIEAS

Machine Languages

Assembly Languages

High-Level Languages

+1300042774+1400593419+1200274027

LOAD AADD B

STORE C

C=A+B

Page 20: Computer Fundamental lecture 2

AssemblerInstructions written in assembly language

must be translated to machine language instructions : Assembler does this

One to one translation : One AL instruction is mapped to one ML instruction.

AL instructions are CPU specific.

Dr. Aman-ur-Rehman DNE, PIEAS

Page 21: Computer Fundamental lecture 2

CompilerInstructions written in high-level language also

must be translated to machine language instructions : Compiler does this

Generally one to many translation : One HL instruction is mapped to many ML instruction.

HL instructions are not CPU specific but compiler is.

Dr. Aman-ur-Rehman DNE, PIEAS

Page 22: Computer Fundamental lecture 2

Interpreter An interpreter translates high-level instructions into an

intermediate form, which it then executes. In contrast, a compiler translates high-level instructions directly into machine language.

Compiled programs generally run faster than interpreted programs.

The advantage of an interpreter, however, is that it does not need to go through the compilation stage during which machine instructions are generated. This process can be time-consuming if the program is long. The interpreter, on the other hand, can immediately execute high-level programs. For this reason, interpreters are sometimes used during the development of a program, when a programmer wants to add small sections at a time and test them quickly.

Dr. Aman-ur-Rehman DNE, PIEAS

Page 23: Computer Fundamental lecture 2

Creating Programs

Dr. Aman-ur-Rehman DNE, PIEAS

hello.ocompile hellohello.c

C libaray

Link

Source File

(High-Level Languages)

Object File

(Machine Languages)

Edit

Page 24: Computer Fundamental lecture 2

Language Concepts Fortran, C, C++ Compiled languages i.e., source code is created with an editor as a

plain text file. Programs then needs to be “compiled” (converted from source code

to machine instructions with relative addresses and undefined external routines still needed).

External routines are those needed to do such operations as read data files, write to the screen, read the keyboard strokes etc.)

The compiled routines (called object modules) need then to be linked or loaded.

Linking creates an executable with relative addresses resolved and external routine loaded from the system and user libraries.

The executable can then, in most cases, be run on any machine with the same architecture.

Compiling and linking can be done in one user step.

Dr. Aman-ur-Rehman DNE, PIEAS

Page 25: Computer Fundamental lecture 2

History of C LanguageDeveloped in early 1970s by Dennis Ritchie C evolved from a language named B developed by

Ken ThomsonDennis Ritchie developed C to overcome some of the

shortcomings of B. He salvaged some of the best features of B, added a number of significant features such as data types and classes, and removed many of the hardware dependent aspects

Dr. Aman-ur-Rehman DNE, PIEAS

Page 26: Computer Fundamental lecture 2

Philosophy of C Language Although C was originally designed as a systems programming

language to be used with UNIX operating system, it soon proved to be a powerful general purpose programming language

It has become a programming language of choice for most professional programmers and its popularity has increased steadily since its creation.

C is already a dominant language on minicomputers and workstations running the Unix operating system

C is also a popular language on personal computers A knowledge of C programming is also essential for developing

applications under many of the newer graphical windowing environments

Dr. Aman-ur-Rehman DNE, PIEAS

Page 27: Computer Fundamental lecture 2

Advantages of C Language Reusability: Programs written in C can be reused. You can save your C programs into a

library file and invoke them in your next programming project simply by including the library file

Readability: C Programs are easy to read Maintainability: C Programs are easy to maintain Portability: C Programs are portable across different computer platforms by just

recompile them according to the relative operating systems Learnability : You don’t have to remember many C keywords or commands before you

start to write programming in C Major parts of popular operating systems like Windows, UNIX, Linux is still written in C Many other high-level languages have been developed based on C. Example, Perl is a

very popular programming language in World Wide Web (WWW) design across the Internet. Perl actually borrows a lot of features from C

If you understand C, learning Perl or PHP is a snap. Another example is the C++ language, which is simply an expanded version of C, although C++ makes object-oriented programming easier. Also, learning Java becomes much easier if you already know C

Dr. Aman-ur-Rehman DNE, PIEAS

Page 28: Computer Fundamental lecture 2

Disadvantages of C LanguageSince C is free-form language and does not impose

strict style rules, C program can be difficult to understand if the programmer has not made the effort to make the program readable.

C does not have array bound checking. Thus it is responsibility of the programmer to make sure that all array references are within the limits of the array.

Invalid pointers can result in system crash.One has to be careful while using some symbols. For

example * and = (x*y and *x similarly x=y and x==y)

Dr. Aman-ur-Rehman DNE, PIEAS

Page 29: Computer Fundamental lecture 2

Structure of a C ProgramMost C Programs contain the

following basic elements Preprocessor statements Global Declaration Function PrototypesFunctions

Dr. Aman-ur-Rehman DNE, PIEAS

Page 30: Computer Fundamental lecture 2

Structure of a C Program

Dr. Aman-ur-Rehman DNE, PIEAS

Preprocessor statements

Global declaration

Function prototypes

main(){……}

function1(){……}

function2(){……}

Page 31: Computer Fundamental lecture 2

Structure of a C ProgramPreprocessor statements represent instructions to the C

preprocessor. All preprocessor statements begin with the # symbol.

Global declaration statements define Global variables which are accessible to all parts of a C program.

Function declaration (also called function prototypes) are statements that provide the compiler information regarding the type of the value returned by a function and also type and number of function arguments.

Functions are groups of statements that the computer can execute. C functions are similar to subroutines in other programming languages.

Dr. Aman-ur-Rehman DNE, PIEAS

Page 32: Computer Fundamental lecture 2

Creating a C Program There are several steps that have to be performed

to create a C program1. Use a text editor to write your program (source

code) in C2. Compile your program using a C compiler. Correct

any errors pointed out by the compiler. Steps 1 and 2 are repeated until there are no errors in the program.

3. Link your program with library functions using an linker.

4. Execute and test your program.Dr. Aman-ur-Rehman

DNE, PIEAS

Page 33: Computer Fundamental lecture 2

Creating the Source Code The first step in creating a C program is to type the C language

statements into a file. A text editor is required to accomplish this task. There are number of editors that can be used for this purpose. All the integrated C programming environments also contain a text

editor. An integrated environment is a menu driven system for developing C

programs that includes and editor, compiler, linker, and debugger. By convention, C program files have names ending in .c. for example,

cylinder.c , binomial.c , roots.c One should give meaningful names to the programs so that is

reminds what the program does. The second part of the file name (.c) identifies it as a C program

Dr. Aman-ur-Rehman DNE, PIEAS

Page 34: Computer Fundamental lecture 2

A SIMPLE C PROGRAM/**************************************************//* hello_world.c *//* Program prints Hello World! *//**************************************************/#include <stdio.h>

int main(){ printf(“Hello World!\n”); return 0;}

Dr. Aman-ur-Rehman DNE, PIEAS

Page 35: Computer Fundamental lecture 2

A SIMPLE C PROGRAM/***********************************************************//* cylinder.c *//* Computes the volume and surface area of a cylinder *//***********************************************************/#include<stdio.h>#define PI 3.141592564

void main(void);

void main(void){

float radius,height,volume,surface_area;

/* print heading */printf("\n Cylinder.c");printf("\n Computes the volume and surface area of a cylinder.");

/* read in radius and height */printf("\n\n Enter radius of cylinder: ");scanf("%f", &radius);printf("\n\n Enter height of cylinder: ");scanf("%f", &height);

/* Compute volume and surface area */volume = PI * radius * radius * height;surface_area = 2 * PI * radius * (radius + height);

/* print results */printf("\n Volume of cylinder is: %10.4f", volume);printf("\n Surface area of cylinder is:%10.4f", surface_area);

}

Dr. Aman-ur-Rehman DNE, PIEAS

Page 36: Computer Fundamental lecture 2

Basic Programming Concepts Comment To explain what the program is for and why it is the

way it is. Preprocessing Done before the program is compiled.

To include header files containing information about C libraries

Statement A line of code that tells computer to perform some action. Always ended with a semicolon(;). Invoking functions

Function A module often consisting of a set of statements. Two functions in the hello world program: main, printf

Dr. Aman-ur-Rehman DNE, PIEAS

Page 37: Computer Fundamental lecture 2

Escape Sequences

• Escape Sequences are used to control printf to do something other than printing characters.• \n: Newline. Position cursor at the beginning of the

next line.• \t: Tab. Move cursor to the next tab stop.• \a: Alert. Sound the system bell.

Exercise• Modify the hello world program to try out

various escape sequences.

Dr. Aman-ur-Rehman DNE, PIEAS

Page 38: Computer Fundamental lecture 2

Computer Arithmetic One type of approximation inevitably

made in scientific computing is in representing real numbers on a computer.

In a digital computer, the real number system R of mathematics is represented by a floating- point number system.

Dr. Aman-ur-Rehman DNE, PIEAS

Page 39: Computer Fundamental lecture 2

Floating Point Numbers The basic idea of a floating- point number

system resembles scientific notation. In this system a number of very large value or

very small value is expressed as a number of a moderate size times an appropriate power of ten.

For example, 2347 and 0.0007396 are written as 2.347103 and 7.39610-4 respectively.

In this system the decimal point moves or floats , as the power of 10 changes.

Dr. Aman-ur-Rehman DNE, PIEAS

Page 40: Computer Fundamental lecture 2

Floating Point Numbers Formally, a floating-point number system F is

characterized by four integers: Base or radix p Precision [L, U] Exponent range

Any Floating point number xF has the form x =(d0+ d1 / +d2 / 2 + d3 / 3 +….+ dp-1 / p-1 ) E

where di is an integer such that 0 di -1, i=0,1,..,p-1

and E is an integer such that L E U.Dr. Aman-ur-Rehman

DNE, PIEAS

Page 41: Computer Fundamental lecture 2

Floating Point Numbers For example consider the number 4.235×103 in decimal

system : =10 Base or radix P=3 Precision [L, U] Exponent range

This floating point number can be expressed as 4.235×103=(4+2/10+3/100+5/1000)103

x =(d0+ d1 / +d2 / 2 + d3 / 3 +….+ dp-1 / p-1 ) E

where di is an integer such that 0 di -1, i=0,1,..,p-1

and E is an integer such that L E U.Dr. Aman-ur-Rehman

DNE, PIEAS

Page 42: Computer Fundamental lecture 2

Mantissa and Exponent of Floating Point Numbers

The part in parentheses, represented by a string of p base- digits d0d1 …..dp-1, is called the mantissa or significant, and E is called the exponent or characteristic of the floating-point number x.

The portion d1d2 …..dp-1, of mantissa is called the fraction. In a computer, the sign, exponent, and mantissa are stored

in separate fields of a given floating point word, each of which has a fixed width.

The number zero is represented uniquely by having both its mantissa and exponent equal to zero or by having a zero fraction and a special value of the exponent.

Dr. Aman-ur-Rehman DNE, PIEAS

Page 43: Computer Fundamental lecture 2

Arithmetic Operators

• To form expressions• Many statements are merely

expressions.

• Normal order of operations is followed. Parentheses can be used.

+ Addition- Subtraction

* Multiplication

/ Division

% Modulus (remainder)

++ Increment-- Decrement

Dr. Aman-ur-Rehman DNE, PIEAS

Page 44: Computer Fundamental lecture 2

Arithmetic Operators: An Example

1. /* Arithmetic operators */2. #include <stdio.h>3. 4. int main()5. {6. printf("7+3=%d\n",7+3);7. printf("7-3=%d\n",7-3);8. printf("7*3=%d\n",7*3);9. printf("7/3=%d\n",7/3);10. printf("7.0/3.0=%f\n",7.0/3.0);11. return 0;12.}

Dr. Aman-ur-Rehman DNE, PIEAS

Page 45: Computer Fundamental lecture 2

Output of the Program

Dr. Aman-ur-Rehman DNE, PIEAS

Page 46: Computer Fundamental lecture 2

A SIMPLE C PROGRAM/***********************************************************//* cylinder.c *//* Computes the volume and surface area of a cylinder *//***********************************************************/#include<stdio.h>#define PI 3.141592564

void main(void);

void main(void){

float radius,height,volume,surface_area;

/* print heading */printf("\n Cylinder.c");printf("\n Computes the volume and surface area of a cylinder.");

/* read in radius and height */printf("\n\n Enter radius of cylinder: ");scanf("%f", &radius);printf("\n\n Enter height of cylinder: ");scanf("%f", &height);

/* Compute volume and surface area */volume = PI * radius * radius * height;surface_area = 2 * PI * radius * (radius + height);

/* print results */printf("\n Volume of cylinder is: %10.4f", volume);printf("\n Surface area of cylinder is:%10.4f", surface_area);

}

Dr. Aman-ur-Rehman DNE, PIEAS

Page 47: Computer Fundamental lecture 2

Output of the Program

Dr. Aman-ur-Rehman DNE, PIEAS

Page 48: Computer Fundamental lecture 2

Output of the Program

Dr. Aman-ur-Rehman DNE, PIEAS

Page 49: Computer Fundamental lecture 2

Output of the Program

Dr. Aman-ur-Rehman DNE, PIEAS

Page 50: Computer Fundamental lecture 2

Output of the Program

Dr. Aman-ur-Rehman DNE, PIEAS

Page 51: Computer Fundamental lecture 2

Output of the Program

Dr. Aman-ur-Rehman DNE, PIEAS

Page 52: Computer Fundamental lecture 2

Structure of a C Program

Dr. Aman-ur-Rehman DNE, PIEAS

Preprocessor statements

Global declaration

Function prototypes

main(){……}

function1(){……}

function2(){……}

Page 53: Computer Fundamental lecture 2

A SIMPLE C PROGRAM/**************************************************//* first.c

*//* Program prints a sentences *//**************************************************/#include <stdio.h>

int main(){ printf(“Every age has a language of its own\n”); return 0;}

Dr. Aman-ur-Rehman DNE, PIEAS

Page 54: Computer Fundamental lecture 2

Functions• Functions are one of the fundamental building blocks of C. The FIRST

program consists almost entirely of a single function called main(). • The only part of this program that are not part of the function is the

first line—the ones that start with #include• The parentheses following the word main are the distinguishing feature

of a function. Without the parentheses the compiler would think that main refers to a variable or to some other program element.

• We’ll put parentheses following the function name.• The parentheses aren’t always empty.• They’re used to hold function arguments: values passed from the

calling program to the function.• The word int preceding the function name indicates that this particular

function has a return value of type int.

Dr. Aman-ur-Rehman DNE, PIEAS

Page 55: Computer Fundamental lecture 2

Braces and the Function Body• The body of a function is surrounded by braces

(sometimes called curly brackets). These braces play the same role as the BEGIN and END keywords in some other languages:

• They surround or delimit a block of program statements. Every function must use this pair of braces around the function body.

• In this example there are only two statements in the function body: the line starting with printf, and the line starting with return.

• However, a function body can consist of many statements.

Dr. Aman-ur-Rehman DNE, PIEAS

Page 56: Computer Fundamental lecture 2

Always Start With Main• When you run a C program, the first statement

executed will be at the beginning of a function called main().

• The program may consist of many functions, and other program elements, but on startup, control always goes to main().

• If there is no function called main() in your program, an error will be reported when you run the program.

• The main() function may also contain calls to other standalone functions.

Dr. Aman-ur-Rehman DNE, PIEAS

Page 57: Computer Fundamental lecture 2

Program Statements• The program statement is the fundamental unit of C

programming. • There are two statements in the FIRST program: the line printf(“Every age has a language of its own\n”); and the return statement return 0;• The first statement tells the computer to display the quoted

phrase. • Most statements tell the computer to do something. • In this respect, statements in C are similar to statements in

other languages.Dr. Aman-ur-Rehman

DNE, PIEAS

Page 58: Computer Fundamental lecture 2

Program Statements• A semicolon signals the end of the statement. This is a crucial

part of the syntax but easy to forget. • In some languages (like BASIC), the end of a statement is

signalled by the end of the line, but that’s not true in C.• If you leave out the semicolon, the compiler will often

(although not always) signal an error.• The last statement in the function body is return 0;. This tells

main() to return the value 0 to whoever called it, in this case the operating system or compiler.

• In older versions of C you could give main() the return type of void and dispense with the return statement, but this is not considered correct in Standard C.

Dr. Aman-ur-Rehman DNE, PIEAS

Page 59: Computer Fundamental lecture 2

String Constants• The phrase in quotation marks, “Every age has a language

of its own\n”, is an example of a string constant.• As you probably know, a constant, unlike a variable, cannot

be given a new value as the program runs. Its value is set when the program is written, and it retains this value throughout the program’s existence.

• The ‘\n’ character at the end of the string constant is an example of an escape sequence.

• It causes the next output to be displayed on a new line. We use it here so that the phrases such as “Press any key to continue,” inserted by some compilers for display after the program terminates, will appear on a new line.

Dr. Aman-ur-Rehman DNE, PIEAS

Page 60: Computer Fundamental lecture 2

Preprocessor Directives• The first line of the FIRST program

#include <stdio.h> might look like a program statement, but it’s not. It isn’t part of a

function body and doesn’t end with a semicolon, as program statements must. Instead, it starts with a number sign (#).

• It’s called a preprocessor directive.• Recall that program statements are instructions to the computer

to do something, such as adding two numbers or printing a sentence.

• A preprocessor directive, on the other hand, is an instruction to the compiler. A part of the compiler called the preprocessor deals with these directives before it begins the real compilation process.

Dr. Aman-ur-Rehman DNE, PIEAS

Page 61: Computer Fundamental lecture 2

Preprocessor Directives• The preprocessor directive #include tells the

compiler to insert another file into your source file.

• In effect, the #include directive is replaced by the contents of the file indicated.

• Using an #include directive to insert another file into your source file is similar to pasting a block of text into a document with your word processor.

• The type file usually included by #include is called a header file.

Dr. Aman-ur-Rehman DNE, PIEAS

Page 62: Computer Fundamental lecture 2

Header File• In the FIRST example, the preprocessor directive #include

tells the compiler to add the source file stdio to the first.c source file before compiling.

• Why do this? stdio is an example of a header file (sometimes called an include file).

• It’s concerned with basic input/output operations, and contains declarations that are needed by the printf function.

• Without these declarations, the compiler won’t recognize printf.

• There are many such include files. • The header files have extension .h.

Dr. Aman-ur-Rehman DNE, PIEAS

Page 63: Computer Fundamental lecture 2

Comments• Comments are an important part of any program.• They help the person writing a program, and anyone else who must read the

source file, understand what’s going on. • The compiler ignores comments, so they do not add to the file size or execution

time of the executable program.• Comments are almost always a good thing. Most programmers don’t use

enough of them. • If you’re tempted to leave out comments, remember that not everyone is as

smart as you; they may need more explanation than you do about what your program is doing.

• Also, you may not be as smart next month, when you’ve forgotten key details of your program’s operation, as you are today.

• Use comments to explain to the person looking at the listing what you’re trying to do. The details are in the program statements themselves, so the comments should concentrate on the big picture, clarifying your reasons for using a certain statement or group of statements.

Dr. Aman-ur-Rehman DNE, PIEAS

Page 64: Computer Fundamental lecture 2

Integer Variables• Variables are the most fundamental part of any language. • A variable has a symbolic name and can be given a variety of values.• Variables are located in particular places in the computer’s memory.

When a variable is given a value, that value is actually placed in the memory space assigned to the variable.

• Most popular languages use the same general variable types, such as integers, floating-point numbers, and characters, so you are probably already familiar with the ideas behind them.

• Integer variables represent integer numbers like 1, 30,000, and –27. Such numbers are used for counting discrete numbers of objects, like 11 pencils or 99 bottles of beer.

• Unlike floating-point numbers, integers have no fractional part; you can express the idea of four using integers, but not four and one-half.

Dr. Aman-ur-Rehman DNE, PIEAS

Page 65: Computer Fundamental lecture 2

Defining Integer Variables• Integer variables exist in several sizes, but the most commonly

used is type int. • The amount of memory occupied by the integer types is system

dependent. On a 32-bit system such as Windows, an int occupies 4 bytes (which is 32 bits) of memory.

• This allows an int to hold numbers in the range from –2,147,483,648 to 2,147,483,647. Figure 2.3 shows an integer variable in memory.

• While type int occupies 4 bytes on current Windows computers, it occupied only 2 bytes in MS-DOS and earlier versions of Windows. The ranges occupied by the various types are listed in the header file LIMITS; you can also look them up using your compiler’s help system.

Dr. Aman-ur-Rehman DNE, PIEAS

Page 66: Computer Fundamental lecture 2

A Program With Several Variables• Here’s a program that defines and uses several variables of type int:

// intvars.c// demonstrates integer variables#include <stdio.h>int main(){

int var1; //define var1int var2; //define var2var1 = 20; //assign value to var1var2 = var1 + 10; //assign value to var2printf("var1+10 is %5d\n", var2); //output text and output value of var2 return 0;

}

Dr. Aman-ur-Rehman DNE, PIEAS

Page 67: Computer Fundamental lecture 2

Variable of Type int in memory

Dr. Aman-ur-Rehman DNE, PIEAS

Page 68: Computer Fundamental lecture 2

Declaration and Definitions• A declaration introduces a variable’s name (such as var1) into

a program and specifies its type (such as int). • However, if a declaration also sets aside memory for the

variable, it is also called a definition. The statementsint var1;int var2;

in the INTVARS program are definitions, as well as declarations, because they set aside memory for var1 and var2.

• We’ll be concerned mostly with declarations that are also definitions, but

• later on we’ll see various kinds of declarations that are not definitions.

Dr. Aman-ur-Rehman DNE, PIEAS

Page 69: Computer Fundamental lecture 2

Variable Names• The names given to variables (and other program features) are called identifiers. • What are the rules for writing identifiers? • You can use upper- and lowercase letters, and the digits from 1 to 9. • You can also use the underscore (_). • The first character must be a letter or underscore.• Identifiers can be as long as you like, but most compilers will only recognize the

first few hundred characters. • The compiler distinguishes between upper- and lowercase letters, so Var is not

the same as var or VAR.• You can’t use a C keyword as a variable name. • A keyword is a predefined word with a special meaning. int, class, if, and while

are examples of keywords.• A variable’s name should make clear to anyone reading the listing the variable’s

purpose and how it is used. Thus boilerTemperature is better than something cryptic like bT or t.

Dr. Aman-ur-Rehman DNE, PIEAS

Page 70: Computer Fundamental lecture 2

Assignment Statements• The statements

var1 = 20;var2 = var1 + 10;

assign values to the two variables. The equal sign (=), as you might guess, causes the value on the right to be assigned to the variable on the left.

• The = in C is equivalent to the := in Pascal or the = in BASIC.

• In the first line shown here, var1, which previously had no value, is given the value 20.

Dr. Aman-ur-Rehman DNE, PIEAS

Page 71: Computer Fundamental lecture 2

Integer Constants• The number 20 is an integer constant. Constants

don’t change during the course of the program.• An integer constant consists of numerical digits. • There must be no decimal point in an integer

constant, and it must lie within the range of integers.• In the second program line shown here, the plus sign

(+) adds the value of var1 and 10, in which 10 is another constant.

• The result of this addition is then assigned to var2.

Dr. Aman-ur-Rehman DNE, PIEAS

Page 72: Computer Fundamental lecture 2

Other Integer Types• There are several numerical integer types besides type int. The two most common

types are long and short.• type int is system dependent.• In contrast, types long and short have fixed sizes no matter what system is used.• Type long always occupies four bytes, which is the same as type int on 32-bit

Windows systems.• Thus it has the same range, from –2,147,483,648 to 2,147,483,647. • It can also be written as long int; this means the same as long. • There’s little point in using type long on 32-bit systems, since it’s the same as int. • However, if your program may need to run on a 16-bit system such as MS-DOS, or on

older versions of Windows, specifying type long will guarantee a four-bit integer type. In 16-bit systems, type int has the same range as type short.

• On all systems type short occupies two bytes, giving it a range of –32,768 to 32,767. • There’s probably not much point using type short on modern Windows systems

unless it’s important to save memory. Type int, although twice as large, is accessed faster than type short.

Dr. Aman-ur-Rehman DNE, PIEAS