Presentation is loading. Please wait.

Presentation is loading. Please wait.

CHAPTER 2 Basic Elements of a Computer Program.

Similar presentations


Presentation on theme: "CHAPTER 2 Basic Elements of a Computer Program."— Presentation transcript:

1 CHAPTER 2 Basic Elements of a Computer Program

2 Chapter Outline Identifier, variable, constants and reserved words
Rules for naming identifiers Declaring data variables and constants Basic data types –integer, float, double, bool, char , string Arithmetic operators – addition, subtraction, multiplication, division, modulus Assignment expression

3 Chapter Outline Precedence & associatively Assignment statement
Introduce some mathematical library functions Input/output statement Formatting output Programming process, debugging and error handling Three types of control structure – sequential, selection, repetition/looping

4 Chapter Outcome At the end of this chapter, student should be able to:
Identify the basic elements needed in writing a program Understand and apply the input/output statement Justify the process of error handling Write a simple program

5 constants and reserved words
Identifier, variable, constants and reserved words Names created by the programmer to variables, constants etc. Use meaningful and descriptive identifiers to make a program easier to understand. An identifier in C++ is case sensitive. For example, the identifier Area is not the same identifier as area or AREA. 

6 Rules for naming identifier
An identifier may contain letters, numbers and only the special character underscore (_). Must begin with a letter or underscore and may NOT begin with a number. An identifier may NOT contain blanks (no space between identifiers) An identifier may NOT be a special/reserved word. No identifier may be declared twice in the same declaration part.

7 Rules for naming identifier
Legal Variables Illegal Variables total3 num age ABC35 2small _result $dollar value123all dollar 4 constage total# All_sum 10days big13 %rate profit12all good day

8 Exercise 1 Identifiers Valid/Not valid courseFile reg# 1stprize
tot_hour Main play-again _amount switch 321go valid not valid Exercise 1

9 Exercise 1 Identifiers Valid/Not valid AveRageNum void INT Total Num
sUm123 &Volume All*price Take123a valid not valid Exercise 1

10 Special Symbol /Syntax Rules
To write a meaningful program, you must learn the programming language’s special symbol & words and syntax rules. The syntax rules tells you which statements (instructions) are legal, or accepted by the programming language, and which are not. Like in any language (spoken or artificial) some words in C++ have a fixed meaning. In programming languages these words are called special / reserved words Special words & symbol state by C++ have their own special meaning which refers to appropriate instruction. This word that cannot be used as a variable name.

11 Special Symbol /Syntax Rules
Example: Special Symbol Special Word (Keyword) * / ; <= void, include, int

12 Special Symbol /Syntax Rules
Sample of Keyword asm default goto register throw auto delete if return try break do inline short typedef case double int signed union catch else long sizeof unsigned char enum new static virtual class extern operator struct void const float private switch volatile continue for protected template while friend public this Example:

13 Declaring data variables and constants
#include <iostream.h> void main() { int val1 = 8; int val2 = 5; int result; result=val1*val2; cout<<”The multiplication for<<val1<<” and ”<< val2 << “ is : ” << result <<endl; } VARIABLE Declaration Statements Initialize DATA TYPE

14 Declaring data variables and constants
Can be used to store data in a program. They can also be seen as names associated with a particular memory location in the memory of the computer. A data structure that holds data that can change while the program is running. When programming in C++, you must select a type of variable called a data type that best fits the nature of data itself.

15 Declaring variables Need (compulsory) to be declared in a program's declaration part in order to be used in the statement part. To declare any variable, we need to specify the type and followed by variable. Declaring a variable must include with data type followed by the name of variable, and a semicolon. Syntax: type variable_name;

16 Declaring variables Example: int day; //Declare day as integer.
float average; //Declare average as float. double salary; //Declare salary as double char icnum[50]; //Declare icnum as string. string address=""; //Declare address as string. char operation; //Declare operation as character.

17 Declaring variables Example: void main( ) { float num1 = 15.5;
int num2; double results; }

18 Constant Provide a way to define a variable which cannot be modified by any other part in the program code. Can be defined by placing the keyword const in front of any variable declaration. May not have its value changed while the programming is running. Constant are usually define in capital letter. Example to define a constant: const int DAY_PER_WEEK = 7;

19 Constant Constant is a value that never changes -> fixed value.
Example: Replaced with: const double PI=3.142; = 3.142

20 Constant All constant and variables to be used in a C++ program must be defined prior their use in the program. The reason that we must defined: First, the compiler must know the value of a constant before it is used and must reserve memory location to store variables. Second, the compiler must know the data type of the constant and variables so that it knows their attributes and behavior.

21 Constant Defining Constant General form of const declarations
const data type const identifier = constant value; //program to calculate the volume of a sphere using constant #include <iostream.h> #include<math.h> void main() { double volume, radius; const double PI = 3.142; cout<<”Enter the radius of a sphere:”; cin>>radius; volume=4.0/3.0* PI*pow(radius,3); cout<<”The volume of a sphere is:”<<volume<<endl; } variable declaration const declaration

22 Statement A fundamental unit of C++ programming.
Many C++ statements must be ended with a semicolon ; (crucial part of syntax but very easy to forget - syntax error). Executable Statements Cause computer to perform some operations. Example of a statement in C++: total=num1+num2; cout << age;

23 Basic Data Types Variable integer, float, double, bool, char,string
floating number Character String Bool Abu bin Ahmad No1 Lorong 1, Taman Jaya, Prai, Penang Variable

24 Data Types int age; age= 17; float tax; tax= 0.06; Numeric Data Type
Integer Whole number – positive, zero or negative C++ keyword int, long Floating point Numbers with decimal points float, double int age; age= 17; float tax; tax= 0.06;

25 Data Types char grade; grade= ‘A’; char name[10]; string CompanyName;
Character Data Types Single character Store one character value C++ keyword char String of characters Store string – sequence of characters terminated by a null character char [ ], string char grade; grade= ‘A’; char name[10]; string CompanyName; strcpy(studName, “izara”);

26 Data Types iii. bool Used only for true or false bool result=false

27 Data Types Example: Character Data Types (char)
//program to enter a string of name with the length 10 #include <iostream.h> void main() { char name[10]; cout<<“Please enter your name:”; cin.getline(name,10); cout<<name<<endl; } OUTPUT: Please enter your name:Dhia Arina Dhia Arina

28 Data Types The difference between Integer, Floating Point and Character Data Type Data Type Integer Floating Point Character We use integer data types when working with +’ve and –’ve whole numbers as a variable. Decimal numbers as a variable. Character or symbol as a variable. int float, double, char Example: int amount=15; float price =3.5; char sym= ‘#’;

29 Data Types Example: Type Description int i;
Make a variable named i of type integer long id; Make a variable named id of type long char cal = ‘*’; Make a variable called cal and store character * in it. double Area =23.65; Make a variable Area, and put some numbers in it. char phoneno[20]; Makes a char array that has 20 as it size. bool final=true; Make a variable name final with type bool and assign true in it.

30 Data Types - String A string is simply a collection of characters.
Example of a string is your name, address or phone number. String in C++ always enclosed in double quotes(“ ”) C++ provides a string class that defines what a string should be as well as operations that can be used on string.

31 Data Types - String To use string class, make sure you include the below header files: #include<iostream> #include<string> using namespace std;

32 Example: header file string string declaration string input
#include<iostream> #include<string> using namespace std; void main() { string name; cout<<“Please enter your name:”; cin>>ws; getline(cin,name); cout<<“Your name is”<<name<<endl; } header file string string declaration string input OUTPUT: Please enter your name:Hadi Fitri Your name is Hadi Fitri

33 Arithmetic Operators Defined in C++
Example Addition + = 29.5, or =34 Subtraction - 35 – 13 = 22, or = 46.4 Multiplication * 13*7 = 91, or 25.6*2= 51.2 Division / 15/2 = 7 , or 15.0/2 = 7.5 Modulus (remainder) % 12%3=0 or 32%3=2 Never use the modulus with floating-point values.

34 Arithmetic Operators Modulus Division
Specified with the percentage sign (%). The operation that gives the remainder of a division of two integer values.

35 Arithmetic Operators Example 1: Example 2:

36 Arithmetic Operators Expression Output 12+25 37 16-3 13 15 * 2 30
35/ 7 5 29 / 3 9 31.0 / 2 15.5 6 / 2.5 2.4 8.0 / 100 0.8 12 % 4 18 % 5 3

37 Arithmetic Expression
Variables and constants of integral and floating point types can be combined into expressions using arithmetic operators. In C++, we have to represent the algebraic expression by using the valid syntax. At a low level, a computer is not able to perform an arithmetic operation on two different data types of data.

38 Arithmetic Expression
In general, only variables and constants of the same type should be combined in an expression. The compiler has strict type checking rules to check for this. In cases where mixed numeric types appear in an expression, the compiler replaces all variables with copies of the highest precision type. Just as there is a need for a hierarchy of operations, there is also a need for a hierarchy of types.

39 Arithmetic Expression
The hierarchy of data types in C++ is: highest double float integer lowest

40 Arithmetic Expression
Mixed-type Expression In a mixed-type expression like (2 / 4.0), the operand lower in hierarchy gets promoted to the higher type before the operation is carried out. So, the expression (2 / 4.0) is converted to (2.0 / 4.0) before the division is performed. The division is, therefore, float division which results in the float value of 0.5. If one operand has a long, double, or signed modifier, the other is promoted as well.

41 Arithmetic Expression
Type changes can be made explicit by placing the value to be changed in parentheses and placing the name of the new type before it. This is called type casting or type conversion. Syntax: (type) expression; type (expression);

42 Arithmetic Expression
Example 1: int y; double x; x = 3.4; y = 12; Expression Output x = (int)(x + y) 15 x = x + (double)y 15.4 x = (int) x % y 3 x = (int)x + y

43 Arithmetic Expression
Example 2: Algebraic Expression Arithmetic Expression 14– 56– 9 2 56 – 9 /2 ( ) /2 52 pow ( 5 , 2 )  ( a – b) sqrt (a – b )  x – y  abs ( x – y )

44 Arithmetic Expression
Example 3: #include <iostream.h> void main() { int no1 = 15.5; int no2 = 2; int div; div = num1 / num2; cout<<”The total number is:”<<div; } Way to write the arithmetic operation. The formula (arithemetic operation) should be written before calling the output for display

45 Precedence & Associativity
When more than one operator will be executed to determine the result, C++ executes the arithmetic operators in the following order: Operator (s) Operation Precedence ( ) parentheses Evaluated first, inside-out if nested or left to right if same level *,/,% Multiply,Divide, Modulus Evaluated second, left to right +, - Add, Subtract Evaluated last, left-to-right

46 Precedence & Associativity
Example: a) – 4 / 3 means ( ) – ( 4 / 3) = ( ) – 1 ( evaluate / ) = ( evaluate +) = 4

47 Precedence & Associativity
Example: b) 3 * 7 – * 5 / 4 + 6 means ( 3 * 7 ) – 6 + ( ( 2 * 5 ) / 4 ) + 6 = 21 – 6 + ( 10 / 4 ) + 6 ( evaluate * ) = 21 – ( evaluate / ) = ( evaluate - ) = ( evaluate first + ) = 23 ( evaluate += result)

48 Precedence & Associativity
Example: c) * 4 % 5 – 3 * 2 (evaluate operators from left to right) means 10 + ( 4 * 4 % 5 ) – ( 3 * 2 ) = – (3*2) ( evaluate * , %) = ( evaluate * ) = 5 ( evaluate +-= result)

49 Assignment Statement It is essential that every variable in a program is given a value explicitly before any attempt is made to use it. It is also very important that the value assigned is of the correct type. The most common form of statement in a program uses the assignment operator, =, and either an expression or a constant to assign a value to a variable: variable = expression; (eg: int num=6)                          variable = constant;  (eg: const double PI=3.142)                 

50 Assignment Statement The assignment statement may be used to give a variable its first value in a program. This first value assignment is called initialization, and in C++ all variables must be explicitly initialized. In C++ here is how it is done: //price is declared to be of n type double double price; */Now the memory cell named price contains the value 59.99*/ price = 59.99;

51 Assignment Statement The declaration statement and initialization can be combined into one statement as follow: double price = ;

52 Assignment Statement  A variable can store only one value at a time. Suppose mark, a variable of type float, the following statements executed in sequence mark= 85.5 mark = 75.5; First, the value 85.5 will be assigned to mark and then assign the value 75.5 to mark. The value 85.5 would be lost and score would retain the value 75.5.

53 Assignment Statement Two variables can also store the same value. Suppose num1 and num2 are of type int. Then the following statements cause the number stored in the location reserved for num1 to be fetched from memory and stored in the location reserved for num2. The contents of num1 are unchanged. num1 = 65; //the value of num1 is 65 num2 = num1; //the value of num2 takes the value of num1=65 Note that only a variable name may appear on the left side of the equal sign in an assignment statement.

54 Assignment Statement Example 1: #include <iostream.h>
void main() { int x, y; x = 6; y = 2 + x; cout<<”x is:”<<x<<” and y is:”<<y<<endl; }

55 Assignment Statement Example 2: //calculate volume of a pyramid
#include <iostream.h> void main() { int height; int base; double volume; cout<<”Enter height : “; cin>>height; cout<<”Enter base : “; cin>>base; volume = 1/3.0*height*base; cout<<”Area of a pyramid is :”<<volume<<endl; }

56 Assignment Statement When we write the program, sometimes we need to modify certain value for any variable, which is the origin value is added or multiply and then the result will be assigned into the origin variable. For example: total = total + 7; When this sequence of symbols is used as an assignment statement in C++ the interpretation is different. The statement above is interpreted by the compiler as: Retrieve from memory the contents of memory cell count. Add five to that number (the value of count). Store the result in the memory cell named count.

57 Assignment Statement Assignment operators store a value in memory.
The value is stored at a location in memory that is accessed by the variable on the left-hand side of the assignment operator. Example, by considering this statement x= x+1 OR x++ It means to add one to x and then assign the resulting value back to x. Another examples: x =6 means value of 6 is assign to x variable x ==6 means x equal to 6

58 Assignment Statement In C++, this statement can be represented by using compound operator. Refer to the following table: Operation Symbol Example Equivalent to Simple assignment = y =1; y=1; Addition/ assignment += y+=10; y= y +10; Subtraction/assignment -= y-=2; y=y -2; Multiplication/ assignment *= y*=5; y=y*5; Division/ assignment /= y/=2; y=y/2; Modulus/ assignment %= y%=2 y=y%2

59 Assignment Statement Increment and Decrement Operator (Postfix & Prefix) Operator Name Operator Meaning Increment postfix a++ a=a+1 Increment prefix ++a Decrement postfix a-- a=a-1 Decrement prefix --a

60 Assignment Statement Example 1: Answer First: 6 Second: 5 Third: 7
#include<iostream.h> void main() { int x=5,y; //value of x will not be increased before assignment y = x++; cout << "First: << x << endl ; //after expression value of x is increased cout << "Second:" << y << endl; //Value of a will be increased before assignment y=++x; cout << "Third:" << y << endl; }

61 Assignment Statement Example 2: Answer 7 8 8 7 9 6
#include<iostream.h> void main() { int a = 7, b = 8; cout << a << " " << b << endl; cout << ++a << " " << --b << endl; // prefix cout << a++ << " " << b-- << endl; // postfix } Answer 7 8 8 7 9 6

62 Mathematical Library Functions
Mathematical function perform an arithmetic operation All the arithmetical function from math.h header file are listed in the following table:

63 Mathematical Library Functions
Function name Operation sqrt() Return the square root of the argument pow(x,y) Return x raised to the power of y pow10(y) Return 10 raised to the power of y sin() Return the sine of argument (radiant) hypot(a,b) Return the hypotenuse of a right triangle whose sides are a and b tan() Return the tangent of the argument (radians) log() Return the natural log of the argument Log10() Return the base 10 log of the argument abs() Return the absolute value of argument

64 Mathematical Library Functions
Example: #include <iostream.h> //standard stream I/O library #include<math.h> //standard math library void main() //start of function main { double number, power, squaroot; //define variable cout<<”Enter a number:”; //Ask user to enter number cin>>number; squaroot=sqrt(number); //calculate root power=pow(number,3); //calculate square cout<<”Number=”<<number<<endl; cout<<”SquareRoot=”<<squaroot<<endl; cout<<”Power=”<<power<<endl; } OUTPUT Enter a number: 9 Number=9 SquareRoot=3 Power=729

65 Input / Output Statement
Provides fundamental input and output capability Getting data into the system is called (input) reading. besides getting data from users, data from problems can be done in 3 ways: initialize the value (changes can be done to the value) OR declare the value as constant (changes cannot be done to the value) OR assign the value directly into the formula

66 Input / Output Statement
Generating data from the system is called (output) writing. By using input and output object, you will ready to write some interactive C++ programs Provided to C++ programmers by the standard library, which is a part of all C++ implementation. This capability can be done by including a header files: #include<iostream.h>

67 Using cin statement To get data from user and store into a variable
Standard input stream, cin, is used to represent input statement The cin statement is used to get input from the user using the keyboard. The stream extraction operator, >> is capable of handling all of the basic data types in a way that is transparent to the programmer. The general format for cin statement is as follow: cin >>num1; cin>>num1>>num2;

68 Using cin statement Other examples of cin statement :
cin >> xNum; cin >> theResults; cin >> thistotal; If input of more than one data element is desired in one statement, the stream extraction operator can be concatenated as follows: cin >> xNum >> theResults >> thistotal;

69 Used for strings of characters
Using cin statement To get data from user and store into a variable Standard input stream, cin, is used to represent input statement Syntax: cin >> variable_name; cin.getline(variable_name, size); OR getline(cin,variable_name); Used for number & characters Used for strings of characters Used for strings

70 Displaying cin statement
Example: #include <iostream.h> void main() { int age; char grade; char name [10]; //ask user to input string cout<<”Please enter your name:”; cin.getline(name, 10); //ask user to input age cout<<”Please enter your age:”; cin>>age; // ask user to input grade cout<<”Please enter your grade:”; cin>>grade; }

71 Using cout statement The cout statement is used to display output.
The general format for cout statement is as follow: i. cout<<item1<<item2<<…. <<itemn; (the value of the item will be displayed) OR ii. cout<<“statement”; (the word “statement” will be displayed)

72 Using cout statement cout is followed by the list of item to be written, which are separated by the << (stream insertion operator) The best way to understand how cout works is to look at the output generated by several different cout statement. cout<< 120; cout<< 18 -8; cout<< ‘Y’; Fixed Character Information cout<< “Welcome!”; cout<<total<<price Variable Information

73 Displaying cout statement
Example: #include <iostream.h> #include<math.h> void main() { int age; age=28; cout<<”Welcome to CSC128 class”;//displaying string cout<<age; //displaying variable value cout<<5*2+3; //displaying expression value cout<<pow(4,2); //displaying mathematical function }

74 Numbers, Characters and String
OPERATOR INTEGER NUMBER FLOATING POINT NUMBER CHARACTER STRINGS (using char[ ] ) ( using string) Declare int age; double price; char dollar; char name[15]; string idno; Input cin>>age; cin>>price; cin>>dollar; cin.getline (name,15); getline (cin,idno) Assign (initialize) age=21; price=2.99; dollar=‘$’; name=‘M’,’I’,’A’; strcpy(name,”MIA”); idno=“23456” Output cout<<age; cout<<price; cout<<dollar; cout<<name; cout<<idno;

75 DO NOT USE FORMATTING OUTPUT IN cin STATEMENT!
C++ allow output formatting using special commands within the cout statement. endl means “end-of-line”, it’s used to move the cursor to the next line right after that word. cout<<“ All the Best!”<< endl; cout<<“ Congratulation..”; DO NOT USE FORMATTING OUTPUT IN cin STATEMENT! OUTPUT All the Best! Congratulation..

76 Escape Sequence Escape sequences symbol also can be used to format the output To use these escape sequence, simply include them as part of a string or insert as single character.

77 Escape Sequence Escape Sequence Meaning \n
newline - go to the next line \t horizontal tab \a Alert/ beep \\ print a backslash character \" print a double quote character \' print a single quote character

78 Escape Sequence Display the output as below using escape sequence:
Example of Escape Sequence cout<< “Simon says.\”Knock your head.\””<<endl. Output: Simon says. “Knock your head.” Exercise 1: How to print: ‘My name is ‘Dayana’ By using only one cout object Display the output as below using escape sequence: Name Address Phone

79 I/O Manipulator To format the field of output screen, we must use setw( ) I/O manipulator contained in the iomanip.h header file. This header file allow you to manipulate the output stream to obtain some desired effect.

80 I/O Manipulator Below are some list of I/O manipulator: Manipulator
Action setw(n) Set field width to n setprecision(n) Sets floating-point precision to n setfill(n) Sets fill character to n

81 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 address and person’s phone number.

82 I/O Manipulator cout<<“\n\n” // skip 2 lines
<<setw(15)<<“NAME” // display heading <<setw(22)<<“ADDRESS” <<setw(23)<<“PHONE”<<endl; cout<<setw(15)<<“----” // display underline <<setw(22)<<“ ” <<setw(23)<<“-----”<<endl; Output Screen: 15 column 22 column 23 column PHONE NAME ADDRESS

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

84 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.

85 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.

86 I/O Manipulator Example 1: #include <iostream.h>
#include<iomanip.h> void main() { //initialize variable with a value double voltage=0; double current=0.01; double resistance=5200.0; //calculate voltage voltage=current*resistance; cout<<”\n\n\n”;//create 3 lines spacing cout<<setw(20)<<”CURRENT”; cout<<setw(20)<<”RESISTANCE”; cout<<setw(20)<<”VOLTAGE”<<endl; //Display heading underline cout<<setw(20)<<” “; cout<<setw(20)<<” “<<endl; //display values cout<<setw(20)<<setfill(‘*’)<<current; cout<<setw(20)<<resistance; cout<<setw(20)<<voltage<<endl; } OUTPUT CURRENT RESISTANCE VOLTAGE ****************0.01****************5200*********************52 Example 1:

87 I/O Manipulator Example 2: #include <iostream>
#include<iomanip> #include<string> using namespace std; void main() { string item1=""; string item2=""; double price1,price2,total; cout.setf(ios::fixed); cout.precision(2); cout.setf(ios::left); //item 1 cout<<"Enter item 1:"; cin>>ws; getline(cin,item1); cout<<"Enter price for item 1:RM"; cin>>price1; Example 2:

88 I/O Manipulator Example 2 cont’d: //item 2
cout<<"\nEnter item 2:"; cin>>ws; getline(cin,item2); cout<<"Enter price for item 2:RM"; cin>>price2; total=price1+price2; cout<<setw(20)<<"ITEM"<<setw(20)<<"PRICE"<<endl; cout<<setw(20)<<" "<<setw(20)<<" "<<endl; //display values cout<<setw(20)<<item1<<setw(20)<<price1<<endl; cout<<setw(20)<<item2<<setw(20)<<price2<<endl<<endl; cout<<setw(20)<<"TOTAL"<<total<<endl; }

89 I/O Manipulator Example 2: output

90 Programming Process, Debugging and Error Handling
The process of tracing, identifying and correcting errors in the programs is called debugging. Compiling Before debugging, users need to compile their program first. Compile is done once users have finished writing a program. Use the steps below to compile a program:

91 Programming Process, Debugging and Error Handling
After writing the program, click the compile button as shown in the figure below:

92 Programming Process, Debugging and Error Handling
After compile , if there is an error in the program , it will appear in the bottom part as shown below:

93 Programming Process, Debugging and Error Handling
To identify the location of the error, double click on the error statement. An arrow will appear on the left side of the program statement which contains error.

94 Programming Process, Debugging and Error Handling
After correcting (process called debugging) the errors ,we have to compile again the program until the message shown there is no errors in the program

95 Programming Process, Debugging and Error Handling
Types of Error 1. Syntax errors Errors related with violations of syntax rules. 2. Logical errors Errors in the logic of a program. Output produced is wrong 3. Run time errors Errors caused program instructions that require the computer to do something illegal such as an attempt to divide a number by 0. In this case, the implementation of program will stop automatically and display a certain messages.

96 Programming Process, Debugging and Error Handling
Example:  Syntax errors Logical errors Run time errors Example : cout <<“Hi”. int tot age; cin<<num; int x=2,y ; cout<<y; y= x + 2 Output: a=1; b=0; result=a/b; cout<<“RESULT=”<<result;

97 Three Types Of Control Structure
A control structure is simply a pattern for controlling the flow of a program module. 4 fundamental control structure of programming language are: Sequence - Statements are executed in the order in which they have appear Selection (decision) - The next statement to be executed is based on a condition Iteration (looping) - The repetition of a statement or a group of a statement

98 Three Types Of Control Structure
Sequential Statements are executed in the order in which they have appear Selection The next statement to be executed is based on a condition Iteration The repetition of a statement or a group of a statement

99 Three Types Of Control Structure
Sequential Control Structure Is a series of steps or statements that are executed in the order in which they are written in algorithm. Used for problem that is not based on the certain condition and not repeating. Sequence control structure is a series of sequential step-by-step statement. Thus, compiler will compile their statements sequentially, one after another in a straight-line fashion Statement Statement 2 Statement 3

100 Three Types Of Control Structure
Selection and Iteration Control Structure Allow flow of program to be altered, depending on one or more Boolean condition. Selection/decision control structure is a decision-making control structure and is implemented using if, if/else and switch statements. Iteration/Repetition control structure is a repetition control structure and is implemented using while, do/while and for statements.

101 Question 1: G=4*pow(PI,2)*(pow(a,3)*(pow(p,2)*(x+y)))
Write a C++ assignment statement for each of the following algebraic equation Algebraic Expression Assignment Statement G=4*pow(PI,2)*(pow(a,3)*(pow(p,2)*(x+y))) V=(pow(a,2)/pow(b,3)*sqrt(S*(S-a)))+c*d K = (L + M3 + 5RB) / 3FC2 K=(L+M*3+5*R*B)/(3*F*C*2)

102 Question 1: Z=5*pow((x+y),x+3)/(2*m*n) FV=PV*pow((1+INT/100),YEARS)
Algebraic Expression Assignment Statement Z=5*pow((x+y),x+3)/(2*m*n) FV=PV*pow((1+INT/100),YEARS) C=2*x*y+1/4.0-3*a/b

103 Question 1: F=k*((M1*M2)/pow(d,2)) T=2*PI*sqrt(m/k)
Algebraic Expression Assignment Statement F=k*((M1*M2)/pow(d,2)) T=2*PI*sqrt(m/k)

104 Question 2: Evaluate the following expressions. Given 23.0 /23 144.0 /144 17.5 19.0/ 19

105 Question 3: Answer: -15

106 Question 4: -2 9 39

107 Question 5: Write an appropriate declareration statement to accomplish each of the following tasks. 1. A floating point variable name gov_tax and initialize 6% to it. float gov_tax=0.06; 2. A string variable named company and assign "ABC SPORT VENTURE". string company=“ABC SPORT VENTURE”; 3. A variable name CodeNum and assign 1 to it. int CodeNum=1; 4. A double variable name Percentage double Percentage; 5. A constant named gravity and assign 9.8m/s2 to it. const float gravity=9.8; 6. A constant named DISCOUNT_RATE and initialize it with 0.07. const double DISCOUNT_RATE=0.07;

108 Question 6: Write assignment statements that perform the following operations with the variables x,y,z. Adds 3 to x and stores the result in y. y=3+x; 2. Multiplies y times 5 and store the result in x. x=y*5; 3. Divides x by 2 and stores the result in y. y=x/2; 4. Substracts 6 from y and stores the result in x. x=6-y; 5. Store the value 39 in x. x=39; 6. Store the character ‘J’ in z. x=‘J’;

109 Question 7: Write C++ statement(s) to perform the following tasks. Declare necessary variables if needed. Prompt the user to input a student_name and then display the name with a message just like the sample below. Hello, Alia! Welcome to UiTM Malaysia. cin.getline (student_name,30); OR getline(cin,student_name); cout<<“Hello, “<<student_name<<“! Welcome to UiTM Malaysia”<<endl; Prompt the user to input the diameter of a circle. Calculate the area of the circle. Then, display the radius and the area of the circle. cin>>circle_d; radius=circle_d/2; area=PI*pow(radius,2); cout<<radius<<“ “<<area;

110 Question 8: Write a program which input b and h from user then calculate the value for A and display it. Use the formula given to calculate A. A=bh (A-Area of parallelogram, b-base,h-height) #include<iostream.h> void main() { double b,h, A; cout<<“Enter base and height:”; cin>>b>>h; A=b*h; cout<<“The area is:”<<A<<endl; }

111 Question 8: A retail store grants its customers a maximum amount of credit. Each customer’s available credit is his or her maximum amount of credit minus the amount of credit used. Write a pseudocode and flowchart algorithm for a program that asks for a customer’s maximum amount of credit and amount of credit used. The program should then display the customer’s available credit. #include<iostream.h> void main() { double max,amount,cred_bal; cout<<“Enter maximum amount of credit:”; cin>>max; cout<<“Enter amount of credit used:”; cin>>amount; cred_bal=max-amount; cout<<“Credit available is:”<<cred_bal; }

112 Question 9: Trace each of the following program and produce the output int a = 0, b = 1, c = 2; a--; b++; c--; ++a; --b; ++c; cout<< a + 2 <<endl; cout<< --b <<endl; cout<< c-- <<endl; 1

113 Question 10: Trace each of the following program and produce the output int num = 4; cout<<num<<endl; cout<<num++<<endl; cout<<++num<<endl; cout<<num--<<endl; cout<<--num<<endl; 4 5 6


Download ppt "CHAPTER 2 Basic Elements of a Computer Program."

Similar presentations


Ads by Google