0% found this document useful (0 votes)
3 views26 pages

2 - C++ Basics

The document provides an overview of C++ basics, covering variables, identifiers, variable declarations, assignment statements, input/output operations, data types, and control flow mechanisms. It explains how to declare and assign values to variables, use input/output functions, and implement control structures like if-else statements and loops. Additionally, it emphasizes program style, including indentation and comments for better readability.

Uploaded by

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

2 - C++ Basics

The document provides an overview of C++ basics, covering variables, identifiers, variable declarations, assignment statements, input/output operations, data types, and control flow mechanisms. It explains how to declare and assign values to variables, use input/output functions, and implement control structures like if-else statements and loops. Additionally, it emphasizes program style, including indentation and comments for better readability.

Uploaded by

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

C++ Basics

• 2.1 Variables and Assignments


• 2.1.1 Variables
• A C++ variable can hold a number or data of other types.
The number or other type of data held in a variable is
called its value.
• In the program shown below, number_of_bars,
one_weight and total_weight are variables. When this
program is run with the input shown in the sample
dialogue, number_of_bars has its value set equal to the
number 11 with the statement
cin >> number_of_bars
• In programming languages, variables are implemented
as memory locations. The compiler assigns a memory
location to each variable in the program.
• The value of the variable, in a coded form consisting of
zeros and ones, is kept in the memory location assigned
to that variable.

• 2.1.2 Name: Identifiers


• The name of a variable is called an identifier. An
identifier must start with either a letter or the underscore
symbol and all the rest of the characters must be letters,
digits or the underscore symbol.
• .
e.g x x1 x_1 _abc ABC123z7 sum RATE count data2 Big_Bonus
• All the above names are legal, but the first five are poor
choices for identifiers since they are not descriptive of
the identifiers’s use.
• None of the following are legal identifiers and all would
be rejected by the compiler
12 3x %change data-1 myfirst.c PROG.CPP

• The first three are not allowed because they do not start
with a letter or underscore. The remaining three are not
identifiers because they contain symbols other than
letters, digits and the underscore symbol.
• C++ is a case-sensitive language. E.g the following are
three distinct identifiers.
rate RATE Rate
• The predefined identifiers, such as main, cin, cout and
so forth must be spelled in all lowercase letters.
• There is a special class of identifiers call keywords or
reserved words that have a predefined meaning in C++
and that you cannot use as names for variables or
anything else.

• 2.1.3 Variable Declarations


• Every variable in a C++ program must be declared.
When you are declare a variable you are telling the
compiler what kind of data you will be storing in the
variable.
• There are two natural places to declare a variable: either
just before it is used or at the start of the main function.
• Variable declaration

All variables must be declared before they are used.


The syntax for variable declaration is as follows:
Syntax:
Type_Name Variable_Name_1, Variable_Name_2, …;

Example:

int count, number_of_dragons, number_of_trolls;


double distance;
• 2.1.4 Assignment Statements
• The most direct way to change the value of a variable is
to use an assignment statement. An assignment
statement is an order to the computer saying “set the
value of this variable to what I have written down”.
• E.g total_weight = one_weight * number_of_bars

• An assignment statement always consists of a variable


on the left-hand side of the equal sign and an expression
on the right-hand side
• An assignment statement ends with a semicolon.
Assignment Statements
Syntax:
Variable = expression;
Examples
Distance = rate * time;
• 2.2 Input and Output
• 2.2.1 Output Using cout
• The values of variables as well as strings of text may be
output to the screen using cout.
• E.g
cout << number_of_bars << “ candy bars\n”;

• This statement tells the computer to output two items:


the value of the variable number_of_bars and the quoted
string “ candy bars \n”.
• You can include arithmetic expression in a cout
statement
cout << “total cost is $” << (price + tax);

• \n tells the computer to start a new line of output. \n is


called the new-line character.
• 2.2.2 Escape Sequences
• The \ preceeding a character tells the compiler that the
sequence following the \ does not have the same
meaning as the character appearing by itself. Such a
sequence is called an escape sequence
• Some escape sequences
New-line \n
Horizontal tab \t
Alert \a
Backslash \\
Double quote \”

• If you wish to insert a blank line in the output, you can


output the new-line character \n by itself
cout << “\n”; or cout << endl;
• 2.2.3 Formatting for numbers with a
decimal Point
• When the computer outputs a value of type double, the
format may not be what you would like. To ensure that
the output is in the form you want, your program should
contain some sort of instructions that tell the computer
how to output the numbers.
• If you want two digits after the decimal point, use the
following magic formula:
cout.setf(ios : : fixed);
cout.setf(ios : : showpoint)
cout.precision (2)

• You may use other nonnegative whole number in place


of two to specify a different number of digits after the
decimal point.
• Input using cin
• You can list more than one variable in a single cin-
statement.
• When a program reaches a cin-statement, it waits for
input to be entered from the keyboard.
cin-statement
A cin-statement sets variabels equal to values typed in at the keyboard

Syntax:
cin >> Variable_1 >> Variable _2 >> ….;

Examples:
cin >> number >> size
cin >> time_to_go
>> points_needed
• Designing Input and Output
• Input and output (I/O) is the part of the program that the
user sees.
• When the computer executes a cin-statement, it expects
some data to be typed in at the keyboard. If non is typed,
it simply waits.
• The program must tell the user when to type in a number
(or other data item).
• Your program should always have output statements
that prompt for input
• E.g
cout << “Enter the number of books you have \n”;
cout << “what is your name \n”
cout << “Then press return \n”
• 2.3 Data Types and Expressions
• 2.3.1 The Types int and double
• Whole numbers (e.g. 2) are of type int
• Numbers of type int are stored as exact values
• Decimal numbers (e. g. 2.0) are of type double
• Numbers of type double are stored as approximate
values.
• The more complicated notation for constants of type
double is frequently called scientific notation or floating
point notation.
• 2.3.2 Other Number Types
• C++ has other numeric types besides int and double
• The various number types allow for different size
numbers and for more or less precision.
Some Number Types
Type Name Memory Used Size Range Precision

short 2 bytes -32767to 32767 Not applicable


(short int)

Int 4 bytes -2,147,483,647 to Not appicable


2,147,483,647
long 4 bytes -2,147,483,647 to Not appicable
2,147,483,647

float 4 bytes 7 digits


double 8 bytes 15 digits
long double 10 bytes 19 digits
• 2.3.3 The Type char
• Values of the type char, which is short for character, are
single symbols such as a letter, digit or punctuation
mark.
char symbol, letter

• 2.3.4The type bool


• Expressions of type bool are called Boolean.
• Boolea expression evaluate to one of the two values true
or false.
• 2.3.4 Assignment Statements
• There is a shorthand notation that combines the
assignment operator (=) and an arithmetic operator so
that a given variable can have its value changed by
adding, subtracting, multiplying by or diving by a
specified value.

Example Equivalent to:

count +=2; count = count + 2;


total-=discount; total = total – discount;
bonus *=2; bonus = bonus * 2;
time /= rush_factor; time = time/rush_factor;
change %= 100; change = change % 100
amount *= cnt1 + cnt2; amount = amount * (cnt1 +cnt2);
• 2.4 Simple Flow of Control
• 2.4.1 A simple Branching Mechanism
• Sometimes it is necessary to have a program choose
one of two alternatives, depending on the input. There is
a C++ statement that does exactly this kind of branching
action. The if-else-statement chooses between two
alternative actions.
• A Boolean expression is any expression that is either
true or false. An if-else-statement always contains a
Boolean_Expression.
• An if-else statement
#include <iostream.h>
int main()
{
int hours;
double gross_pay, rate;

cout << “Enter the hourly rate of pay: $”;


cin >> rate;
cout << Enter the number of hours worked, \n”
<< “rounded to a whole number of hours: ”;
cin >> hours;
if (hours > 40)
gross_pay = rate*40 + 1.5*rate*(hours – 40);
else
gross_pay = rate*hours
cout.setf(ios : : fixed);
cout.setf(ios : : showpoint)
cout.precision (2)

cout << “Hours =“ << hours << endl;


cout << “Hourly pay rate = $” << rate << endl;
cout << “Gross pay = $” << gross_pay << endl;

return 0;
}
• 2.4.2 Comparisons Operators

Maths symbol English C++ Notation

= equal to ==
≠ not equal to !=
< less than <
≤ less than or equal to <=
> Greater than >
≥ greater than or equal to >=

• You can combine two comparisons using the “and”,


which is spelled && in C++
• You can also combine two comparisons using the “or”
operator which is spelled || in C++
• 2.4.3 Compound Statements
• You will often want the branches of an if-else-statement
to execute more than one statement each. To
accomplish this, enclose the statements for each branch
between a pair of braces { and }.
• A list of statements enclosed in a pair of braces is called
a compound statement.
• A compound statement is treated as a single statement
by C++ and may be used anywhere that a single
statement may be used.
• Compound statements used with if-else

If (my_score > your_score)


{
cout << “I win!\n”;
wager = wager +100;
}
Else
{
cout << “I wish these were football scores. \n”;
wager = 0;
}
• 2.4.5 Simple loop mechanisms
• Most programs include some action that is repeated a
number of times. A portion of a program that repeats a
statement or group of statements is called a loop.
• The C++ language has a number of ways to create
loops. One of these constructions is called a while-
statement or while loop.
• A while-Loop
#include <iostream.h>
int main()
{
int count_down;

cout << “How many greetings do you want? ”;


cin >> count_down

while (count_down > 0)


{
cout << “hello ”;
count_down = count_down – 1;
}

cout << endl;


cout << “that’s all! \n”;

return 0;
}
• A do-while-Loop
#include <iostream.h>
int main()
{
char ans;

do
{
cout << “hello \n”;
cout << “Do you want another greeting?\n”
<< “Press y for yes, n for no, \n)
<< “and then press return:”;
cin >> ans;

}while (ans == ‘y’ || ans == ‘Y’(;

cout << “Good-Bye \n”;

return 0;
}

• A do-while loop is similar to while loop except that the loop body is
always executed at least once.
• 2.4.5 Increment and Decrement Operators

• Unary operators have only one operand, i.e. + or -. The


C++ language has two other very common unary
operators , ++ and --.
• The ++ operator is called the increment operator and the
-- operator is called the decrement operator.
• They are usually used with variables of type int.
• If n is a variable of type int, then n++ increases the value
of n by one and n-- decreases the value of n by one.
• 2.5 Program Style
• 2.5.1 Indenting
• A program should be laid out so that elements that are
naturally considered a group are made to look like a
group.
• One way to do this is to skip a line between parts that
are logically considered separate.
• Indenting can also help the structure of the program
clearer.
• A statement within a statement should be indented. In
particular, if-else statements, while loops and do-while
loops.
• 2.5.2 Comments
• In order to make a program understandable, you should
include some explanatory notes at key places in the
program. Such notes are called comments.
• In C++ the symbols // are used to indicate the start of a
comment.
• The other way to insert a comment is using the symbols
pair /* and the symbol pair */.
/* this is a comment that spans
three lines. Note that there is no comment symbol
of any kind on the second line . */

// this is also a comment

You might also like