basics of c and c++ by eteaching
TRANSCRIPT
C++
IT 3rd Sem
C & C++
Ken Thompson designed B Language [BCPL(Basic Combined
Programming language)]
C was developed in 1970s in Bell Laboratories by Dennis
Ritchie (B language modified)
C was written for UNIX operating system.
History of C Language
History of C++
Language designed by Bjarne Stroutstrup in early 1980s
Named….. C with classes
In 1983, name changes to C++
IT 3rd Sem
C & C++
C++ is superset of C
case-sensitive
Similarities
Differences
classes and objects
C is procedural language whereas C++ is object-oriented
programming language.
IT 3rd Sem
C++Character Set
IT 3rd Sem
Letters A-Z, a-z
Digits 0-9
Special Symbols Space + − * / ^ \ ( ) [ ] { } = !=
< > . ‘ “ , % ! & _ # <= >=
White SpacesBlank Space, Horizontal Tab (→ )
Carriage Return ( ) Newline
Source File
Object File
Tokens
Identifiers
Keywords
Important Terms
IT 3rd Sem
C++
Data Types
IT 3rd Sem
C++
int
2 bytes
range -32768 to +32767 (signed)
range 0 to +65535 (unsigned)
Type Size Range
int 2 -32767 to +32767
unsigned int 2 0 to 65535
signed int 2 -32767 to +32767
short int 2 -32767 to +32767
unsigned short int 2 0 to 65535
signed short int 2 -32767 to +32767
long int 4 -2147483648 to +2147483647
signed long int 4 -2147483648 to +2147483647
unsigned long int 4 0 to +42949667295
IT 3rd Sem
C++
float & double
Type Size Range
float 4 3.4 E-38 to 3.4 E+38
double 8 1.7 E-308 to 1.7 E+308
long double 10 3.4 E-4932 to 1.1 E+4932
IT 3rd Sem
C++
char
Type Size Range
char 1 -128 to +127
unsigned char 1 0 to +255
signed char 1 -128 to +127
void
size 0 bytes
IT 3rd Sem
C++
Variable
Rules
Variable Declaration
data-type var1,var2;
For eg:
int a,b,c;
float x;
IT 3rd Sem
C++
Variable initialization
data-type var1;
var1=value;
For eg:
int a;
a=2;
Method 1:
Method 2:
data-type var1=value;
For eg:
int a=2;
IT 3rd Sem
C++
C++Derived Data Types:
Array
Structure
Union
Enumerations
Pointers
Class
IT 3rd Sem
C++Enumerations:
set of values represented by identifiers
Format:
enum name{var1,var2,var3,----------, varn};
name n1,n2;
n1=var1;
n2=var3;
cout<<n1;
cout<<n2;
output will be 0 and 2
IT 3rd Sem
C++Operators:
Type Operators Meaning
Arithmetic
+ Addition
− Subtraction
* Multiplication
/ Division
% Modulus (Remainder)
Relational
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to
== Equal to
!= Not equal to
IT 3rd Sem
C++Operators:
Type Operators Meaning
Logical
&& Logical AND
|| Logical OR
! Logical NOT
Bitwise
& Bitwise AND
I Bitwise OR
^ Bitwise Exclusive-OR (XOR)
>> Bitwise Shift Right
<< Bitwise Shift Left
~ Bitwise Complement
IT 3rd Sem
C++Operators:
Type Operators Meaning
Assignment
= Assignment
+= a+=b means a=a+b
−= a−=b means a=a−b
*= a*=b means a=a*b
/= a/=b means a=a/b
%= a%=b means a=a%b
>>= a>>=n means a=a>>n
<<= a<<=n means a=a<<n
&= a&=b means a=a&b
|= a|=b means a=a|b
!= a!=b means a=a!b
IT 3rd Sem
C++Operators:
Type Operators Meaning
Special
* Pointer
& Address
. Membership
:: Scope Resolution
size of()
?: Ternary Operator
++ Increment (pre and post)
−− Decrement (pre and post)
IT 3rd Sem
C++Operator Precedence:
IT 3rd Sem
Operator(s) Operation(s) Order of evaluation (precedence)
() Parentheses Evaluated first. If the parentheses are nested, the expression
in the innermost pair is evaluated first. If there are several
pairs of parentheses “on the same level” (i.e., not nested),
they are evaluated left to right.
!, +, - Logical NOT, signs Evaluated second. If there are several, they re
evaluated right to left.
*, /, or % Multiplication Division
Modulus
Evaluated third. If there are several, they re
evaluated left to right.
+ or - Addition
Subtraction
Evaluated fourth. If there are several, they are
evaluated left to right.
>, <, >=, <= Relational Operators Evaluated fifth. If there are several, they are
evaluated left to right.
==, != Equality Operators Evaluated sixth. If there are several, they are
evaluated left to right.
&& Logical AND Evaluated seventh. If there are several, they are
evaluated left to right.
| | Logical OR Evaluated eighth. If there are several, they are
evaluated left to right.
C++Expression:
IT 3rd Sem
C++Type Conversion:
Implicit or Automatic
Explicit or type casting
Syntax:
(cast-type) expression;
cast-type (expression);
For eg:
int a,b;
float c;
c = (float) a/b;
IT 3rd Sem
C++Phases of C++
programs:
IT 3rd Sem
C++ PROGRAM DEVELOPMENT GOES THROUGH SIX STEPS:Step1: Edit (using text editor to type, correct and save the program
file).
Step2: preprocessor, automatically before compile, executes to
include other text files in the file to be compiled.
Step3: Compile , the compiler translates the C++ code into machine
language (also called object-code).
Step4: Link , it is linking any used functions that are defined elsewhere
such as standard library functions, or private library for a group of
programmers, linker, links the object code with the code for the missing
functions to provide full code
Step5: Load, a program before executing , must be loaded into the
main memory, loader does this task , loading code from disk.
Step6: Execute, the computer under the control of its CPU executes
the program. Instruction by instruction.
C++IT 3rd Sem
ILLUSTRATION OF C++
PROGRAM PHASES
Phases of C++ Programs:
1. Edit
2. Preprocess
3. Compile
4. Link
5. Load
6. Execute
Loader
main
Memory
Program is created in
the editor and stored
on disk.
Preprocessor program
processes the code.
Loader puts program
in memory.
CPU takes each
instruction and
executes it, possibly
storing new data
values as the program
executes.
CompilerCompiler creates
object code and
stores
it on disk.Linker links the object
code with the libraries,
creates a.out and
stores it on disk
Editor
Preprocessor
Linker
CPU
main
Memory
.
.
.
.
.
.
.
.
.
.
.
.
Disk
Disk
Disk
Disk
Disk
C++Structure of C++ program
IT 3rd Sem
Every C++ program must have a function named main. The programmer
can choose to decompose the program into several parts (user-defined
functions). Think of main as the master and the other functions are the
servants.
The execution always starts with main.
1. Comments
2. Load <iostream.h>
3. main
3.1 Print "Welcome to C++\n"
3.2 exit (return 0)
1 // Fig. 1.2: fig01_02.cpp
2 // A first program in C++
3 #include <iostream.h>
4
5 int main()
6 {
7 cout << "Welcome to C++!\n";
8
9 return 0; // indicate that program ended successfully
10 }
Welcome to C++!
preprocessor directive
Message to the C++ preprocessor.
Lines beginning with # are preprocessor directives.
#include <iostream.h> tells the preprocessor to include
the contents of the file <iostream.h>, which includes
input/output operations (such as printing to the screen).
Comments
Written between /* and */ or following a //.
Improve program readability and do not cause the computer to
perform any action.
C++ programs contain one or more functions, one of which must be main
Parenthesis are used to indicate a function
int means that main "returns" an integer value.
Prints the string of characters contained between the quotation
marks. The entire line, including cout, the << operator, the string
"Welcome to C++!\n" and the semicolon (;), is called a
statement.
All statements must end with a semicolon.
return is a way to exit a function from a
function.
return 0, in this case, means that the
program terminated normally.
A left brace { begins the body of every function
and a right brace } ends it.
C++A Simple Program: Printing a Line of Text
IT 3rd Sem
cout
Standard output stream object
“Connected” to the screen
<<
Stream insertion operator
Value to the right of the operator (right operand) inserted into output stream (which is connected to the screen)
cout << “Welcome to C++!\n”;
\
Escape character
Indicates that a “special” character is to be output
C++A Simple Program: Printing a Line of Text
IT 3rd Sem
Escape Sequence Description
\n Newline. Position the screen cursor to the
beginning of the next line.
\t Horizontal tab. Move the screen cursor to the next
tab stop.
\r Carriage return. Position the screen cursor to the
beginning of the current line; do not advance to the
next line.
\a Alert. Sound the system bell.
\\ Backslash. Used to print a backslash character.
\" Double quote. Used to print a double quote
character.
There are multiple ways to print text
Following are more examples
C++IT 3rd Sem
1. Load <iostream.h>
2. main
2.1 Print "Welcome"
2.2 Print "to C++!"
2.3 newline
2.4 exit (return 0)
Program Output
Welcome to C++!
1 // Fig. 1.4: fig01_04.cpp
2 // Printing a line with multiple statements
3 #include <iostream.h>
4
5 int main()
6 {
7 cout << "Welcome ";
8 cout << "to C++!\n";
9
10 return 0; // indicate that program ended successfully
11 }
Unless new line '\n' is specified, the text continues
on the same line.
C++IT 3rd Sem
1. Load <iostream.h>
2. main
2.1 Print "Welcome"
2.2 newline
2.3 Print "to"
2.4 newline
2.5 newline
2.6 Print "C++!"
2.7 newline
2.8 exit (return 0)
Program Output
1 // Fig. 1.5: fig01_05.cpp
2 // Printing multiple lines with a single statement
3 #include <iostream.h>
4
5 int main()
6 {
7 cout << "Welcome\nto\n\nC++!\n";
8
9 return 0; // indicate that program ended successfully
10 }
Welcome
to
C++!
Multiple lines can be printed with one
statement.
C++Another Program: Adding Two Integers
IT 3rd Sem
>> (stream extraction operator)When used with cin, waits for the user to input a value and stores the value in the variable to the right of the operator
The user types a value, then presses the Enter (Return) key to send the data to the computer
Example:int myVariable;
cin >> myVariable;
Waits for user input, then stores input in myVariable
= (assignment operator)Assigns value to a variable
Binary operator (has two operands)
Example:sum = variable1 + variable2;
1. Load <iostream>
2. main
2.1 Initialize variables integer1, integer2,
and sum
2.2 Print "Enter first integer"
2.2.1 Get input
2.3 Print "Enter second integer"
2.3.1 Get input
2.4 Add variables and put result into sum
2.5 Print "Sum is"
2.5.1 Output sum
2.6 exit (return 0)
Program Output
1 // Fig. 1.6: fig01_06.cpp
2 // Addition program
3 #include <iostream.h>
4
5 int main()
6 {
7 int integer1, integer2, sum; // declaration
8
9 cout << "Enter first integer\n"; // prompt
10 cin >> integer1; // read an integer
11 cout << "Enter second integer\n"; // prompt
12 cin >> integer2; // read an integer
13 sum = integer1 + integer2; // assignment of sum
14 cout << "Sum is " << sum << endl; // print sum
15
16 return 0; // indicate that program ended successfully
17 }
Enter first integer
45
Enter second integer
72
Sum is 117Variables can be output using
cout << variableName.
endl flushes the buffer and prints a
newline.
Notice how cin is used to get user input.
C++
C++Built-in (Library) Function
IT 3rd Sem
Function Exponentiation
pow (x, y) x is raised to power y; (xy )
sqrt (x) Square-root of x
sin (x) Sine of x
cos (x) Cosine of x
tan (x) Tangent of x
exp (x) Exponentiation of x, ( ex)
fabs (x) Absolute Value of x, | x |
log (x) Logarithm of x (base e)
log10 (x) Logarithm of x (base 10)
floor (x) Rounding-down x
ceil (x) Rounding-up x
______etc. {there are more}_______________________
Eg.1. floor (9.2) = 9.0
Eg.2. floor (-9.8) = -10.0
Remark:you need to include <math.h> to be able to use these functions. In newer versions it is #include<cmath>
C++Common programming Errors
IT 3rd Sem
Divide by zero.
Not including iostream for input/output operations.
Forgetting the (;) at end of each statement.
If a space found between the pair-of-symbols forthe relational operators. (i.e., > = instead of >= ).
Confusing the equality == with the assignment =.
Reversing the order of the relational operators
(i.e., => instead of >=).
C++Formatted Output
IT 3rd Sem
setw can be used to specify the width of the field that the next value of output will be printed in. To use it, you must include <iomanip.h> header file.
eg1:-
int num=12;
cout<< setw(4) << num; //num will be printed in a field width of 4 character.
eg2:-
int n1=12;
int n2=197;
cout<<setw(5)<< n1 << setw(6) << n2;
eg3:- (if the value is more than the specified setw value the compiler ignores the
setw effect and print it with the minimum number of positions required.)
int num=1977;
cout<<setw(3)<<num;