0% found this document useful (0 votes)
13 views10 pages

ICT

Introduction to C++ Grade 9

Uploaded by

braine26
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views10 pages

ICT

Introduction to C++ Grade 9

Uploaded by

braine26
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 10

ICT Int main() - entry point of the program

- this part is the first thing the


INTRODUCTION TO C++ compiler will look for (additional info from sir)

Why C++? return 0; - exit status of the program


- Industry Standard - if not put in, the program will not
- High-Level and Low-Level end/exit.
- Efficient in Memory Management
- Flexible Header files
- Large Community ● <iostream> - input-output stream
- Portable functions, used for taking input from and
displaying output to the user.
C++ Compilers - Will translate the code to ● <iomanip> - output manipulators, used
machine code to format the output of the program
● <cmath> - used for mathematical
>Online C++ Compiler - Jdoodle formula/operations
>Android C++ Compiler - ● <cmath> - used to manipulate “strings”
Cxxdroid-c/c++ such as words, phrases, and sentences.
>IOS C++ Compiler - Mobile C[C/C++
Compiler] cout- used to output a certain text or number
>Windows C++ - Dev C++ on your computer system

Syntax - refers to the rules that define the VARIABLES IN C++


structure of a language
- According to computerhope.com Variable Declaration - temporary storage of
“When referring to a programming language, any input from the user
the syntax is a set of rules for grammar and Variable Type
spelling. In other words, it means using Int - numbers
character structures that a computer can char - characters/single letter from a-z
interpret.” string - single word

Basic C++ Program Syntax cout<< - output to monitor


cin>> - input from keyboard
#include<iostream>
using namespace std; Variable - a container where the data will be
Int main() put into and stored.

{ Ex. a program that will ask the user to input


cout<<”Hello World!”; two no. and get the corresponding sum.
return 0;
} Variable Declaration:
#include - preprocessor directive; a way of - In C++ declaring a variable requires 3
including a standard or user-defined file in the parts:
program - Syntax: data_type variable_name;
- Multiple variable declaration : start with
Iostream - separate program the data type, separate each variable
- “library” or tool box in c++; contains name with a comma, and end it with a
“function” that can be used in the program. semicolon.
- Syntax: data_type variable_name1,
#include<iostream> - use the iostream library variable_name2;
in the program
Variable Initialization - to assign a value to a - a- variable name
variable, use the equal sign (=) called the - = - assignment operator
assignment operator. - 5.5f - value
- The identifier goes on the left of the - ; - semicolon
equal sign and the value goes on the
right double
- You can assign new value to your
variable anytime you want. - Double precision floating point values
- Syntax: data_type variable_name=value - Real numbers that can handle up to 15
- Syntax: data_type decimals
varname1,varname2=value; - Ex. double a = 100.5356;
- double - data type
Data Types - a- variable name
- = - assignment operator
- Used to tell the variables the type of - 100.5356 - value
data it can store - ; - semicolon
- All variables use data type during
declaration to restrict the type of data to bool
be stored - Truth values
- Can store many different types of - True or false
information - Ex. bool a = true; bool b = false;
- bool - data type
char - a- variable name
- = - assignment operator
- character(letters,symbol, or white - true - value
space) - ; - semicolon
- Should be enclosed in single quotes
- Ex. char letter = ‘A’ C++ Comments
- char - data type
- Letter - variable name - Explanatory statements that you can
- = - assignment operator include in c++ code
- ‘A’ - value - All characters inside any comment are
- ; - semicolon ignored by c++

Int Types:

- integer ❖ Single Line Comment - (//)


- Whole number ranging between ±32767 ❖ Multi-Line Comment - enclosed in /**/
- Ex. int a = 5; int b = -10; symbols
- Int - data type
- a- variable name endl function
- = - assignment operator
- 5 - value - to start a new line of output
- ; - semicolon - Ex. cout<<”Programming is”<<endl;
- cout<<”fun!”;
float
- Single precision floating point values Variable Name (Identifier)
- Real numbers that can handle up to 7
decimals - Used to identify a variable, usually
- Ex. float a = 5.5f; float b = 10.3f limited to letters, digits, and
- float - data type underscores.
Variable Naming Conventions
● Addition (+)
- Only compose of letters, numbers,
and/or a single symbol, underscores.
- All names must always start with a letter
or an underscore (A-Z, a-z, _ ).
- To use more than one word to name a
variable, use the underscore symbol
instead of a space or use uppercase
letters to start each word with no space
between words.
- C++ is a case sensitive language. It will Normal : varName += varName + value;
distinguish between upper and Shortcut: varName += value;
lowercase letters in identifiers.
- Variable names should be short and ● Subtraction
should clearly describe what the
variable represents. Just make sure that
the first 3 letters of its name make sense
when you read it so that it will be easy to
remember and easy to type as well.
- Avoid using very short names for a
variable that won't make sense the first
time you read them.

Naming Styles
Normal : varName -= varName - value;
Shortcut: varName -= value;
● Flat Case - all lower case but connected
directly ● Multiplication (*)
● Camel Case - uncapitalized first letter,
capitalized proceeding words and
connected directly
● Pascal Case - capitalized and
connected directly
● Snake Case - all words in lowercase
and connected by an underscore ( _ ).
● Macro Case - all words are in upper
case and connected by an underscore
( _ ).
Normal : varName *= varName * value;
Shortcut: varName *= value;
● Division (/)

C++ Arithmetic & Mathematical Operators

Operator
- A symbol that tells the compiler to
perform specific mathematical or logical
manipulators

Operators and symbol


- If the data type of the result is an int, the ● sqrt (num)
decimal part is discarded ● Ex.
Normal : varName /= varName / value;
Shortcut: varName /= value; cout << sqrt(9) << endl; // output is 3

● Modulo (%) floor()

● Rounds down a number to the largest


integer less than or equal to the
number.
● floor(num)
● Ex

cout << floor(3.3) << endl; // output is


3
-
only works if both the left and right is an
integer ceil()

Normal : varName %= varName % value; ● Rounds up the number to the


Shortcut: varName %= value; smallest integer greater than or equal
to the number.
Incrementing ● ceil(num)
● Ex.
Increasing by 1
cout << ceil(3.3) << endl; // output is 4
● Normal: varName = varName +1;
● Shorthand: varName++; fabs()

Decrementing ● Returns the absolute, positive value


of num.
● fabs (num)
Decreasing by 1
● Ex.
● Normal: varName = varName - 1;
cout << fabs(-3.2) << endl; // output is
● Shorthand: varName--;
3.2
Basic Math Functions
cout << fabs(5.9) << endl; // output is
5.9
pow()
CONDITIONAL STATEMENTS
● Returns the value of the left operand
(base) raised to the power of the right
Conditional Statements PART 1
operand (exponent).
● pow (base, exponent)
● Ex. LOGICAL EXPRESSIONS

cout << pow(2,3) << endl; // 2³ is 8 ▪ All conditional statements in C++


make use of logical expressions that
are true/false statements about data
sqrt()

● Returns the square root of a number.


▪ Simple logical expressions are of the ▪ This will attempt to do assignment instead
form: (data operator data)
▪ The logical expression will not check for
▪ Data terms in logical expressions equality
can be variables, constants or
arithmetic expressions ▪ Warning: Do not use =<, =>, =! to
compare data values
▪ C++ evaluates logical expressions
from left to right to see if they are ▪ These are invalid operators
true/false
▪ You will get a compiler error
The C++ relational operators are:
COMPLEX LOGICAL EXPRESSIONS
- < less than
- > greater than ▪ Simple logical expressions have limited
- <= less than or equal power
- >= greater than or equal
- == equal to ▪ To solve this problem, we can combine
- != not equal to simple logical expressions to get complex
logical expressions
▪ Some examples:
▪ This is useful for more realistic data
▪ (17 < 42) is true comparison tasks

▪ (42 > 17) is true ▪ The basic syntax is: (expression operator
expression)
▪ (17 == 42) is false
▪ Expression can be a simple or complex
▪ (42 != 17) is true logical expression

▪ ((17 + 10) > (42 – 2)) is false ▪ The C++ logical operators are:

▪ ((17 * 3) <= (17 + 17 + 17) is true && and

▪ When integer variables a=17 and b=42 || or

▪ (a < b) is true ▪ Truth tables are often be used to


enumerate all possible values of a complex
▪ (a >= b) is false logical expression

▪ (a == 17) is true ▪ We make columns for all logical


expressions
▪ (a != b) is true
▪ Each row illustrates one set of input values
▪ ((a + 17) == b) is false
▪ The number of rows is always a power of 2
▪ ((42 – a) < b) is true

▪ Warning: Do not use a single = for


checking equality
▪ C++ evaluates complex logical ▪ The not operator in in C++ reverses the
expressions from left to right value of any logical expression

▪ (exp1 && exp2) will be true if both exp are ▪ Logically “not true” is same as “false”
true
▪ Logically “not false” is same as “true”
▪ (exp1 && exp2 && exp3) will be true if all
exp are true ▪ The C++ syntax for the not operator
is: !expression
▪ (exp1 || exp2 || exp3) will be true if any exp
is true ▪ This is a “unary” operator since there is
just one expression to the right of the not
▪ C++ has a feature called “conditional operator
evaluation” that will stop the evaluation
early in some cases ▪ Examples with integer variables a = 7
and b = 3
▪ (exp1 && exp2) will be false if exp1 is false
▪ (a > b) is true !(a > b) is false
▪ (exp1 || exp2) will be true if exp1 is true
▪ (a <= b) is false !(a <= b) is true
▪ In both cases, we do not need to evaluate
exp2 ▪ (a == b) is false !(a == b) is true

▪ Complex logical expressions ▪ (a != b) is true !(a != b) is false

▪ ((17 < 42) && (42 < 17)) is false, because ▪ We can often “move the not operation
second half is false inside” a simple logical expression

▪ ((17 <= 42) || (42 <= 17)) is true, because ▪ To do this simplification, we need to
first half is true remove the ! operator and reverse the logic
of the relational operator
▪ When float variables x = 3.14 and y =
7.89 ▪ !(a < b) same as (a >= b)

▪ ((x < 4) && (y < 8)) is true, because both ▪ !(a <= b) same as (a > b)
halves are true
▪ !(a > b) same as (a <= b)
▪ ((x > 3) && (y > 8)) is false, because
second half is false ▪ !(a >= b) same as (a < b)

▪ ((x < 4) || (y > 8)) is true, because first half ▪ !(a == b) same as (a != b)
is true
▪ !(a != b) same as (a == b)
▪ ((x < 3) || (y < 8)) is true, because second
half is true ▪ We can extend truth tables to illustrate
the not operator
▪ ((x > 4) || (y > 8)) is false, because both
halves are false ▪ Add new columns showing !A and !B and
their use in complex logical expressions
THE NOT OPERATOR
▪ Examples with float variables x = 4.3 and
y = 9.2

▪ ((x < 5) && (y < 10)) is true

▪ !((x < 5) && (y < 10)) is false

▪ ( !(x < 5) || !(y < 10)) is false


From the truth table we can see that:
▪ ((x >= 5) || (y >= 10)) is false
!(A || B) is the same as !A && ! B
▪ !((x >= 5) || (y >= 10)) is true
!(A && B) is the same as !A || ! B
▪ ( !(x >= 5) && !(y >= 10)) is true
▪ This rule is known as “De Morgan’s
Law” ▪ ((x < 5) && (y < 10)) is true

▪ It allows us to simplify a complex logical SUMMARY


expression by “moving the not operation
inside” ● In this section, we have focused on
how logical expressions can be
▪ To apply De Morgan’s Law, we must written in C++
change the logical operator and the
expressions ● We have seen how relational
operators (<, <=, >, >=, ==, and !=) can
▪ The && operator changes into || be used to create simple logical
expressions
▪ The || operator changes into &&
● We have seen how logical operators
(&& and !!) can be used to make more
▪ The ! is applied to both expressions
complex logical expressions
▪ Remember, two not operators side by ● Finally, we have seen how the not
side cancel each other out so they can both operator (!) can be used to reverse
be removed the true/false value of logical
expressions
▪ When exp1 and exp2 are simple logical
expressions Conditional Statements PART 2

▪ !(exp1 && exp2) same as (!exp1 || !exp2) IF STATEMENTS

▪ !(exp1 || exp2) same as (!exp1 && !exp2) ● Sometimes we want to selectively


execute a block of code
▪ !(!exp1 || !exp2) same as (!!exp1 && !!
exp2) or (exp1 && exp2) ● The C++ syntax of the if statement is:

▪ !(!exp1 && !exp2) same as (!!exp1 || !! if ( logical expression )


exp2) or (exp1 || exp2)
{
▪ Hence, there are many different ways to
represent the same logical expression
// Block of code to execute if expression
is true

● When expression is true, the block of


code is executed

● When expression is false, the block of


code is skipped
● Programming style suggestions: ● If the logical expression is false, we take
a different path through the diagram
➢ The block of code should be (skipping over the lock of code)
indented 3-4 spaces to aid
program readability
➢ If the block of code is only one
line long the { } brackets can be
omitted
● Never put a semicolon directly after the
Boolean expression in an if statement
➢ The empty statement between )
and ; will be selectively executed
based on the logical expression // Simple if statement
value int a, b;
➢ The block of code directly below cin >> a >> b;
if statement will always be if (a < b)
executed, which is probably not {
what you intended
cout << “A is smaller than B\n”;
}
● We can visualize the program’s if ===========================
statement decision process using a
“flow chart” diagram // One line block of code
int a, b;
cin >> a >> b;
if (a == b)
cout << “A is equal to B\n”;
===========================

// Block of code that never executes


if (1 == 2)
● If the logical expression is true, we take {
one path through the diagram cout << “This code will never execute\n”;
(executing the block code)
}
===========================

// Block of code that always executes ● We can visualize the program’s if-else
if (true) statement decision process using a
“flow chart” diagram
{
cout << “This code will always execute\
n”;
}

IF-ELSE STATEMENT
● Sometimes we need to handle two
alternatives in our code
● The C++ syntax of the if-else statement
is:
● If the logical expression is true, we take
if ( logical expression )
one path through the diagram
{ (executing one block of code)

// Block of code to execute if expression


is true
}
else
{
// Block of code to execute if expression
is false ● If the logical expression is false, we take
one path through the diagram
} (executing the other block of code)

● Programming style suggestions:


➢ Type the “if line” and the “else
line” and the { } brackets so they
are vertically aligned with each
other
➢ Do not put a semi-colon after the // Simple if-else example
“if line” or the “else line” or you
will get very strange run time if ((a > 0) && (b > 0))
errors {
c = a / b;
➢ The two blocks of code should be
indented 3-4 spaces to aid a = a - c;
program readability }
➢ If either block of code is only one else
line long the { } brackets can be {
omitted c = a * b;
a = b + c; Grade = 'F';
}
============================== ● We add more code to calculate
the remaining letter grades
// Ugly if-else example
if (a < b) {
SUMMARY
c = a * 3;
● In this section we have studied the
a = b - c; } else
syntax and use of the C++ if statement
a = c + 5; and the if-else statement

● This code is nice and short but it is hard ● We have also seen how flow chart
to read diagrams can be used to visualize
============================== different execution paths in a program

// Pretty if-else example ● Finally, we showed how if statements


if (a < b) can be used to implement a simple
{ grade calculation program
c = a * 3;
a = b - c;
}
else
a = c + 5;

● This code takes more lines but it is


easier to read

Grade Calculation Example

// Calculate grade
if (Score >= 90)
Grade = 'A';
else if (Score >= 80)
Grade = 'B';
else if (Score >= 70)
Grade = 'C';
else if (Score >= 60)
Grade = 'D';
else

You might also like