Вы находитесь на странице: 1из 19

Internal representation of data

All data that is stored in a computer is converted to sequences of 0s and 1s.

A computers memory is divided into tiny storage locations known as bytes.

Each byte is divided into eight smaller storage locations known as bits.

The term Bit stands for binary digit.

A sequence of 8 bits is called bytes and a sequence of 4 bits is called nibble.

Storing Integer Numbers


In computer systems, a bit that is turned off represents the number 0 and a bit that is turned on
represents the number 1.

This corresponds perfectly to the binary numbering system.

In the binary numbering system (or binary) all numeric values are written as sequences of 0s
and 1s.

Here is an example of a number that is written in binary: 10011101

If the word length of the computer is 8 bit, the left most bit is reserved for the sign of the
number. A negative number is represented by a 1 in this bit and the remaining 7 bits are used
to store the binary equivalent of the number.

Decimal to Binary Conversion

Binary To Decimal Conversion


Storing Real Numbers (Floating Point Representation)
Storing Characters

Any piece of data that is stored in a computers memory must be stored as a binary number.

That includes characters, such as letters and punctuation marks.


When a character is stored in memory, it is first converted to a numeric code. The numeric
code is then stored in memory as a binary number.
Over the years, different coding schemes have been developed to represent characters in
computer memory.
The most important of these coding schemes is ASCII, which stands for the American
Standard Code for Information Interchange.
ASCII is a set of 128 numeric codes that represent the English letters, various punctuation
marks, and other characters. Later was extende to 8 bit to accommodate 256 different codes
For example, the ASCII code for the uppercase letter A is 65. When you type an uppercase A
on your computer keyboard, the number 65 is stored in memory.
ASCII code for A-Z is 65 90 and a-z is 97-122. ASCII of 0-9 is 48-57
Unicode coding system is used to represent all the alphabets of popular languages in the
world. It is 16 bit coding system. It can represent more than 65000 characters

Compiler
It converts a high level language (programming language) to a low level language (machine
language).
It converts source code to object code (machine code).
INTRODUCTION TO C++

C++ is an object-oriented programming language.

It was developed by Bjarne Stroustrup at AT&T Bell Laboratories.

A Simple C++ Program

Write a C++ Program to print Hello World on Screen.

#include <iostream>
using namespace std;

int main()
{
cout << Hello World;
return 0;

Pre-processor Directives
These are compiler pre-processor statements.
Preprocessor directives are lines included in a program with the character #
It gives instruction to the compiler to preprocess the information before actual compilation
starts.
The general syntax is: #include <header file> or #include "header file"

For example:
#include <iostream.h>
#include <conio.h>

The iostream File

The #define preprocessor directive creates symbolic constants.


The general syntax is: #define variable name value

For example: #define PI 3.142


Namespace
This defines a scope for the identifiers that are used in a program.

main()
main function is where a program starts execution.
Main () program is the C++ program's main structure in which we process some statements.

Output Opreator

The statement
cout<< Hello World;
causes the string in quotation mark to be displayed on the screen.
cout is a predefined object that represents the standard output stream in C++.
The operator << is called insertion or put to operator.
Input Opreator

The statement
cin >> num1;
is an input statement and causes the program to wait for the user to type in a number.
cout is a predefined object that represents the standard input stream in C++.
The operator >> is called extraction or get from operator.

Write a C++ Program to print sum and average of two numbers

#include <iostream>
using namespace std;

int main()
{
float num1, num2, sum, avg;

cout << Enter two numbers;


cin >> num1;
cin >> num2;

sum = num1+num2;
avg = sum/2;

cout << Sum of two number = << sum << \n;


cout << Average of two number = << avg;

return 0;

}
Write a C++ Program to find area and perimeter of a circle.

#include <iostream>
using namespace std;

int main()
{
float radius, area, perimeter;

cout << Enter the value of radius;


cin >> radius;

area = 3.14 * radius * radius;


perimeter = 2 * 3.14 * radius;

cout << Area of circle= << area;


cout << \n Perimeter of circle = << perimeter;

return 0;

Write a C++ Program to find area and perimeter of a rectangle.

#include <iostream>
using namespace std;

int main()
{
float length, breadth, area, perimeter;

cout << Enter the value of length and breadth;


cin >> length >> breadth;

area = length * breadth;


perimeter = 2 *( length + breadth);

cout << Area of rectangle= << area;


cout << \n Perimeter of rectangle = << perimeter;

return 0;

}
Structure of C++ Program

C++ program contain 4 sections. These section may be placed in separate code files and then
compiled independently or jointly. It is a common practice to organize a program into 3 files.
The class declarations are placed in a header file and the definitions of member functions go
into another files
Finally the main program that uses the class is placed in a third file which includes the
previous two files as well as any other files required.

This concept is based on the concept of client server model. The class definition including
member functions constitute the server that provides services to main program known as
client.
Tokens
The smallest individual unit in a program are known as tokens. C++ has the following tokens:
Keywords
Identifiers
Constants
Strings
Operators
Keywords
These are reserved words and cannot be used as names for the program variables or other user
defined program elements.

Identifiers

Example of variables
sum, Average, roll_no, year_99

Example of variable declaration


int num1;
float average;
int num1,num2;

Data Type
A data type determines the type and the operations that can be performed on the data.
C++ provides various data types and each data type is represented differently within the
computer's memory.
The various data types provided by C++ are shown in Figure
Built-In Datatypes (Primitive datatype)
The basic (fundamental) data types provided by c++ are integral, floating point and void data
type.
Among these data types, the integral and floating-point data types can be preceded by several
type modifiers.
These modifiers (also known as type qualifiers) are the keywords that alter either size or range
or both of the data types.
The various modifiers are short, long, signed and unsigned.

Integral Data Type:


The integral data type is used to store integers and includes char (character) and int (integer)
data types.
Char:
Characters refer to the alphabet, numbers and other characters (such as {, @, #, etc.) defined
in the ASCII character set.
In C++, the char data type is also treated as an integer data type as the characters are internally
stored as integers that range in value from -128 to 127.
The char data type occupies 1 byte of memory

Example char ch;

Int:
Numbers without the fractional part represent integer data.
In C++, the int data type is used to store integers such as 4, 42, 5233, -32, -745.
Thus, it cannot store numbers such as 4.28, -62.533.

Example int a;

Floating-point Data Type:


A floating-point data type is used to store real numbers such as 3 .28, 8.01, -24.53.
This data type includes float and double' data types.
Example - float f=3.14, a; double d;

Boolean :
The boo1ean data type can hold only Boolean values, that is; either true or false, where true
represents 1 and false represents 0.
It requires only one bit of storage.
The bool data type is most commonly used for expressing the results of logical operations
performed on the data.

Void : actually refers to an object that does not have a value of any type

Constants
Constant refers to fixed values that do not change during execution of a program. They
include characters, integers, floating point numbers and strings.
Literal constants do not have memory location.

Any value declared as const cannot be modified by the program.


Two ways to define constants
const int a=5;
#define pi 3.14;

Escape Sequence
Escape sequence or backslash ( \ ) character constants are a special category of constants.
These are used to represent certain non printing characters or symbols like , , ? , \ in a string
constant. Backslash ( \ ) causes escape from the normal way the characters are interpreted by the
compiler.
Example
\n - newline
\t - horizontal tab
\v - vertical tab
\b - backspace
\r - carriage return
\ - double quote
\ - single quote
\? - question mark
\\ - backslash

OPERATORS
An operator is a symbol which operates on a value or a variable. It tells compiler to perform
specific mathematical or logical manipulations on operands.
Data items on which operator acts upon are called operands.
For example: + is an operator to perform addition.
C++ programming has wide range of operators to perform various operations.

Arithmetic Operators
An arithmetic operator performs mathematical operations such as addition, subtraction and multiplication
on numerical values (constants and variables).

Increment and decrement operators


C++ has two operators increment ++ and decrement -- to change the value of an operand
(constant or variable) by 1.
Increment ++ increases the value by 1 whereas decrement -- decreases the value by
These two operators are unary operators, meaning they only operate on a single operand.

x = x+1; is the same as x++; or ++x;


x = x-1; is the same as x--; or --x;

When the operator preceeds the operand (prefix), the increment or decrement operation is performed
before using the operands value in the expression
If the operator follows the operand (postfix), the value of operand will be used before incrementing or
decrementing it.
Example 1
int x=5;
y = ++x;
Here value of y = 6 and x=6. Since x is incremented first and that value is assigned to y.

Example 2
int x=5;
y = x++;
Here value of y = 5 and x=6. Since only after assigning the value of x to y, x will be
incremented

Precedence
It is the order of evaluation of different operators in a statement. Operations with higher
precedence are carried out before other operations having lower precedence. Usage of parentheses can
forcefully change the natural order of evaluation.

Precedence Rule of Arithmetic operators:


Highest ++ , -- , - (unary)
*, / , %
Lowest + , -

Associativity
The order in which consecutive operations within the same precedence group are carried out is
known as associativity.
Associativity of arithmetic operator is from left to right.

Relational Operators
A relational operator checks the relationship between two operands.
If the relation is true, it returns 1; if the relation is false, it returns value 0.
Relational operators are used in decision making and loops.
Logical Operators
An expression containing logical operator returns either 0 or 1 depending upon whether
expression results true or false.
Logical operators are commonly used in decision making in C programming.

Assignment Operators
An assignment operator is used for assigning a value to a variable. The most common assignment
operator is =

Bitwise Operators
During computation, mathematical operations like: addition, subtraction, addition and division
are converted to bit-level which makes processing faster and saves power.
Bitwise operators are used in C++ to perform bit-level operations.
Comma Operator
Comma operators are used to link related expressions together. For example:

Example : int a=3,b,c;

The sizeof operator


The sizeof is an unary operator which returns the size of data (constant, variables, array,
structure etc). It returns the number of bytes the operand occupies in the memory.
Example :
int a = 5,x;
x = sizeof(a);
Here a is of type int which is 2 bytes in size, so it returns the value 2.

Type cast Operator


A programmer can intensionally change the type of expression in an arithmetic statement. It is
also called explicit type conversion.

Example
int a=8, b =3;
float x;
x = a / b;
Since a and b are integer, result of division of two integer number is also an integer, so x=2.0.

After type casting

x = (float) a / b;
here it will convert variable to float type and perform floating point division instead of integer
division. So x=2.66
Conditional Operator ( ? : )
It is also known as ternary operator, ie it works on 3 operands.

Syntax
conditionalexpression ? expression1 : expression2;

The first expression conditionalexpression is evaluated first.


This expression evaluates to 1 if its true and evaluates to 0 if its false
If conditionalexpression is true, expression1 is evaluated
If conditionalexpression is false, expression2 is evaluated

Write a C++ Program to find largest of two numbers using conditional operator.

#include <iostream>
using namespace std;

int main()
{
int a, b, large;

cout << Enter the value of two numbers;


cin >> a >> b;

large = a>b? a : b ;

cout << Largest Number= << large;

return 0;
}

Write a C++ Program to find largest of three numbers using conditional operator.

#include <iostream>
using namespace std;

int main()
{
int a, b, c, large;

cout << Enter the value of three numbers;


cin >> a >> b >> c;

large = a>b ? a>c ? a : c : b>c ? b : c ;

cout << Largest Number= << large;

return 0;
}
Simple and Compound Statements

Most statements in a typical C++ program are Simple statements, such as assignments or
function calls.
Simple statement is a statement followed by a semicolon.
Eg of simple statement
a = b+c;
cout << Hi;
Compound statements or blocks are brace-enclosed sequences of statements
A compound statement is a grouping of statements in which each individual statement ends
with a semi-colon.

The group of statements is called block.

Compound statements are enclosed between the pair of braces { }

Declaration Statement
A simple declaration is a statement that introduces, creates, and optionally initializes one or
several identifiers, typically variables.
Syntax:
Datatype identifier;
Example:
int a;
char ch;
float avg;

Write a C++ Program to swap two numbers

#include <iostream>
using namespace std;

int main()
{
int a, b, temp;

cout << Enter two numbers;


cin >> a >> b;

cout << Before Swapping A= << a << B= << b;

temp=a;
a=b;
b=temp;

cout << After Swapping A= << a << B= << b;

return 0;

}
Write a C++ Program to swap two numbers without temporary variable

#include <iostream>
using namespace std;

int main()
{
int a, b;

cout << Enter two numbers;


cin >> a >> b;

cout << Before Swapping A= << a << B= << b;

a=a + b;
b=a - b;
a=a - b;

cout << After Swapping A= << a << B= << b;

return 0;

Basic Input / Output statements


The standard I/O system is declared in the header file:- #include <iostream.h>
cin The standard input, normally the keyboard.
cout The standard output, normally the screen.

The standard output stream (cout)


The predefined object cout is an instance of ostream class.
The cout object is said to be "connected to" the standard output device, which usually is the
display screen.
The cout is used in with the stream insertion operator, which is written as << .
cout<<hello..;
The cout object can also be used with other member functions such as put(), write(), etc.
Some of the commonly used member functions are:
cout.put(char &ch): Displays the character stored by ch.
cout.write(char *str, int n): Displays the first n character reading from str.

The standard input stream (cin)


The predefined object cin is an instance of istream class.
The cin object is said to be attached to the standard input device, which usually is the
keyboard.
The cin is used with the stream extraction operator, which is written as >>
cin>>a>>b; .
The cin object can also be used with other member functions such as get, getline(), read(), etc.
Some of the commonly used member functions are:
cin.get(char &ch): Reads an input character and store it in ch.
cin.getline(char *buffer, int length): Reads a stream of characters into the string buffer, It
stops when it has read length-1 characters or when it finds an end-of-line character ('\n') or the
end of the file.
cin.read(char *buffer, int n): Reads n bytes (or until the end of the file) from the stream into
the buffer.
Enumeration

An enumerated type declares an optional type name and a set of zero or more identifiers that can be
used as values of the type. Each enumerator is a constant whose type is the enumeration.Creating an
enumeration requires the use of the keyword enum. The general form of an enumeration type is
enum enum-name ( enumeration-list } variable-list;

the enum-name is the enumeration's type name. The enumeration-listis comma separated.For
example, the following code defines an enumeration of colors called colors and the variable c
of type color. Finally, c is assigned the value "blue".

enum color { red, green, blue } c;

c = blue;

By default, the value of the first name is 0, the second name has the value 1, and the third has the
value 2, and so on. But you can give a name, a specific value by adding an initializer.

For example, in the following enumeration, green will have the value 5.

enum color { red, green = 5, blue };

Here, red will have value 0, blue will have a value of 6 because each name will be one greater than
the one that precedes it.

#include <iostream>
using namespace std;
int main()
{
enum week { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday };
week today;
today = Wednesday;
cout<< "Day " << today;
return 0;
}
Here the output is Day 3. Because Sunday = 0, Monday = 1, Tuesday = 2, Wednesday = 3,
Thursday = 4, Friday = 5, Saturday = 6 . Variable today is assigned value Wednesday.

Вам также может понравиться