Académique Documents
Professionnel Documents
Culture Documents
COURSE CONTENTS
Basic components of a computer Programming languages Programming in C and its Applications
Lab Teachers
1. 2. 3. 4. 5. 6. 7. 8. Dr. Yousaf Hamza, PE, DPAM, PIEAS Dr. Naeem Akhtar, SE, DCIS, PIEAS Mr. Mazhar Husnain, SE, DMS, PIEAS Mrs. Romana Basit, SS, DChE, PIEAS Mr. Qaiser Nadeem, JE, DNE, PIEAS Mr. Muhammad Hur, JE, DEE, PIEAS Mr. Taskeen Ahmad, PhD Scholar, DEE, PIEAS Mr. Iftekhar Ahmad, PhD Scholar, DPAM, PIEAS
Dr. Aman-ur-Rehman DNE, PIEAS
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 nonnumerical (arithmetic and logical) calculations.
Components of a Computer
INPUT Keyboard Mouse Scanner Camera
Arithmetic Logic Unit (ALU) Control Unit Internal Memory Unit
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
Computer Program
A computer program is a sequence instructions that are executed by a CPU. of
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
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
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
Computer Languages
High Level Languages:
The user friendly language ...more natural language than assembly language. Complier is needed to convert high level to machine language
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.
Dr. Aman-ur-Rehman DNE, PIEAS
Programming Languages
Machine Languages +1300042774 +1400593419 +1200274027
Assembly Languages
High-Level Languages
C=A+B
Assembler
Instructions 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.
Compiler
Instructions 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.
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
Creating Programs
C libaray
Edit
hello.c
compile
hello.o
Link
hello
Source File
(High-Level Languages)
Object File
(Machine Languages)
History of C Language
Developed in early 1970s by Dennis Ritchie C evolved from a language named B developed by Ken Thomson Dennis 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
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
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 dont 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
Disadvantages of C Language
Since 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
Structure of a C Program
Structure of a C Program
Preprocessor statements
Global declaration
Function prototypes
main() { }
function1() { }
function2() { }
Structure of a C Program
Preprocessor 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
Creating a C Program
There are several steps that have to be performed to create a C program
1.
2.
3. 4.
Use a text editor to write your program (source code) in C 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. Link your program with library functions using an linker. Execute and test your program.
Dr. Aman-ur-Rehman DNE, PIEAS
A SIMPLE C PROGRAM
/**************************************************/ /* hello_world.c */ /* Program prints Hello World! */ /**************************************************/ #include <stdio.h>
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);
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
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
In this system the decimal point moves or floats , as the power of 10 changes.
Dr. Aman-ur-Rehman DNE, PIEAS
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.
This floating point number can be expressed as 4.235103=(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
Arithmetic Operators
To form expressions
Many statements are merely expressions.
+ * / % ++ --
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);
Structure of a C Program
Preprocessor statements
Global declaration
Function prototypes
main() { }
function1() { }
function2() { }
A SIMPLE C PROGRAM
/**************************************************/ /* first.c */ /* Program prints a sentences */ /**************************************************/ #include <stdio.h>
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 linethe 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. Well put parentheses following the function name. The parentheses arent always empty. Theyre 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
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
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 thats 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
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 programs 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
Preprocessor Directives
The first line of the FIRST program #include <stdio.h> might look like a program statement, but its not. It isnt part of a function body and doesnt end with a semicolon, as program statements must. Instead, it starts with a number sign (#). Its 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
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
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). Its concerned with basic input/output operations, and contains declarations that are needed by the printf function. Without these declarations, the compiler wont recognize printf. There are many such include files. The header files have extension .h.
Dr. Aman-ur-Rehman DNE, PIEAS
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 whats 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 dont use enough of them. If youre 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 youve forgotten key details of your programs operation, as you are today. Use comments to explain to the person looking at the listing what youre 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
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 computers 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
}
Dr. Aman-ur-Rehman DNE, PIEAS
in the INTVARS program are definitions, as well as declarations, because they set aside memory for var1 and var2. Well be concerned mostly with declarations that are also definitions, but later on well see various kinds of declarations that are not definitions.
Dr. Aman-ur-Rehman DNE, PIEAS
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 cant 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 variables name should make clear to anyone reading the listing the variables purpose and how it is used. Thus boilerTemperature is better than something cryptic like bT or t.
Dr. Aman-ur-Rehman DNE, PIEAS
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
Integer Constants
The number 20 is an integer constant. Constants dont 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