Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 40

COLLEGE OF INFORMATICS AND VIRTUAL EDUCATION

(CIVE)

CP 123: Introduction to High-Level Programming

Basic C++ Syntax

1
General C++ Program
//Program description is first
#include directives go next
using namespace std;
int main()
{
constant declarations go here
variable declarations go here

assignment statements go here


return 0;
} 2
General C++ Language
 Compiler Directive: #include
It refers to a header file of library functions or
variables.
The compiler reads in the contents of the file before
compiling the program.
The included file is compiled with the program.
There are two forms of #include:
#include <stdio.h> // for pre-defined files
#include "my_lib.h" // for user-defined files

3
General C++ Language..
 Compiler Directive: #include

4
Libraries
 #include loads the code from the standard libraries:
#include <iostream> // new I/O library
#include <iostream.h> // old I/O library
#include <stdio.h> // standard functions
#include <math.h> // math functions
#include <stdlib.h> // contains random funct
#include <time.h> // time function
 using namespace std; indicates that the new C++
libraries should be used. If this line is left out, then the
old iostream library is loaded:
#include <iostream.h>
Namespace
 The #include <iostream> command is where cin
and cout are declared.
 They are declared within a namespace called std
 When we specify using namespace std;
 Then we need NOT preface the cin and cout commands with
std::cin and std::cout

6
Keywords
 Keywords have predefined purpose in the language.
Therefore, keywords should not be used for naming
purposes.
 That is, do not use keywords as variable, constant,
function or program/file name.
 Some of the keywords in C++ include:
bool, break, case, char, const, continue, do, default, double,
else, extern, false, float, for, if, int, long, namespace, return,
short, static, struct, switch, typedef, true, unsigned, void,
while
 Note that all keywords are in lowercase. 7
Comments
 Comments are explanatory notes; they are not part of
the program.
 The compiler ignores all comments.
 There are two ways to write comments in a C++
program:
 Single line comments: Everything after the // until the line return
is a comment. This is the preferred method for single line
comments
 Multiline comments: Everything between the /* and */ is a
comment. Can be used to comment out a block of code when
debugging a program, and to add sample output at the end of a
program
8
Case Sensitivity
 A programming language where upper and
lower case make a difference is called case
sensitive.
 C++ is a case sensitive language, therefore
treats differently identifiers like Muce,
MUCE, mUcE.

9
Identifiers
 Identifiers are the names given to programmer-
defined entities within the program – variables,
constants, functions, etc.
 Rules for naming identifiers:
 Names in C++ are case sensitive.
 Names may be very long up to 255 characters
 Names may contain letters, numbers and only the special character
underscore
 Names may NOT begin with a number
 Names must begin with a letter (at this stage in your C++ knowledge)
 Names may NOT contain blanks
 Names may not be a reserved word
10
Identifiers: Style Conventions

 Use names that are descriptive


 Standard abbreviations are fine
 Begin all variables with a lower case letter
 For variable names that contain more than one word,
capitalize the first letter of every word after the first
word
 Example: a variable called miles per hour would be named milesPerHour

 For named constants, capitalize the entire name, and


use the underscore to separate each word
 Example: a constant named kilometers per mile would be named
KM_PER_MILE 11
Data Types

 Data types supported by C++ can be classified as


Simple, Structured or Pointers.

12
Data Types

 Simple data types:


Type Memory Size (bits) Values
short 16 -2^16 to 2^16-1
int 32 -2^32 to 2^32-1
long 64 -2^64 t0 2^64-1
float 32 ±1038 with 7 decimal
places
double 64 ±10308 with 15
decimal places
char 8 -2^8 to 2^8-1
bool 8 true, false

13
Data Types..

 A string is a sequence of characters.


 The string type is programmer defined and you need
to #include<string> before you can use it.
 Examples: “James”, “Am going home”, “89320”,
“R6%90*”

14
Constants

 A constant is a data that has unchanging value.


 Name, data type and value must be specified
when declaring constants.
 Constant Declaration Syntax
const type name = expression;

 The statement must include the reserved word


const, which designates the declaration as a
constant declaration.
15
Constants..

 The type specification is optional and will be


assumed to be integer.

 Examples
const float TAXRATE = 0.0675;
const int NUMSTATES = 50;

 Convention is to use uppercase letters for names


of constants.

16
Variables

 Variables are data whose values can change


during the course of execution of your program.
 Any variable in your program must be declared
before it can be used.
 Variable declaration syntax:
<type> <identifier>;

Examples:
int age;
double salary;

A variable is best thought of as a container/box


for a value:1000 17
Variables..

 A variable can be initialized in a declaration:


int x = 3;

 Several variables of the same type can be declared


in the same declaration (though it is better to put
them on separate lines):
double total_USD, area;

 A variable must have only one type. For


example, a variable of the type int can only hold
integer values.
18
Variable Declaration: Memory
Depiction
Memory
float y = 12.5; location

int Temperature = 32; 1001


1002
y 12.5
1003
char Letter = 'c'; 1004
1005
int Number; Temperature 32 1006
1007
1008
Letter -
'c' 1009
1010
1011
Number 1012
1013
Assignment Statements
 Assignment syntax:
<identifier> = <expression>;

 Examples:
int n, m, k; // declaration
n = 5;
m = 6 + (4 * 6);
k = (n * 2) + m;
k = k / 2;
Assignment Statements..
int NewStudents = 6;
NewStudents 6
int OldStudents = 21;
OldStudents 21
int TotalStudents;
TotalStudents -

TotalStudents = NewStudents + OldStudents ;


NewStudents 6
OldStudents 21
TotalStudents 27
Assignment Statements..
int Value1 = 10; Value1 10
int Value2 = 20; Value2 20
int Hold = Value1;
Hold 10

Value1 = Value2; Value1 20


Value2 20
Hold 10

Value2 = Hold; Value1 20


Value2 10
Hold 10
Displaying Information on the Screen
 cout is used to display information on the computer
screen.
 It is declared in the header file iostream
 Syntax:
cout << expression;
 Uses << operator to send information to
computer screen
cout << "Hello, there!";

 Can be used to send more than one item


cout << "Hello, " << "there!";
23
Displaying Information on the Screen..
 To get multiple lines of output on screen:
Use the either the endl function
cout << "Hello, there!" << endl;
Or use \n in the output string:
cout << "Hello, there!\n";
 Other Escape Sequences include:
Escape Sequence Meaning
\t Horizontal tab
\r Carriage return, it moves the screen cursor to the beginning
of the line
\a Alert. Sound the system bell

24
Displaying Information on the Screen..
 Other Escape Sequences include:

Escape Sequence Meaning


\\ Used to print the backslash ‘\’
character
\’ Used to print a single-quote
character

\” Used to print a double-quote


character

25
Getting Data From the User
 cin - the standard input stream is used to get
data from the user.
 It is declared in the header file iostream
 Syntax:
cin >> variable;
 Input operator “>>”
extracts data from input “stream” (the keyboard by
default)
skips over white spaces
extracts only characters of the right form and
performs automatic conversion to the type
specified
26
Getting Data From the User..
 Often used with cout to display a message asking
the user to input data.
 Can be used to input more than one value:
cin >> height >> width;

 Multiple values entered from keyboard must be


separated by spaces.

 Order is important: first value entered goes to


first variable, etc.
27
Arithmetic Operators
 Arithmetic Operators are used to perform numeric
calculations.

Symbol Meaning Example Value of


Ans
+ Addition Ans=3+5; 8
- Subtraction Ans=67-40; 27
* Multiplication Ans=6*5; 30
/ Division Ans=7/3; 2
% Modulus Ans=13/5; 3
(Remainder)
28
Integer Division
 Integer division produces an integer result
It rounds down the result.
 Examples
3 / 2 evaluates to 1
4 / 6 evaluates to 0
10 / 3 evaluates to 3
Rules for Division
 C++ treats integers different than doubles.
 100 is an int.
 100.0 , 100.0000, and 100. are doubles.
 The general rule for division of int and double types
is:
double/double -> double (normal)
double/int -> double (normal)
int/double -> double (normal)
int/int -> int (special case: any decimal
places discarded)
Rules for Division..
 Example:
220. / 100.0 double/double -> double result is
2.2
220. / 100 double/int -> double result is 2.2
220 / 100.0 int/double -> double result is 2.2
220 / 100 int/int -> int result is 2
 Summary: division is normal unless both the
numerator and denominator are int, then the result is
an int (the decimal places are discarded).
Forcing a Type Change
 You can change the type of an expression with a cast
operation.
 The process is commonly known as typecasting.
 Syntax:
variable1 = type(variable2);
variable1 = type(expression);
 Example:
int x=1, y=2;
double result1 = x/y; // result1 is 0.0
double result2 = double(x)/y; // result2 is 0.5
double result3 = x/double(y); // result3 is 0.5
double result4 = double(x)/double(y);// result4 is 0.5
double result5 = double(x/y); // result5 is 0.0
The remainder Operator (%)
 Remainder is very useful in programming.
 For example, an even number % 2 is always 0 and an odd
number % 2 is always 1. So you can use this property to
determine whether a number is even or odd.
 Suppose today is Saturday and you and your friends are
going to meet in 10 days. What day is in 10 days? You can
find that day is Tuesday using the following expression:
Saturday is the 6th day in a week
A week has 7 days
(6 + 10) % 7 is 2
The 2nd day in a week is Tuesday
After 10 days
Increment and Decrement Operators
 Pre-increment and pre-decrement operators change
values before execution of statement.
Pre-increment example: ++x;
 Pre-decrement example: --x;
 Post-increment and Post decrement changes value
after execution of statement.
Post-increment example: x++;
 Post-decrement example: x--;
Operator Precedence
 Operator precedence tells how to evaluate
expressions.
 Standard precedence order:
( ) Evaluated first, if nested innermost done
first
++,-- Increment and decrement operators
 * / % Evaluated second. If there are several,
then evaluate from left-to-right
+ - Evaluate third. If there are several,
then evaluate from left-to-right
Relational Operators
 Tests relationship between two operands.
 Evaluates to true or false.

Operator Meaning Example


> Greater than a>b
< Less than a<b
>= Greater than or a>=b
equal
<= Less than or equal a<=b
Equality Operators
 Similar to relational operators.
 Checks if two operands are equal or unequal.
 Evaluates to true or false.

Operator Meaning Example


== Equal a==b
!= Not equal a!=b
Logical Operators
 Allows a program to make decisions based on
multiple conditions

Operator Meaning Example


&& And. It evaluates to true if both operands a&&b
are true, otherwise it evaluates to false
|| Or. It evaluates to true if either of the a||b
operands is true, otherwise it evaluates to
false
! Not. Denotes the opposite of operand. It !true
evaluates to false if the operand is true,
and true, otherwise.
Conditional Operator
 The conditional operator evaluates an expression,
returning one value if that expression evaluates to true,
and a different one if the expression evaluates as false.
 Syntax is:
condition ? Result1: Result2;
 If condition is true, the entire expression evaluates
to Result1, and otherwise to Result2.
 Example:
Example Answer

7==5 ? 4 : 3 evaluates to 3, since 7 is not equal to 5.


7==5+2 ? 4 : 3 evaluates to 4, since 7 is equal to 5+2.
Bitwise Operators
 Bitwise operators modify variables considering the bit
patterns that represent the values they store.
Operator Meaning Description

& AND Bitwise AND


| OR Bitwise OR
^ XOR Bitwise XOR
~ NOT Bitwise NOT
<< SHL Shift bits to left
>> SHR Shift bits to right

You might also like