Download presentation
Presentation is loading. Please wait.
1
Basic Elements of Computer Program
Week 2
2
Topic 2 - Outline Identifier Data types Arithmetic Operator
Arithmetic Expression Assignment Statement IO Statement C++ Program Structure Programming Process Control Structure Topic 2 - Outline
3
What? Name assigned by user
Identifier What? Name assigned by user Why? To represent programming entities such as variable, function or constant Rules? The 1st character must be an alphabet letter or an underscore ‘_’. Can only consists of letters, digits and underscore ‘_’. Cannot use C++ reserved words/keywords There must be no blank space character Identifiers are case sensitive
4
Reserved Word It has predefined meaning for the language. int char
long float double default case for void break const else if private do goto switch while public class return continue
5
Variable Rules? What? Memory location in computer.
Must begin with a letter or underscore (_), and may only contain only letters, underscore, or digits. Variable name cannot be a keyword. Variable name cannot consists of more than 31 characters. Variable What? Memory location in computer. Why? To store data/instructions How? Store a data at a time Variable value might be changed during program execution Must declare before used Must assign / initialize a value to variable before use it Rules?
6
Variable Declaration Syntax: data_type variable; Example: int x; int number1, number2, number3; Please take note of the coma to Separate the variable list & Semicolon to end the variable declaration
7
Variable: what happen when a variable is declared??
The compiler allocates a memory space for the variable. In the memory space, name, data type and value of the variable are stored. ex. Allocates a memory of 4 bytes with address the information stored in the memory space are variable name (area), data type (float). float area;
8
Constant Values that are fixed and do not change throughout program execution Declaring a constant: Using const keyword
9
Constant Declaration Syntax: const data_type constant_name = value; const float PI = 3.14; Data type const keyword Constant_name value
10
Legal and Illegal Identifiers
The following are legal identifiers in C++: first conversion payRate
11
Data Types Numeric Int Float Double Character Char
12
Numeric Data Type Integer Floating point
Whole number – positive, zero or negative C++ keyword int, long int, long long int Floating point Numbers with decimal points float, double int area; float area;
13
int Data Type 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
14
float, double Data Type Is a decimal number that contains the decimal point (.)or the exponent (e) or both. float data type can hold values up to six or seven significant digit accuracy. double data type can hold values up to 14 or 15 significant digit accuracy.
15
Character Data Type char Single character Example: char name;
Store one character value C++ keyword char Example: char name;
16
char Data Type The smallest integral data type
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
17
char[] Data Type Sequence of characters
It stores sequence of zero or more characters Enclosed in double quotation marks Null: no characters is stored. Each character has relative position Position of first character is 0, the position of the second is 1, and so on Length: number of characters in a sequence C++ keyword char[] char name[5]; Note: the double quotes and Single quotes
18
Initialization A variable can be initialized to any value as long as the value’s data type matches the variable’s data type. Syntax: datatype variable [ = initialValue ]; Examples: int age = 0; float rate = 0.0; double sale = 0.0; char grade = ‘ ’; char company[20] =“ ”;
19
SUMMARY OF DATA TYPE Category Data types Keywords Bits Range Examples
Numeric integer int 16 to 32767 45, 0, -10 long integer long 32 to -37876 floating point Float 6 digit precision 32.88, -89.5 double floating point double 64 12 digit precision Character char 8 ‘c’, ‘v’ Sequence of character char[ ] “hello”, “sarah”
20
OPERATORS A Symbol that tells the compiler to perform specific mathematical or logical manipulations Types of operator: Arithmetic operators Assignment operators Relational operators Logical operators
21
Arithmetic Operator Addition + Subtraction - Division / Multiplication
* Modulus %
22
Precedence & Associativity
Precedence of operator Precedence rules: specify which operator is evaluated first when two operators with different precedence are adjacent in an expression. Associativity rules: specify which operator is evaluated first when two operators with the same precedence are adjacent in an expression. Highest Operators Associativity () Left to right * / % Lowest
23
Precedence & Associativity
Example 1: Example 2: 4 + 2 * 3 3 * 4 / 2
24
Arithmetic Expression: Operands & Operator
One of the input of an operator Example: 3 + 6 Operator Operand
25
Several rules that you need to follow to evaluate arithmetic expression:
If one or more operand(s) in an arithmetic expression has/have data type double, the resulting expression is of data type double. If all operands in arithmetic expression are of type int, the resulting expression is of type int.
26
Arithmetic operators Require two operands Ex. +, -, *, /, %
For the modulus (remainder) operator, all of its operands must be integer only. Be careful of the operands’ data types when using division operator. For example, Expressions Output 7 / 4 1 7.0 / 4 1.75 -1 / 4 -1 / 4.0 -0.25
27
Example 3 * 7 – * 5 / (3 * 7) – 6 + ( (2 * 5) / 4 ) + 6 = 21 – 6 + (10 / 4) + 6 (Evaluate *) = 21 – (Evaluate /) = (Evaluate -) = (Evaluate first +) = 23 (Evaluate +)
28
Assignment statement Assigns a value to respective memory space allocated to a variable. May involve arithmetic expressions. Syntax: Examples variable = value/ variable; a = 3; x = 5.6; y = ‘z’; pi = 3.14; 5 = z; //invalid!!
29
Assignment statement Syntax:
The expressions may contains variables, constant and arithmetic operators, Example: variable = expression; float radius, pi, area; radius = 3; pi = 3.14; area = pi * radius * radius;
30
Assignment statement A sequence of character:
Using assignment statement: Using strcpy function: char a [20] = “sample string”; char a [20]; strcpy(a ,“sample string”);
31
Writing algebraic expression using C++ statement.
Algebraic statement pow(a,b) ab sqrt(a - b) √ (a – b) abs(x - y) | x – y |
32
Arithmetic Expression
Examples Algebraic Expression Arithmetic Expression 17– 23 – 7 5 23 – 7 / 5 4 ( ) / 4 42 pow ( 4 , 2 ) ( a – b) sqrt (a – b ) x – y abs ( x – y )
33
Examples: -b ± √b2 – 4ac 2a Solution : Or
-b + sqrt ((pow (b,2) – (4 * a * c))/(2 * a) Or -b - sqrt (b * b – 4 * a * c) / (2 * a)
34
IO Statement: Output statements
Used to display information on screen. The header file iostream.h must be included in the preprocessor directives. Syntax: The symbol << is called insertion operator cout<<variable<<variable<<…<<variable;
35
Output statements Sample output: … year = 1999;
cout << “my year of birth is”<<year; my year of birth is 1999
36
cout << (2003 – year);
Output statements The operand after the symbol << can be a constant, variable or an expression. The following are escape sequence which can be used in a string literal in a cout statement. cout << (2003 – year); \n – new line \’ – single quote \t - tab \” - double quote \b - backspace \\ - backslash
37
IO Statement: Input statement
Used to read in information from a keyboard. Syntax: The symbol >> is called an extraction operator. The operand after the symbol >> must be a variable. cin>>variable>>variable>>…>>variable;
38
Input statement: example
… cout << “enter your age and matric number:”; cin>>age>>matric;
39
Input statement cin only takes input up to the first blank (ignores whitespace such as blanks, tabs). When reading a sequence of character (including whitespace), used: cin.getline(name, 20);
40
Example Using cin statement: Sample output
cout<< “Enter your name:”; cin>>name; cout<< “Welcome, ”<<name<<“!”; Enter your name: Adam Ahmad Welcome, Adam!
41
Example Using cin.getline statement: Sample output
cout<< “Enter your name:”; cin.getline(name,20); cout<< “Welcome, ”<<name<<“!”; Enter your name: Adam Ahmad Welcome, Adam Ahmad!
42
C++ Program Structure Components of the program
Preprocessor directives Constant and type definition section Main program heading Begin block Main block Declaration section Statement section End block
43
Syntax #include <headerFileName> const <dataType><identifier> = <value> dataType <identifier> <functionType> <functionName> (formal parameter list) { cout << statement; cin >> variables; }
44
A C++ program is a collection of one or more subprograms, called functions
A subprogram or a function is a collection of statements that, when activated (executed), accomplishes something Every C++ program has a function called main
45
Preprocessor directives
Examples: #include <iostream.h> To declares the basic C++ streams (I/O) routines. #include <math.h> Declares prototypes for the math functions and math error handlers. #include <conio.h> Declares various functions used in calling the operating system console I/O routines.
46
Example of program Preprocessor Directives main function
#include <iostream.h> #include <conio.h> #include <string> void main() { string name; int age; cout<< "Please enter your name:\n"; cin>>name; cout<< "Please enter your age:\n"; cin>>age; cout<<endl; cout<< "Your name is:"<<name<<endl; cout<< "Your age is:"<<age<<endl; getch(); } Preprocessor Directives main function
47
Programming process
48
Compilation process
49
Running a program
50
Control Structure: Sequential Control Structure
The simplest of all the structures The program instruction has one starting point and one ending point. Each step is carried out in order of their position and is only done once.
51
Sequential Control Structure
Flowchart Begin Fill a kettle with water Boil the water in the kettle Put tea leaves in the pot Pour boiling water into the pot End
52
Control Structure: Selection Control Structure
The selection structure allows comparison of expression, and based on the comparison, to select certain course of action
53
Selection Control Structure
Telephone rings? F T Continue reading Answer phone
54
Control Structure: Repetition control structure
The repetition structure allow a sequence of instructions to be executed repeatedly until a certain condition is achieved.
55
Repetition control structure
beg has items? false true Take item out
56
Control Structure: Modular
Is a method of dividing a problem into separate tasks, each with a single purpose. Separate task with a single purpose = FUNCTION
57
Modular Company IT Accountancy Human resource
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.