Presentation is loading. Please wait.

Presentation is loading. Please wait.

CHAPTER 2 components of a programming language

Similar presentations


Presentation on theme: "CHAPTER 2 components of a programming language"— Presentation transcript:

1 CHAPTER 2 components of a programming language
Introduction To Computer Programming (CSC425) CHAPTER 2 components of a programming language

2 Contents Variable Definition - Identifier, variable, constant - Standard data type (int, float, double, char) - Input/output structure - C++ block structure

3 At The end of this class, student should be able to:
Identify the basic elements needed in writing a program

4 Introduction Computer program: sequence of statements (instructions) designed to accomplish some task Programming: planning/creating a program Syntax: rules that specify which statements (instructions) are legal Programming language: a set of rules, symbols, and special words

5 C++ block structure // Introductory comments // file name, programmer, when written or modified // what program does #include <iostream.h> void main() { constant declarations ; variable declarations; executable statements ; }

6 Example of C++ program:
//A simple C++ program #include <iostream.h>  compiler directive/header file void main( ) main function { //display greeting message comment cout<<”Welcome to CSC 425 class”; statement } OUTPUT Welcome to CSC 425 class

7 Comments Important part of a program's documentation.
It is used to explain the purpose of a program. Explain the parts of program and keep note regarding changes to the source code. Describe about the reason of the program and understand the program more clearly. Increased the user understanding of the program. Store the names of programmers for future reference. Used to make program documentation.

8 Comments Can be used in 2 ways: Using /* */ symbol
Used for one or more than one line of comments in group Example: /* This is the example of comment in C++ program. This is the second line */

9 Comments 2. Using // symbol Used only for one line Example:
// This is example of comments // This is the second line

10 Preprocessor Directive
A line of code that begins with the # symbol.   Are processed by preprocessor (which is usually bundled into the compiler) before compilation. Are not executable code lines but instructions to the compiler. Each header file stores functions that are related to a particular application. The directive #include <iostream.h> tells the preprocessor to include the contents of the file <iostream.h>, which includes input-output operations (such as printing to the screen). 

11 Function Main Function
Every C++ program contains one or more functions, one of which must be named main. Every C++ program has a main function. A function is a block of code that carries out a specific task. The word main is followed in the code by a pair of parentheses ( ).

12 Function Braces Right after these parentheses we can find the body of the main function enclosed in braces { }. What is contained within these braces is what the function does when it is executed. Braces used to mark the beginning and end of blocks of code. The open braces ({ ) are place in the beginning of code after the main functions and close braces ( }) are used to show closing of code. The code after the ( }) will not be read/evaluate by compiler

13 Function Statement A function consists of a sequence of statements that perform the work of the function. It consists of instructions or command which make the program work. Each statement in C++ ends with a semicolon (;). There are 3 type of statement : Input statement- cin>>statement; Output statement-cout<<“statement”; Operation statement-mathematical operation

14 VARIABLE DEFINITION Operation done by computer Receive input
Produce output Assign value into storage Perform arithmetic and logic operation Make selection Repeating a set of actions

15 Program Elements Generally a computer program has the following elements: Input section Storage allocation Constants Variables Files Processing using arithmetic or logic operation and control with either sequential, selection or and repetition structure. Output Section

16 Program Elements Processing Input Output Storage
int number1, number2, total; cin >> number1 >> number2; total = number1 + number2; cout << total << endl Arithmetic Logic cin >> number1 >> number2; Processing cout << total << endl total = number1 + number2; Input Output constant Storage variable int number1, number2, total;

17 Storage One of the essential resource of a program
A location in computer memory that is allocated to the program Used to hold value of specific data type Categories: Constants Variables Files Data Types Integer number Floating point number Character Identifier is the name given to specific storage

18 Identifiers Example: int number; Data type Identifier

19 Identifiers Identifier naming rules: Examples of valid identifiers
Must begin with a letter or _ Can be followed by a letter, number or underscore (‘_’) Cannot have space in between Cannot have keywords Examples of valid identifiers number1 averageScore latest_CGPA Examples of invalid identifiers 20score Student’sAge average Salary

20 Constant identifiers Constant To hold fixed value that cannot be altered during program execution. Examples: PI value  Number of days per week  7 Constant declaration: const keyword is used to declare a constant and it must be initialized. Example: const double PI = ; const <data type> <identifier> = value;

21 Variables DataType identifier, identifier, . . .;
To hold value that might be altered during program execution. Hold value on temporary basis Examples: score Temperature Speed Length The syntax for declaring one variable or multiple variable is : Example: int number; float score1, score2; int score; float number; int count = 0; //initialize count to 0 DataType identifier, identifier, . . .;

22 Data types Basic Data Types C++ Data Types Examples int score;
Integer (90, 0, -78) int Floating point (4.5,1.0,-0.67) float or double Character (‘A’,’a’,’*’,’1’) char, char…[10] String (“Ali”, “Anson Road”) string Examples int score; float temperature; double accountBalance; char gender; char name[15]; string name=“”;

23 int DATA TYPE Memory allocated for the int type is 4 bytes
signed: to unsigned: 0 to Examples: -6728 78 Positive integers do not have to have a + sign in front of them No commas are used within an integer Commas are used for separating items in a list

24 Floating-Point Data Types
C++ uses scientific notation to represent real numbers (floating-point notation)

25 Floating-Point Data Types (continued)
float: represents any real number Range: -3.4E+38 to 3.4E+38 (7 digits) Memory allocated for the float type is 4 bytes Float values are called single precision double: represents any real number Range: -1.7E+308 to 1.7E+308 (15 digits) Memory allocated for double type is 8 bytes Double values are called double precision Precision: maximum number of significant digits

26 char DATA TYPE The smallest integral data type
Memory allocated for the char type is 1 byte Used for characters: letters, digits, and special symbols Each character is enclosed in single quotes Some of the values belonging to char data type are: 'A', 'a', '0', '*', '+', '$', '&' A blank space is a character and is written ' ', with a space left between the single quotes Find the range of char datatype?

27 string Data Type Programmer-defined type supplied in standard library
Sequence of zero or more characters Enclosed in double quotation marks Null: a string with no characters Each character has relative position in string Position of first character is 0, the position of the second is 1, and so on Length: number of characters in string

28 Data Types - String #include <iostream> OUTPUT
#include<string> using namespace std; void main() { int number; string name; cout<<”Enter a number:”; cin>>number; cout<<”Enter a name:”; getline (cin, name); cout<<”Your number is:”<<number<<endl; cout<<”Your name is:”<<name<<endl; } OUTPUT Enter a number: 5 Enter a name: Ali Ahmad Your number is 5 Your name is Ali Ahmad Press any key to continue_

29 Data types - Examples Example (integer) #include <iostream.h>
void main() { int num1, num2, sum; cout<<"Enter first number:"; cin>>num1; cout<<"Enter second number:"; cin>>num2; sum=num1+num2; cout<<"The sum of two number is:"<<sum<<endl; }

30 Data types - Examples Example (float/double/const)
#include <iostream.h> void main() { const double PI=3.142; float radius; double area; cout<<“Enter radius:”; cin>>radius; area=2*PI*radius; cout<<“The area is:”<<area<<endl; }

31 Data types - Examples Example (char/char [])
#include <iostream.h> void main() { char gender; char name[15]; cout<<"Please enter your name:"; cin.getline(name, 15); cout<<name; cout<<" Enter you gender (M or F):"; cin>>gender; }

32 Data types - Examples Example (string)
#include <iostream> NOT <iostream.h> #include <string> using namespace std; void main() { string name=“”; cout<<"Please enter your name:”; cin>>ws;  remove whitespaces at the start getline(cin, name); cout<<name; }

33 Input Data must be loaded into main memory before it can be manipulated Storing data in memory is a two-step process: Instruct the computer to allocate memory Include statements to put data into allocated memory

34 Example 1 3.1416 ? ? #include <iostream.h> PI radius area
//program to calculate area of a circle main() { //variable and constant allocation const double PI = ; int radius; double area; //input section cout << “Enter a radius : ”; cin >> radius; area = PI * radius * radius; //processing //output section cout << “Area of the circle is ” << area << endl; return 0; }//end main() PI 3.1416 radius ? area ?

35 Example 1 - Output Enter a radius : __ Example: user enter number 8
Area of the circle is

36 Example 1 - Output PI 3.1416 radius 8 area 201.0624
#include <iostream.h> //program to calculate area of a circle main() { //variable and constant allocation const double PI = ; int radius; double area; //input section cout << “Enter a radius : ”; cin >> radius; area = PI * radius * radius; //processing //output section cout << “Area of the circle is ” << area << endl; return 0; }//end main() PI 3.1416 radius 8 area

37 Input and Output Statement
Input Statement To received input from keyboard or read input from a file. Using cin keyword and input stream operator (>>). Syntax: cin >> <variable>; Example cin >> number; cin >> number1 >> number2;

38 Input and Output Statement
Example of a good input statement: cout << “Enter a score : ”; cin >> score; Prompt user to enter a number Read a number

39 Input and Output Statement
To display output on screen or to write output into file. Using cout keyword and output stream operator (<<). Syntax: cout << <string/constant/variable/expression>;

40 Input and Output Statement
Examples: Statements Output cout << “Hello World”; Hello World cout << 80; 80 cout << area; content of area cout << 8 + 4; 12

41 Input and Output Statement
What is the output of the following statements? Statements Output cout << “Total is ” << 8 + 2; ? cout << “8 + 2 = ” << 8 + 2; ?

42 Input and Output Statement
End of line (newline) endl keyword will force the cursor to begin at new line. Examples: Code fragment Output cout << 14; 1416 cout << 16; cout << 14 << endl; 14 cout << 16 << endl; 16 cout << 14 << ‘\n’; 14 cout << 16 << ‘\n’; 16 cout<<“Hi”<<endl; Hi cout<<“\nHi”; Hi

43 Exercise 1 Write a program that does the following :
Prompts the user to input two decimal numbers and display the two numbers. #include <iostream.h> void main () { double a, b; cout<<“Enter two decimal number”; cin >> a>> b; cout<<“Number 1 : “ <<a<<endl; cout<<“Number 2 : “ <<b<<endl; }

44 Exercise 2 Write a program to display the following: Student name
Student MatricNo Student Program Student’s CGPA

45 #include <iostream> #include <string> using namespace std; void main () { string StudName, MatricNo, program; double cgpa; cout<<"Enter Student Name :"; cin >> ws; getline(cin,StudName); cout<<"Enter Matric Number:"; getline(cin,MatricNo); cout<<"Enter Program:"; getline(cin,program); cout<<"Enter CGPA:"; cin >> cgpa; cout<<"STUDENT NAME: "<<StudName<<endl; cout<<"MATRIC NUMBER:"<<MatricNo<<endl; cout<<"PROGRAM :"<<program<<endl; cout<<"CGPA:"<<cgpa<<endl; }

46 #include <iostream.h>
void main () { char StudName[30], MatricNo [12], program[10]; double cgpa; cout<<"Enter Student Name :"; cin.getline(StudName,30); cout<<"Enter Matric Number:"; cin.getline(MatricNo,30); cout<<"Enter Program:"; cin.getline(program,10); cout<<"Enter CGPA:"; cin >> cgpa; cout<<"STUDENT NAME: "<<StudName<<endl; cout<<"MATRIC NUMBER:"<<MatricNo<<endl; cout<<"PROGRAM :"<<program<<endl; cout<<"CGPA:"<<cgpa<<endl; }

47 Formatting Program Output
Besides displaying correct results, it is extremely important for a program to present its output attractively. To include manipulators within an output display, must include the header file using the preprocessor command as follows : #include <iomanip.h> Most commonly used manipulators in a cout statement : setw(n) - Set field width to n setfill(n) - Sets fill character to n setprecision(n) - Sets floating-point precision to n Semester Jan – Apr 2010 CSC425 : INTRODUCTION TO COMPUTER PROGRAMMING

48 I/O Manipulator Most system divides a page of text output into twenty five rows and eighty columns. Example: Suppose you want to create three column of output: person’s name, person’s student id and person’s code program.

49 I/O Manipulator cout<<“\n\n” // skip 2 lines
<<setw(15)<<“NAME” // display heading <<setw(22)<<“STUDENT ID” <<setw(23)<<“CODE”<<endl; cout<<setw(15)<<“----” // display underline <<setw(22)<<“ ” <<setw(23)<<“-----”<<endl; Output Screen: 15 column 22 column 23 column CODE NAME S T U D E N T I D

50 I/O Manipulator setfill(n)
Specifies character for blank space in field Single quotes required around character enclosed in parentheses Example: num = ; cout<<setw(10)<<setfill(‘*’)<<num; Output: ****165.48

51 I/O Manipulator Generating Left-Justified Value
Specifies character for blank space in field cout.setf(ios::left); By default, when we use setw(n) to print values or information, the values are right justified. So to put as left justify we must write the above statement.

52 I/O Manipulator Generating Decimal Point Value cout.setf(ios::fixed);
cout.precision(n); Statement cout.setf(ios::fixed) forces the compiler to generate a fixed decimal output without exponential, or e, notation. Meanwhile cout.precision(n) dictates the number of decimal places to the right of decimal point to be generated.

53 I/O Manipulator Generating Currency Output cout.setf(ios::fixed);
cout.setf(ios::showpoint); // the two means two decimal places cout.precision(2); The showpoint function forces the decimal point to always be displayed.

54 I/O Manipulator Example for set precision: #include<iostream.h>
#include<iomanip.h> void main() { double x= 123.4, y = 456.0; cout.setf(ios::fixed); cout.precision(6); cout<<x<<endl; cout<<y<<endl; }

55 I/O Manipulator #include<iostream.h> #include<math.h>
#include<iomanip.h> void main() { double circumference,area,radius; double PI = 3.142; cout<<"Enter Radius : "; cin>>radius; circumference = 2 * PI * radius; area = PI * pow(radius,2); cout.setf(ios::left); cout.setf(ios::fixed); cout.precision(2); cout<<setw(20)<<"Radius"; cout<<setw(20)<<"Circumference"; cout<<setw(20)<<"Area"<<endl; cout<<setw(20)<<"------"; cout<<setw(20)<<" "; cout<<setw(20)<<"-----"<<endl; cout<<setw(20)<<setfill('*')<<radius; cout<<setw(20)<<setfill('*')<<circumference; cout<<setw(20)<<setfill('*')<<area<<endl; }

56 I/O Manipulator


Download ppt "CHAPTER 2 components of a programming language"

Similar presentations


Ads by Google