Computer Programming PDF

Document Details

HandsDownKangaroo

Uploaded by HandsDownKangaroo

Federal College of Education H-9 Islamabad

Tags

computer programming programming languages low-level languages computer science

Summary

This document provides an introduction to computer programming, explaining concepts like syntax, semantics, and computer programs. It also details programming languages, including low-level languages such as machine and assembly languages, and also high-level languages, such as Visual Basic, C, Java, and Pascal.

Full Transcript

2.1 2 INTRODUCTION TO COMPUTER PROGRAMMING Computer programming is the process of writing a computer program in computer language to solve a particular problem. Computer program controls the operation of a computer and it is de...

2.1 2 INTRODUCTION TO COMPUTER PROGRAMMING Computer programming is the process of writing a computer program in computer language to solve a particular problem. Computer program controls the operation of a computer and it is developed in a computer language to perform a task. Therefore, it is essential for students to learn computer languages to solve various problems. Computer languages are also known as programming languages. 2.1.1 COMPUTER PROGRAM A computer program is a set of instructions (statements) written in a programming language to solve a particular problem and achieving specific results. Any task performed by a computer is controlled by a set of instructions that are executed by the microprocessor. A large variety of programming languages have been developed for writing computer programs to use the computer as a problem-solving tool. Each statement of a programming language has syntax and semantic. Syntax Syntax refers to the rules of a programming language according to which statements of a program are to be written. It describes the way to write correct statements in a program. Syntax of a programming language is similar to the grammar of a natural language. For example, an assignment statement consists of a variable and an expression separated by equal sign as an assignment operator. This is the syntax of assignment statement and it can be expressed as given below. variable = expression; Semantic Semantic gives meaning to statements of a programming language. It describes the sequence of operations to be performed by a computer when executing the statements of a computer program. For example, in the assignment statement: sum = a + b; the semantic of the statement is to perform the expression, that is, add the values stored in variables a and b and then store the result in variable sum. 2.1.2 PROGRAMMING LANGUAGES A programming language is a language which is understood by computer. It is designed to give instructions to a computer to perform a specific task. It is used to write computer programs. Programming languages can be classified into two categories, that is, low level languages and high level languages. Low Level Languages 2 Programming in C 31 Low level language is machine-oriented language. To understand low level language, detailed knowledge of internal working of computer is required. Low level languages include machine language and assembly language. 2 Programming in C Machine Language Programming language that is directly understood by computer hardware is known as machine language. Machine language is associated with architecture of computer. Therefore, programs written in machine language for one computer will not work on another because of design differences. It consists of zeroes and ones. It is almost impossible for humans to use machine language because it entirely consists of numbers. Therefore, practically no programming is done in machine language. Instead, assembly languages and high level languages are used. Assembly Language Assembly language consists of symbolic codes or abbreviations known as mnemonics. It was developed to make computer programming easier than machine language. The abbreviations used in assembly language make it easier to learn and write programs compared to machine language. A program written in assembly language must be converted into machine language before it is executed by computer. A program known as assembler is used to translate assembly language into machine language. Some important characteristics of Assembly language are:  Assembly language allows programmers to have access to all the special features of the computer they are using. Certain types of operations which are not possible in high level languages are easily programmed using assembly language.  Generally a program written in assembly language will require less storage and less running time than one prepared in a high level language.  Assembly languages are still the best choice in some applications but their use is gradually declining. High Level Languages (HLLs) High level languages are English-oriented languages and they are commonly used for writing computer programs. These languages use English language words such as print, go to, if, end, etc. Therefore, they are easy to learn and use. Some examples of high level languages are Visual Basic, C, Java and Pascal. A program known as compiler/interpreter is required to translate a high level program into machine language. Coding and debugging of a high level language program is much easier than a program written in a low level language. High-level languages can be classified into procedural, structured and object-oriented programming languages. 32 Procedural Languages Procedural programming is based upon the concept of modular programming. In modular programming, programs are divided into smaller parts known as modules. Modular programs consist of one or more modules. A module is a group of statements that can be executed more than once in a program. Each module in a program performs a specific task. It is easy to design, modify and debug a program in a procedural language since it provides better programming facilities. Some examples of procedural languages are FORTRAN, Pascal, C and BASIC. Structured Languages Structured languages consist of three fundamental elements, which are sequence, selection and repetition. Sequence: It means, writing program statements in a logical sequence. Each step in the sequence must logically progress to the next without producing any undesirable effects. Selection: It allows the selection of any number of statements based on the result of evaluation of a condition which may be true or false. Examples of statements that implement selection in programming are if, else-if, switch, etc. Repetition (loop): It means executing one or more statements a number of times until a condition is satisfied. Repetition is implemented in programs using statements, such as for and while loops. Some examples of structured languages are ALGOL, PL/1, Ada and Pascal. Object-Oriented Programming Languages (oops) Object-oriented programming (oops) refers to a programming method that is based on objects such as student, vehicle, building, etc. Object-oriented programming language provides a set of rules for defining and managing objects. An object can be considered a thing that can perform a set of activities. For example, the object vehicle can be defined as an object that has number of wheels, number of doors, color, number of seats, etc. The set of activities that can be performed on this object include Steer, Accelerate, Brake, etc. Complicated and large computer programs are difficult to design, develop, maintain and debug. The concept of object-oriented programming solves this problem. The most widely used object-oriented programming languages are C++, C#, php and Java. 2.1.3 CHARACTERISTICS OF HIGH LEVEL LANGAUGES High-level languages have the following characteristics. 2 Programming in C 33 1) These languages were developed to make computer programming simple, easier and less prone to errors. 2) High level languages are not machine dependent. They enable programmers to write programs that are independent of a particular type of computer. 2 Programming in C 3) Programs written in high-level languages must be translated into machine language by a compiler or an interpreter before execution by the computer. 4) The process of finding and removing errors in programs (debugging) is easier in high-level languages compared to low level language. 5) High-level language programs are highly structured. They allow programmers to break lengthy programs into a number of modules which can be written and tested independently. This makes writing and testing of programs easier. 2.1.4 POPULAR HIGH LEVEL LANGUAGES C/C++ C language was developed in early 1970s by Dennis Ritchie at Bell Laboratories. C has become one of the most popular programming languages today. It is a highly structures programming language that is easy to understand and use. In the past, it was mainly used for writing system programs such as operating systems, compilers, assemblers, etc. Today, it is used for writing all types of application programs as well, such as word-processing programs, spreadsheet programs, database management systems, educational programs, games, etc. C++ was developed by Bjarne Stroustrup also at Bell Laboratories during 1983-1985. C++ is a superset of C, meaning that any valid C program is also a valid C++ program. The purpose of developing C++ was to provide programming facilities to easily and quickly write more powerful programs. Visual Basic Visual Basic (VB) is a high level language which evolved from the earlier version called BASIC. BASIC stands for Beginner’s All-purpose Symbolic Instruction Code. VB is a very popular programming language for writing Windows and Web applications. It provides a graphical development environment to programmers to develop powerful Windows and Web applications. VB is commonly used for developing business programs such as payroll system and inventory control program. The user can also write programs related with engineering, science, arts, education, games, etc. C# C# (pronounced as C-sharp) is a language developed in 2000 by Microsoft Corporation. It is a simple, modern, general-purpose programming language. Syntax of C# is very similar to C 34 and C++. It also has some features of Java. It is a language that makes computer programming easy and efficient. It provides facilities to write Web applications that can be used across the Internet. All types of programs including games, utilities, operating systems, compilers, business applications and Web based applications can be developed in C#. Java Java is a high-level language developed by Sun Microsystems. It is very similar in syntax to C and C++. In Java, the user can write all types of programs as those written in other programming languages and small programs that can be embedded in a Web page accessed through Internet. Java is an ideal language for network computing. It is used for writing programs for a wide range of devices, computers and networks. It is widely used in Web applications. The current versions of most of the Web browsers are made Java enabled. A few browsers that support Java are Microsoft’s Internet Explorer, Firefox and Mozilla. 2.1.5 COMPILER AND INTERPRETER Compiler A compiler is computer software that translates source program into object program as shown in Fig.2-1. Source Program Compiler Object Program Fig.2-1 Translation of source program into object program Source program consists of statements written in a high level language such as C, Pascal, Java, etc. For example, a program written in C language by a programmer to print table of a number is known as source program. When it is translated with a compiler into machine language, the resulting program is known as object program. The object program is understandable by computer processor but difficult for a human to read and understand because it consists of zeroes and ones. Interpreter 2 Programming in C 35 Interpreter translates high level language programs into machine language but it translates one instruction at a time and executes it immediately before translating the next instruction. Examples of programming languages that use interpreter are Java Script, BASIC, Visual Basic and Perl. Interpreter reads each statement of source program, one at a time and determines what it means as it executes it. It means each time a statement is read, it must be translated into machine language before execution. Compiler translates the entire program into object program before execution by computer. Therefore, a compiled program runs fast. 2 Programming in C 2.2 PROGRAMMING ENVIRONMENT Programming environment is the set of processes and programming tools used to develop computer programs. In the past, programmers used various standalone programming tools for developing computer programs. These included editor, compiler, linker, debugger, etc. Using separate programs provided a difficult and time consuming environment for creating computer programs. Today, programmers use Integrated Development Environment for developing computer programs. Integrated Development Environment is an application package that consists of editor, compiler, linker and debugger with a graphical user interface. 2.2.1 INTEGRATED DEVELOPMENT ENVIRONMENT Most of the new programming languages use Integrated Development Environment (IDE) to create, compile and run programs. IDE is computer software that brings all the processes and tools required for program development into one place. IDE’s aim is to make the life of programmers easier by grouping together all the tasks needed for building applications into one environment. Today’s modern IDEs have user-friendly Graphical User Interface (GUI). 2.2.2 PROGRAMMING ENVIRONMENT OF C LANGUAGE A C language IDE consists of the following modules. Text Editor Compiler Linker Loader Debugger Text Editor A text editor is a simple word-processor that is used to create and edit source code of a program as shown in Fig.2-2. Files created by a text editor are plain text files. Most of the editors automatically highlight compile errors to simplify removing them. 36 2 Programming in C is used in the program, then it would assume that it is defined in C library. It will replace this function in the object program with the code from C library and then create a single executable program. Loader It is a software that loads programs into memory and then executes them. Debugger It is a software that executes a program line by line, examines the values stored in variables and helps in finding and removing errors in programs. 2.3 PROGRAMMING BASICS C is a popular and widely used programming language for creating computer programs. A large variety of application programs and many modern operating systems are written in C. 2.3.1 C LANGUAGE CHARACTER SET The C Language character set includes: Letters C language comprises the following set of letters to form a standard program. They are: A to Z in Capital letters. a to z in Small letters. In C programming, small latter and caps latter are distinct. Digits C language comprises the following sequence of numbers to associate the letters. 0 to 9 digits. Special Characters C language contains the following special character in association with the letters and digits. Symbol Meaning Symbol Meaning Symbol Meaning ~ Tilde _ Underscore ] Right bracket ! Exclamation mark + Plus sign : Colon # Number sign | Vertical bar " Quotation mark $ Dollar sign \ Backslash ; Semicolon 2 Programming in C 37 % Percent sign ` Apostrophe < Opening angle bracket ^ Caret - Minus sign > Closing angle bracket & Ampersand = Equal to sign ? Question mark * Asterisk { Left brace , Comma ( Lest parenthesis } Right brace. Period ) Right parenthesis [ Left bracket / Slash 38 40 2 Programming in C In order to use a library function, the programmer must include appropriate header file at the beginning of the program as shown in Fig.2-4. When source program is translated into executable file, a copy of code of function is pasted in the source program by the linker from the header file before creating the executable file. 2.3.4 STRUCTURE OF A C PROGRAM The format according to which a program is written is called the structure of program. The following is the structure of a C program. To introduce the structure of a C program, consider a very simple program that will print the message: I Love Pakistan The program may be written as shown in Fig.2-6. Fig.2-6 Program to print a message on the screen 2 Programming in C 41 This program consists of three main parts which are preprocessor directive, the main() function and the body of main(). Preprocessor Directives Preprocessor directives are instructions for the C compiler. Every C language program contains certain preprocessor directives at the beginning of the program. Before translating a C language program into machine language, the compiler of C language carries out the processor directives. These directives start with number sign (#). The most commonly used preprocessor directives are #include and #define. #include Preprocessor Directive It has the following syntax. #include When this preprocessor is carried out by the C compiler, it will search for the header file that is written within the less than () symbols and copy it into the source file. In the above program the header file stdio.h is used. It tells the C compiler to copy the stdio.h header file into the program. The stdio.h header file stands for standard input-output header. It includes the standard printf( ) and scanf() function prototypes. In the above program the printf() functions is used. Therefore, it is required to include this header file in the include preprocessor directive. main() Function C programs consist of one or more functions. A function performs a single well-defined task. Every C program must have the function main() which is the first section to be executed when the program runs. The general form of main() is: void main(void) The word void before the function main() means that this function does not return a value and the second void inside the brackets means it does not have any argument. Body of main() Function The body of the function main() is surrounded by braces (curly brackets { and }). The left brace indicates the start of the body of the function and the matching right brace indicates the end of the body of the function. The body of the function in the program (see Fig. 2.6) consists of a single statement printf() which ends with a semicolon(;). printf() is the standard output function. The text to be printed is enclosed in double quotes. A statement in C is terminated with a semicolon. Therefore, a semicolon is used at the end of printf() statement. This program will print the message I Love Pakistan on the screen. 42 2.3.5 COMMENTS IN C LANGUAGE It is a good programming practice to add comments in program to make it easy for others to understand it. Comments in the source code are ignored by the compiler. The program in Fig.2-7 demonstrates how single line comments are used in a program. In this program comments describe the purpose of statements. 2.4 CONSTANTS AND VARIABLES Constant and variables are used in expressions in computer programs. After an expression is evaluated, the result of the expression is also stored in a variable. 2.4.1 CONSTANT AND VARIABLE Constant Constants are quantities whose values do not change during program execution. They may be numeric, character or string. Numeric Constants are of two types, integer and floating-point numbers. Integer constants represent values that are counted, like the number of students in a class. Some examples of integer constants are 7145, -234, 26, etc. Floating-point constants are used to represent values that are measured, like the height of a person which might have a value of 166.75 cm or the weight such as 82.6 kilograms. Character Constant is one of the symbols in C character set. It includes digits 0 to 9, uppercase letters A to Z, lower-case letters a to z, punctuation symbols such as semicolon (;), comma (,), period (.) and special symbols such as +, -, =, >, etc. A character constant is enclosed by single quotes such as ‘a’, ‘s’, etc. String Constant contains a string of characters within double quotes such as “Hello Ahmed”, “a”, etc. Variable A variable is a symbolic name that represents a value that can change during execution of a program. A variable has a name, known as variable name and it holds data of other types. A number or any other type of data held in a variable is called its value. It also indicates the types of value a variable can represent. Variables are of two types, numeric and character. Numeric variables are used to represent numeric values in computer programs. They represent integer and floating-point values. Some examples of numeric variables are sum, avg, length, salary, marks, etc. Character variables represent character values in computer programs. It can represent a single character or a string of characters. Some examples of character variables are name, city, gender, etc. 2 Programming in C 43 When a variable is used in a computer program, the computer associates it with a particular memory location. The value of a variable at any time is the value stored in the associated memory location at that time. Variables are used so that the same space in memory can hold different values at different times. 2.4.2 RULES FOR SPECIFYING VARIABLE NAMES The following are the rules for specifying variable names in C language. 2 Programming in C A variable begins with a letter or underscore ( _ ) and may consist of letters, underscores and/or digits. The underscore may be used to improve readability of the variable name. For example, over_time. There is no restriction on the length of a variable name. However, only the first 31 characters of a variable are significant. This means that if two variables have the same first 31 characters they are considered to be the same variables. Both upper and lower case letters are allowed in naming variables. An upper case letter is considered different from a lower case letter. For example the variable AVG is different from Avg or avg. Special characters cannot be used as variable name. e.g., #, ?, @ etc. Reserved words of C language such as int, case, if, etc., cannot be used as variable names. Space is not allowed in the name of variable. For example ma ss is not correct. 2.4.3 DATA TYPES USED IN C PROGRAMS C provides three main data types for variables, that is, integer, floating-point and character variables. Integer Data Type Integer variable declaration statement has the form: Type specifier Variable; For example: int sum; The declaration consists of the type name, int, followed by the name of the variable, sum. All the variables used in a C program must be declared. If there are more than one variable of the same type, separate the variable names with commas as shown in the following declaration statement. 44 int a,b,sum,product; Declaring a variable tells the computer the name of the variable and its type. This enables the compiler to recognize the valid variable names in program. This is very helpful if the user types the wrong spellings of a variable name in his program, the compiler will give an error message indicating that the variable is not declared. Declaration of an integer variable can begin with the type qualifiers, short, long, unsigned or signed. Some examples are: short int num; long int sum, avg; unsigned int count; short unsigned int count; Type qualifiers refer to the number of bytes used for storing the integer on a particular computer. Refer to computer manual to find out the sizes of the computer being used. Generally, the number of bytes set aside by the compiler for the above type qualifiers are as given in Fig.2-8. Variable Declaration No. of Bytes Range Here, int or short int 2 -32,768 ~ +32,767 -2,147,483,648 ~ long int 4 +2,147,483,647 unsigned int 2 0 ~ 65,535 Fig.2-8 Integer data types used in C unsigned implies that the value of variable is greater than or equal to zero. The qualifier, signed, is rarely used since by default, an int declaration assumes a signed number. Note that in the above examples, the word int may be omitted when it begins with long or unsigned type qualifiers in the declaration statements. For example you can write: short num; Floating-point Data Type Floating-point variables are used for storing floating-point numbers. Floating point numbers are stored in memory in two parts. The first part is the mantissa and the second part is the exponent. The mantissa is the value of the number and the exponent is the power to which it is raised. Some examples of floating-point variable declaration statements are: float base,height; double float a,b,total; long double float size,x,y; 2 Programming in C 45 Usually the number of bytes set aside by the compiler for the above floating-point type qualifiers are as given in Fig.2-9. Variable Declaration No. of Bytes Range 10-38 ~ 1038 float 4 (with 6 or 7 digits of precision) 10-308 ~ 10308 double float 8 (with 15 digits of precision) 10-4932 ~ 104932 long double float 10 (with twice the precision of double) Fig.2-9 Floating-point data types used in C 2 Programming in C Here, precision means the number of digits after the decimal point. The word float may be omitted when it is preceded by double or long double type qualifiers in the declaration statements. There is another method of representing floating-point numbers known as exponential notation. For example, the number 23,688 would be represented as 2.3688e4. Here, 2.3688 is the value of the number (mantissa) and 4 is the exponent(e). The exponent can also be negative. For example, the number 0.0005672 is represented as 5.672e-4 in exponential notation. Exponential notation is used to represent very large and very small numbers. In C, a floating point number of type float is stored in four bytes. Three bytes for the mantissa and one byte for the exponent and provides 6 or 7 digits of precision. Character Data Type Character variables are used to store character constants. Examples of declaration of character variables are: char ch, letter,a; A character variable can only store one character. The compiler sets aside one byte of memory for storing a character in a character variable. Key Points Syntax refers to the rules of a programming language according to which statements of a program are to be written. Semantic gives meaning to statements of a programming language. 46 Machine language is a programming language that is directly understood by computer hardware. It consists of zeroes and ones. Assembly language consists of symbolic codes or abbreviations. It was developed to make computer programming easier than machine language. A program called assembler is required to convert assembly language to machine language for execution by the computer. High level language is an English-oriented language. It is commonly used for writing computer programs. A program called compiler/interpreter is required to translate high level language into machine language for execution by the computer. Compiler is a computer program that translates a program written in a high level language into machine language equivalent program. It converts the entire program into machine language before execution by the computer. Interpreter is a computer program that translates a program written in a high level language into machine language. It translates one instruction at a time and executes it immediately before translating the next instruction. Programming environment is the set of processes and programming tools used to develop computer programs. Integrated Development Environment (IDE) is a computer software that is used to create, compile and run programs. It brings all the processes and tools required for program development into one place. Text editor is a simple word-processor that is used to create and edit source code of a program. Linker is a software that takes one or more object files, generated by a compiler and combines them into a single executable program. Loader is a software that loads programs into memory and then executes them. Debugger is a software that executes a program line by line, examines the values stored in variables and helps in finding and removing errors in programs. Header file is a file that contains predefined functions of C language. Including a header file in a C source file produces the same result as copying the header file into the source file. Reserved words are those words that are part of a programming language and have special purpose in computer programs. Preprocessor directives are instructions for the C compiler at the beginning of program. Comments are notes that are included in programs when a fact is necessary to be brought to the attention of program’s reader. 2 Programming in C 2 Programming in47 C D. 1990s Constant is a quantity whose value does not B. Microsoft change during program execution. D. IBM Variable is a symbolic name that represents a value that can change during execution of a program. B. Keywords D. Mnemonics B. 3 Exercise D. 5 Q1. Select the best answer for the following MCQs. B. 3 i. What defines the rules of valid statements in D. 5 programming? -38 38 A. Compiler B. Interpreter B. 10 ~ 10 -4932 C. Syntax D. Semantic ii. Which D. 10 ~ 104932 language is directly understood by the computer? B. Linker A. Machine language B. Assembly D. Debugger language C. High level language D. C language iii. B. Text Editor When was C language developed? D. Debugger A. Late 1960s B. Early 1970s C. 1980s iv. Who developed Java language? A. Dennis Ritchie C. Sun Microsystems v. What is the other word used for Reserved Words? A. Compiler words C. Special programming words vi. How many bytes are set aside by the compiler for a variable of type int? A. 2 C. 4 vii. How many bytes are set aside by the compiler for a variable of type float? A. 2 C. 4 viii. What is the range of numbers that can be stored in a variable of type double float? 48 A. -32,768 ~ +32,767 C. 10-308 ~ 10308 ix. Which program translates high level language into machine language? A. Compiler C. Loader x. Which software helps in finding and removing errors in programs? A. Linker B. Loader Short Questions Q2. Give short answers to the following questions. i. Define computer program. ii. Differentiate between syntax and semantic. iii. Write three differences between assembly language and HLLs. iv. Write four characteristics of HLLs. v. Define Integrated Development Environment (IDE). vi. Differentiate between constant and variable. vii. Which of the following are valid C variables? Give the reason if not a valid variable. area, 5x, Sum, net pay, float, _age, else, case, size22, my_weight viii. What are reserved words? Why they should not be used as variable names? 2 Programming in C 49 ix. Why comments are used in programs? x. What is the purpose of header files in C language? Extensive Questions Q3. Describe the following High Level Languages. a) C/C++ b) Visual Basic c) C# d) Java Q4. What is C language IDE? Explain its modules in detail. Q5. What are the rules for specifying a variable name in C language? Q6. What is a preprocessor directive? Explain include# preprocessor directive in detail.

Use Quizgecko on...
Browser
Browser