Computer Programming (CP)
Unit-2
C++ Basics
Faculty of Computing and Informatics
Jimma Technology Institute, Jimma
[email protected] +251912499102
Outline
Looping
Introduction to C++ Programming
Preprocessor directives (#)
C++ keywords (Reserved words)
C++ identifiers
C++ comments
Variables
Variable Declaration
Basic Data Types
Input/Output Statements
Operators
Introduction to C++ Programming
C++ programs contain a basic building block
named a statement.
A statement could be an instruction or combination
of instructions.
statement ends by semicolon ( e.g. int x; )
C++ is case sensitive ( i.e. A and a are different. )
The compiler ignores allInt
spaces and new line.
x=5;
E.g. Int x=5 is the same as after
compiled.
AJP Unit 1 – Java Networking 3
Preprocessor directives (#)
Before you can use any runtime libraries in your program, you must first
add a header-file into your program, using the # include statement.
A header file is a file with an extension of .h that is included as part of
a program and notifies the compiler that a program uses run-time
libraries.
Preprocessor directives processed by preprocessor before compiling
and begin with #
Example, #include <iostream.h> Tells preprocessor to include the
input/output stream header file <iostream.h>
AJP Unit 1 – Java Networking 4
C++ keywords (Reserved words)
Reserved/Key words have a unique meaning within a C+
+ program.
Each keyword has a predefined purpose in the language.
Do not use keywords as variable and constant names!!
The following are some of the reserved words of C++.
AJP Unit 1 – Java Networking 5
C++ identifiers
The C++ identifier is a name used to identify a variable, function,
class, module, or any other user-defined item.
It consists of a letter followed by any sequence of letters, digits, and
underscores.
The general rules for constructing names for variables (unique
identifiers) are:
Names can contain letters, digits and underscores
Names must begin with a letter or an underscore (_)
Names are case sensitive (myVar and myvar are different variables)
Names cannot contain whitespaces or special characters like !, #,
%, etc.
Reserved words (like C++ keywords, such as int) cannot be used as
names
AJP Unit 1 – Java Networking 6
AJP Unit 1 – Java Networking 7
C++ Comments
Comments are explanatory notes
Program comments are totally ignored by the compiler and are only intended for human
readers.
C++ provides two types of comment delimiters:
a. Single-line comment
Begin with //
Anything after // (until the end of the line on which it appears) is considered a comment.
Example // this is a text-printing program
b. Multi-line comment
Start with /*
End with */
Anything enclosed by the pair /* and */ is considered a comment.
Example /* This is a text-printing program*/
AJP Unit 1 – Java Networking 8
Comments
// A first program in C++ Written between /* and */ or following a //.
#include <iostream> Improve program readability and do not cause
the computer to perform any action.
int main()
{
preprocessor directive
cout << "Welcome to C++!\n";
Message to the C++ preprocessor.
Lines beginning with # are preprocessor
return 0; directives.ended successfully
// indicate that program
} #include <iostream> tells the preprocessor
to include
C++ the contents
programs of the
contain one file <iostream>,
or more functions,
which
one includes
of which input/output
must be main operations (such as
Welcome to C++! printing to the
Parenthesis arescreen).
used to indicate a function
int means that main "returns" an integer value.
Prints the string of characters contained between
the quotation
return is a way to exit a functionmarks.
from a function. A left brace { begins the body of every
The means
return 0, in this case, function
entire line, including cout,andthe
a right brace } ends it.
<< operator,
the string "Welcome to C++!\n" and the
that the program terminated
normally. semicolon (;), is called a statement.
All statements must end with a semicolon.
AJP Unit 1 – Java Networking 9
// Printing a line with multiple statements
#include <iostream>
int main()
{
cout << "Welcome ";
cout << "to C++!\n";
return 0; // indicate that program ended successfully
}
Welcome to C++!
Unless new line '\n' is specified, the text continues
on the same line.
AJP Unit 1 – Java Networking 10
// Printing multiple lines with a single statement
#include <iostream>
int main()
{
cout << "Welcome\nto\n\nC++!\n";
return 0; // indicate that program ended successfully
}
Welcome
to
C++!
Multiple lines can be printed with one
statement.
AJP Unit 1 – Java Networking 11
// Addition program
#include <iostream>
int main()
{
int integer1, integer2, sum; // declaration
cout << "Enter first integer\n"; // ompt
cin >> integer1; // read an integerNotice how cin is used to get user input.
cout << "Enter second integer\n"; // prompt
cin >> integer2; // read an integer
sum = integer1 + integer2; // assignment of sum
cout << "Sum is " << sum << endl; // print sum
return 0; // indicate that program ended successfully endl flushes the buffer and prints a
} newline.
Enter first integer Variables can be output using cout << variableName.
45
Enter second integer
72
Sum is 117
AJP Unit 1 – Java Networking 12
Variables
• A variable is a symbolic name for a memory location in which data
can be stored and subsequently recalled.
• Variables are used for holding data values so that they can be
changed and utilized in various computations in a program.
• All variables have two important attributes:
– A type: which is, established when the variable is defined (e.g.,
integer, float, character).
• Once defined, the type of a C++ variable cannot be changed.
– A value: which can be changed by assigning a new value to the
variable.
• The kind of values a variable can assume depends on its type.
• example, an integer variable can only take integer values (e.g.,
2, 100, -12) not real numbers like 0.123.
AJP Unit 1 – Java Networking 13
Variable Declaration
• Declaring a variable means defining (creating) a variable.
– You create or define a variable by stating its type, followed by one
or more spaces, followed by the variable name and a semicolon.
Syntax: Data_Type Variable_Name;
Fore example:
• int year; //integer variable declaration, the variable name is
year.
• char ch; //character variable declaration, the variable name is
ch.
• float bonus; //floating number declaration, the variable name is
bonus.
• The following statement defines an integer variable called myAge:
• int myAge;
Variables must be declared before used!
AJP Unit 1 – Java Networking 14
Creating More Than One Variable at a Time
– You can create more than one variable of the same
type in one statement by writing the type and then
the variable names, separated by commas.
– Syntax: Data_Type Variable_Name1,
Variable_Name2, …… Variable_NameN;
For examples:
int myAge, myWeight; // two int variables
long area, width, length; // three longs
– you cannot mix types in one definition statement
AJP Unit 1 – Java Networking 15
Assigning Values to Your Variables
• You assign a value to a variable by using the assignment
operator (=).
Syntax: Data_Type Valid _Variable_Name;
Valid _Variable_Name = Initial _Value;
For examples:
int Width; //declaration
Width = 5; //assignment
OR
int Width = 5; //initialization
// create two int variables and initialize them
int width = 5, length = 7;
//mix definitions and initializations:
int myAge = 39, yourAge, hisAge = 40;
AJP Unit 1 – Java Networking 16
Basic Data Types
• When you define a variable in C++, you must tell the
compiler what kind of variable it is:
– This information tells the compiler how much room to set aside and
what kind of value you want to store in your variable.
• Several data types are built into C++.
– The varieties of data types allow programmers to select the type
appropriate to the needs of the applications being developed.
• The data types supported by C++ can be classified as
– basic (fundamental) data types
– user defined data types
– derived data types
AJP Unit 1 – Java Networking 17
• Basic data types can be divided into:
– numeric and
– character types
• Numeric variables can further be divided into
– integer variables – hold only integers
– floating-point variables – hold real numbers
• Both the numeric data types offer modifiers that are used
to vary the nature of the data to be stored.
– short
– long
– signed
– unsigned.
AJP Unit 1 – Java Networking 18
C++ data types and their ranges
Type Size Values
unsigned short int 2 bytes 0 to 65,535
short int(signed short int) 2 bytes -32,768 to 32,767
unsigned long int 4 bytes 0 to 4,294,967,295
long int(signed long int) 4 bytes -2,147,483,648 to 2,147,483,647
int 4 bytes -2147483648 to
2147483647
unsigned int 2 bytes 0 to 65,535
signed int 2 bytes -32,768 to 32,767
char 1 byte 256 character values
float 4 bytes 3.4e-38 to 3.4e38
double 8 bytes 1.7e-308 to 1.7e308
long double 10 bytes 1.2e-4932 to 1.2e4932
AJP Unit 1 – Java Networking 19
Characters
• Character variables (type char) are typically 1 byte,
– enough to hold 256 values.
• A char can be interpreted as a small number (0-255) or as a
member of the ASCII set.
– ASCII - the American Standard Code for Information Interchange.
– The ASCII character set and its ISO (International Standards
Organization) equivalent are a way to encode all the letters,
numerals, and punctuation marks.
• In the ASCII code, the lowercase letter "a" is assigned the
value 97. All the lower- and uppercase letters, all the
numerals, and all the punctuation marks are assigned values
between 1 and 128.
– Another 128 marks and symbols are reserved for use by the
computer maker, although the IBM extended character set has
become something of a standard
AJP Unit 1 – Java Networking 20
Characters and Numbers
• When you put a character, for example, `a', into a
char variable, what is really there is just a number
between 0 and 255.
• The compiler knows how to translate back and
forth between characters and one of the ASCII
values.
• There is a big difference between the value 5 and
the character `5'.
– The latter is actually valued at 53
AJP Unit 1 – Java Networking 21
Constants
C++ introduces the concept of a named constant that is just like a
variable, except that its value cannot be changed.
The qualifier const tells the compiler that a name represents a
constant. Any data type, built-in or user-defined, may be defined as
const.
If you define something as const and then attempt to modify it, the
compiler will generate an error.
Example:
const float PI = 3.1416;
const double SALESTAX = 0.05;
const int MAXNUM = 100;
Once declared, a constant can be used in any C++ statement in
place of the number it represents.
AJP Unit 1 – Java Networking 22
Input/Output Statements
• The most common way in which a program communicates with the outside
world is through simple, character-oriented Input/Output (IO) operations.
• C++ provides two useful operators for text based output and input purpose:
– >> for input and
– << for output.
The cout object is an output object that sends data given to it to the
standard output display device.
To send a message to the cout object, you use the following pattern:
cout <<"text“;
The cin object is an input object that accepts data from the standard input
device.
To accept a message from the cin object, you use the following
pattern: cin >>text;
AJP Unit 1 – Java Networking 23
#include <iostream.h>
int main (){
int workDays = 5;
float workHours = 7.5;
float payRate, weeklyPay;
cout << "What is the hourly pay rate? ";
cin >> payRate;
weeklyPay = workDays * workHours * payRate;
cout << "Weekly Pay = ";
cout << weeklyPay;
cout << '\n';
}
AJP Unit 1 – Java Networking 24
Operators
• C++ provides operators for composing
expressions
– arithmetic
– relational
– logical
– bitwise
• It also provides operators which produce useful
side-effects
– assignment
– increment
– decrement
AJP Unit 1 – Java Networking 25
Arithmetic Operators
C++ provides five basic arithmetic operators.
• Except for remainder (%) all other arithmetic operators
can accept a mix of integer and real operands.
– Generally, if both operands are integers then the result will be an
integer. However, if one or both of the operands are reals then
the result will be a real (or double to be exact).
• The remainder operator (%) expects integers for both of
its operands.
– It returns the remainder of integer-dividing the operands.
AJP Unit 1 – Java Networking 26
• Integer division always results in an integer outcome
(i.e., the result is always rounded down). For
example:
9/2 // gives 4, not 4.5!
• It is illegal to divide a number by zero. This results in a
run-time division-by-zero failure, which typically causes
the program to terminate.
AJP Unit 1 – Java Networking 27
Assignment Operators
• The assignment operator is used for storing a value at some memory
location (typically denoted by a variable).
• Its left operand should be an lvalue(left value), and its right operand
may be an arbitrary expression.
– The latter is evaluated and the outcome is stored in the location denoted by the
lvalue.
– An lvalue is anything that denotes a memory location in which a value may be
stored.
• The assignment operator has a number of variants obtained by
combining it with the arithmetic operators.
Syntax:
<Variable Identifier> = < expression>;
Description: The <expression> is evaluated and the resulting value
is stored in the memory space reserved for <variable identifier>.
AJP Unit 1 – Java Networking 28
• Generally Assignment operator (=):
Assigns value on left to variable on right
Binary operator (two operands).
Example:
• int a= 5;
• float b= 9.66;
• char ch=‘d’
AJP Unit 1 – Java Networking 29
Relational Operators
• C++ provides six relational operators for comparing
numeric quantities.
• Relational operators evaluate to 1 (true outcome) or 0
(false outcome).
AJP Unit 1 – Java Networking 30
• The operands of a relational operator must evaluate to a number.
• Characters are valid operands since they are represented by numeric
values.
'A' < 'F' // gives 1 (is like 65 < 70)
• The relational operators should not be used for comparing strings, because
this will result in the string addresses being compared, not the string
contents.
• C++ provides library functions (e.g., strcmp) for the lexicographic
comparison of string.
AJP Unit 1 – Java Networking 31
Logical Operators
• C++ provides three logical operators for combining logical
expression.
• Like the relational operators, logical operators evaluate to 1 or 0.
• Logical negation is a unary operator, which negates the
logical value of its single operand.
– If its operand is nonzero it produces 0, and if it is 0 it
produces 1.
AJP Unit 1 – Java Networking 32
• Logical and produces 0 if one or both of its operands evaluate
to 0. Otherwise, it produces 1.
• Logical or produces 0 if both of its operands evaluate to 0.
Otherwise, it produces 1.
• valid logical expressions:
!20 // gives 0
10 && 5 // gives 1
10 || 5.5 // gives 1
10 && 0 // gives 0
• C++ does not have a built-in boolean type. It is customary to
use the type int for this purpose instead.
• For example:
int sorted = 0; // false
int balanced = 1; // true
AJP Unit 1 – Java Networking 33
Bitwise Operators
Bitwise operator works on bits and performs bit-by-bit operation.
Assume a=12 and b=25
Operator Description Example
| (bitwise OR) compares corresponding bits of two operands. If a|b=29
either of the bits is 1, it gives 1. If not, it gives 0.
&(bitwise AND) If both bits are 1, it gives 1. If either of the bits is a&b=8
not 1, it gives 0.
~(bitwise inverts the bit pattern. It makes every 0 to 1, and ~a=11110011
complement) every 1 to 0.
^(bitwise XOR) If corresponding bits are different, it gives 1. If a^b=21
corresponding bits are same, it gives 0.
<<(left shift) shifts a bit pattern to the left by certain number of a<<1=24
specified bits
>>(right shift) shifts a bit pattern to the right by certain number of a>>1=6
specified bits.
AJP Unit 1 – Java Networking 34
• Bitwise operators expect their operands to be integer quantities and treat them as
bit sequences.
– Bitwise negation is a unary operator which reverses the bits in its operands.
– Bitwise and compares the corresponding bits of its operands and produces a 1
when both bits are 1, and 0 otherwise.
– Bitwise or compares the corresponding bits of its operands and produces a 0
when both bits are 0, and 1 otherwise.
– Bitwise exclusive or compares the corresponding bits of its operands and
produces a 0 when both bits are 1 or both bits are 0, and 1 otherwise.
– Bitwise left shift operator and bitwise right shift operator both take a bit
sequence as their left operand and a positive integer quantity n as their right
operand.
• The former produces a bit sequence equal to the left operand but which has
been shifted n bit positions to the left.
• The latter produces a bit sequence equal to the left operand but which has
been shifted n bit positions to the right. Vacated bits at either end are set to 0.
AJP Unit 1 – Java Networking 35
Increment/decrement Operators
The auto increment (++) and auto decrement (--) operators provide a
convenient way of, respectively, adding and subtracting 1 from a
numeric variable.
AJP Unit 1 – Java Networking 36
AJP Unit 1 – Java Networking 37
int x, a, b, c;
a = 2;
b = 4;
c = 5;
x = a-- + b++ - ++c;
AJP Unit 1 – Java Networking 38
Precedence of Operators
The order in which operators are evaluated in an
expression is significant and is determined by precedence
rules.
These rules divide the C++ operators into a number of
precedence levels.
Operators in higher levels take precedence over operators
in lower levels.
AJP Unit 1 – Java Networking 39
Level Operator Kind Order
Highes :: Unary Both
t
() [] Binary Left to Right
.
+ ++ ! * new sizeof() Unary Right to Left
- -- ~ & delete
->* .* Binary Left to Right
* / % Binary Left to Right
+ - Binary Left to Right
<< >> Binary Left to Right
< <= > >= Binary Left to Right
== != Binary Left to Right
& Binary Left to Right
^ Binary Left to Right
| Binary Left to Right
&& Binary Left to Right
|| Binary Left to Right
?: Ternary Left to Right
AJP Unit 1 – Java Networking 40
Precedence of Operators
a + b + c + d + e a + b * c - d / e
1 2 3 4 3 1 4 2
a / (b + c) - d % e
2 1 4 3
a / (b * (c + (d - e)))
4 3 2 1
• Example: Evaluate the following expressions
3+2*3 9
(3 + 2) * 3 15
23 + 4 * 5 /2 % 3-7 17
AJP Unit 1 – Java Networking 41
Simple Type Conversion
• C++ allows us to convert data of one type to that of another.
• This is known as type conversion.
• here are two types of type conversion in C++.
1.Implicit Conversion
2.Explicit Conversion (also known as Type Casting)
Implicit Type Conversion
This type of conversion is also known as automatic conversion.
For example:
double num_double = 9.99;
int num_int = 9;
int num_int;
double num_double;
num_double = num_int; num_int = num_double;
AJP Unit 1 – Java Networking 42
Explicit Conversion
When the user manually changes data from one type to
another
Syntax: –(int) 3.14 // converts 3.14 to an
(type) expression int to give 3
For example, –(double) 2 // converts 2 to a double
double x = 1.2; to give 2.0
int sum = (int)x + 1;
AJP Unit 1 – Java Networking 43
Exercise
1. Write a statement (or comment) to accomplish each of the
following:
– State that a program calculates the product of three integers.
– Declare the variables x, y, z and result to be of type int.
– Prompt the user to enter three integers.
– Read three integers from the keyboard and store them in the
variables x, y and z.
– Compute the product of the three integers contained in
variables x, y and z, and assign the result to the variable result.
– Print "The product is " followed by the value of the variable
result.
– Return a value from main indicating that the program
terminated successfully.
AJP Unit 1 – Java Networking 44
Exercise
2. Write a program that accepts two integers and display the
sum, difference, product and division of the two numbers. The
program should also state the greater and smaller number.
3. Write a program that calculate and display the circumference
of a circle. (C = 2∏r )
4. Write a program to solve a quadratic equation.
Hint: y = ax2 + bx + c
root = (-b ± sqrt(b2 -4ac)) / 2a
Note: include math.h to use square root
function(sqrt(double))
AJP Unit 1 – Java Networking 45
AJP Unit 1 – Java Networking 46