0% found this document useful (0 votes)
11 views

Introduction to C++ for Learning and cracking Computer science exam.

C++ is an object-oriented programming language developed by Bjarne Stroustrup in the early 1980s, serving as a superset of C. The document covers essential aspects of C++ programming, including data types, operators, control structures, functions, and arrays, along with example code snippets. It also discusses the compilation process, text editors, and the importance of comments in code.

Uploaded by

ratnakarnakka33
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Introduction to C++ for Learning and cracking Computer science exam.

C++ is an object-oriented programming language developed by Bjarne Stroustrup in the early 1980s, serving as a superset of C. The document covers essential aspects of C++ programming, including data types, operators, control structures, functions, and arrays, along with example code snippets. It also discusses the compilation process, text editors, and the importance of comments in code.

Uploaded by

ratnakarnakka33
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 58

Introduction to C++

Bjarne Stroustrup at Bell Labs initially developed C++ Programming langauge


during early 1980’s

C++ is described as It is a Superset of C with support of Object Oriented


Programming Language

C++ Program can be created by using any text Editor.

Text Editor is a Software that allows you to create and edit textfiles.

After coding is over , to run program that should be error free this process is
called compilation and compiler is a software tool which is doing this task.

It converts your source code to machine level code and displays the errors on the
screen
Text Editors
• Basically we have two Text Editors
1. Turbo C++
2. Borland C++
Both can provide IDE(Integrated Development
Environment) of C++ Program. It also
provides Menubar such as File, Edit, Compile
and Run etc.
By Default all C++ programs are saved using File
Extension .cpp
Simple C++ Program
1. #include<iostream.h>
2. void main()
3. {
4. cout<<“Hello and Welcome to World of
C++\n”;
5. }
Three Important Steps of C++
Program
• Compilation
• Run
• Output
Shortcut Keys for above Steps
1. Alt+C (To Compile Program)
2. Alt+R ( To Run program)
3. Alt+F5 ( To see the output on Screen)
Data types
• Built In Data Types
• Derived Data Types
• User Defined Data Types
Built in Data Types

Name Size in Bytes Range


Char 1 One Character
Short 2 -32768 to 32767
Long 4 -2147483648 to
2147483647

Int 4 -2147483648 to
2147483647

Float 4 7 digits
Double 8 15 digits
Long double 10 19 digits
Bool 1 Yes/No
True/false
On/Off
Type Modifiers
• Signed – You can use +ve and –ve sign number
• Unsigned – You can use only +ve number
• Long – For big +ve and -ve number
• const – You cant change the value during the
program
Variables in C++
• Variable is nothing but the storage which can
store value or information for temporary
purpose. Its not permanent. User can change
value or information at any time in program.
So its called variable.
Syntax for Declaration of variable –
Data type name variable name;
Eg. int a;
Rules for variable Declaration
• Variable should begin with an alphabet or
letter
• Variable should not contain any special
character such as @,#,$,%,& etc. except
underscore (_).
• Variable should not exceed the length 32
characters.
• Variable should not be any reserved word or
keyword.
C++ Comments
Comments can be used to explain C++ code, and to make it more
readable. It can also be used to prevent execution when testing
alternative code. Comments can be singled-lined or multi-lined.

Single-line comments start with two forward slashes (//).


Any text between // and the end of the line is ignored by the
compiler (will not be executed).
Example
// This is a comment

C++ Multi-line Comments


Multi-line comments start with /* and ends with */.
Any text between /* and */ will be ignored by the compiler:
Example
/* The code below will print the words Hello World!
to the screen, and it is amazing */
cout << "Hello World!";
Arithmetic Operators

Arithmetic operators are used to perform common


mathematical operations.

There are basically three types of Arithmetic Operators.

1. Unary Arithmetic Operators – It takes only one operand


(value)
Operator Name Description Example

+ Unary Plus It assigns a sign to a +a


number

- Unary Minus It assigns a minus -b


sign to a number
Binary Arithmetic Operators
It takes two operands means Two values
Operator Name Description Example

+ Addition Adds together two x+y


values

- Subtraction Subtracts one value x-y


from another

* Multiplication Multiplies two values x * y

/ Division Divides one value by x/y


another

% Modulus Returns the division x%y


remainder
Comparison Operators
Comparison operators are used to compare two values.

Operator Name Example

== Equal to x == y

!= Not equal x != y

> Greater than x>y

< Less than x<y

>= Greater than or equal to x >= y

<= Less than or equal to x <= y


Logical Operators
Logical operators are used to determine the logic between
variables or values:

Operator Name Description Example

&& Logical and Returns true if both x < 5 && x < 10


statements are true

|| Logical or Returns true if one x < 5 || x < 4


of the statements is
true

! Logical not Reverse the result, !(x < 5 && x < 10)
returns false if the
result is true
• Assignment Operators
Assignment operators are used to assign values to
variables.
In the example below, we use
the assignment operator (=) to assign the
value 10 to a variable called x:
Example
int x = 10;
Compound Operators (Shorthand )
Operator Name Example Equivalent to

+= Add assign x += 3 x=x+3

-= Substract assign x -= 3 x=x-3

*= Multiply assign x *= 3 X=x*3

/= Division assign x \=3 X=x/3

%= Modulus assign x %=3 X=x%3


Increment and decrement operators
Operator Name Decription Example
Increases the
++ Increment value of a ++x, x++
variable by 1
Decreases the
-- Decrement value of a --x, x--
variable by 1

It Incrementing and decrementing can be of two types:


1. Prefix :First increment the value of variable and then
takes new value e.g. ++a, --b
2. Postfix: First take the value of variable and then
increment and decrement the variable e.g. a++, b--
Conditional Operator
• It is a ternary operator which takes three
operands. The value at an expression using
conditional operator is the value either 2nd or
3rd operand depending on the value of the
first operand 2ndoperan
d

Operator name Symbol Form


Conditional ?: a > b? a : b

3rd
1st operand
operand
Insertion Operator (<<):
Stream decides the flow of data. There are many types of streams in
c++ but dealing with input and output is called iostream. The
operator dealing with output is called insertion. This operator is used
along with output stream.
E.g. cout<<a;

here the value of variable a will be printed on screen.

While cout<<“a” will display character a on the screen

Extraction Operator :
It extracts the value from the input device ie keyboard and assigns
the value to variable. Its dealing with input stream. E.g.cin>>a;
Comma Operator:
Multiple operations can be combined into one expression using
comma operator
e.g. int m,n,o;
Control Structures

1. Branching statements
2. Looping Statements
Branching statements
• It statement: In this statement If the condition is true
then Action statement is executed.
syntax : if(condition)
{
Action statement;
}
e.g. int age;
age = 20;
if (age>18)
{
cout<<“You are eligible for voting”
}
If else statement
• Syntax : if (condition)
{
Action statement1;
else
Action Statement2;
}
In this statement, If condition is true then Action
statement1 is executed. If condition is false then
Action statement2 is executed.
Else if ladder
• Syntax: if(condition1)
{
Action statement1;
else if(condition2)
Action statement2;
else if(condition3)
……
else
default statement;
}
In this statement, If condition1 is true then action statment1 is
executed and so on if no condition is satisfied then default
statement is executed.
WAP in c++ to display grade of candidate using Else if ladder
#include<iostream.h>#include<conio.h>
void main()
{clrscr();
float per;
cout<<"Enter your percentage";
cin>>per;
if(per>=75)
{
cout<<"You have got First Class with Distinction";
}
else if(per>=60)
{
cout<<"You have got First Class";
}
else if(per>=45)
{
cout<<"You have got Second Class";
}
else if(per>=35)
{
cout<<"You have got Pass Class";
}
else
cout<<"Sorry!!! You are failed";
WAP in C++ to accept two numbers and display the addition/Substraction/Multiplication/Division of two
numbers as per the choice of end user using Else if ladder
#include<iostream.h>
#include<conio.h>
void main()
{
int a,b,c,d,e;
char oper;
float f;
cout<<"Enter any two numbers";
cin>>a>>b;
cout<<"Enter your operator for addition/Subtraction/Multiplication or division +,-,* or /";
cin>>oper;
if(oper=='+')
{
c=a+b;
cout<<"Addition of two numbers is"<<c;
}
else if(oper=='-')
{
d=a-b;
cout<<"Addition of two numbers is"<<d;
}
Program Continues…..
else if(oper=='*')
{
e=a*b;
cout<<"Addition of two numbers is"<<e;
}
else if(oper=='/')
{
f=a/b;
cout<<"Addition of two numbers is"<<f;
}
else
cout<<"Invalid Operator”;
}
Looping statements
• While loop
• For loop
1. While loop : In this loop, Until the condition
is true the block of code is executed.
Syntax : while(condition)
{
block of code
}
Write a program in C+ to display first 10 numbers using
while loop

#include<iostream.h>
void main()
{
int n=1;
while(n<11)
{
cout<<n<<"\nf";
n++;
}
}
Write a program in C+ to display sum first 10 numbers
using while loop

#include<iostream.h>
void main()
{
int n=1, sum=0;
while(n<11)
{
Sum=sum+n;
n++;
}
Cout<<“The sum of first 10 numbers is:”<<sum;
}
Write a program in C+ to accept any five digits number and
display the sum of digits of an accepted number using
while loop
#include<iostream.h>
void main()
{
int n, r, sum=0;
Cout<<“Enter any five digits number”
Cin>>n;
while(n>0)
{
r=n%10;
sum=sum+r;
n = n /10;
}
Cout<<“The sum of digits of numbers is:”<<sum;
}
Write a program in C+ to accept any five digits number and
display number in reverse order using while loop
#include<iostream.h>
void main()
{
int n, r, sum=0;
Cout<<“Enter any five digits number”
Cin>>n;
while(n>0)
{
r=n%10;
sum=sum*10+r;
n = n /10;
}
Cout<<“The sum of digits of numbers is:”<<sum;
}
For loop
Syntax:
for(initialization;condition;increment/decrement)
{
block of code;
}

In this loop, it checks the condition if it is true the block of code is


executed. If the condition is false then you will come out from the
loop
Initialization – Starting value/Initial Value
Condition – checking the condition
Increment/decrement – How you want to increment/decrement the
starting value.
Write a program in C++ to display the
sum of first 10 numbers using for loop
#include<iostream.h>
void main()
{
int sum=0;
for(int n=1;n<11;n++)
{
sum=sum+n;
}
cout<<"The sum of first 10 no is"<<sum;
}
Nested For loop
When you have loop within a loop then that is called
nested for loop

Syntax:
For( initialization; condition; increment/decrement)
{
Body of outer loop
For(initialization; condition ; increment/decrement)
{
Body of inner loop
}
}
Write a program in C++ to display the following output
*
**
***
****
*****
#include<iostream.h>
void main()
{
for(int i=1;i<=5;i++)
{
for( int j=1;j<=5;j++)
{
cout<<“*”<<“\t”;
}
cout<<“\n”;
}
Write a program in C++ to display the following output
1
12
123
1234
12345
#include<iostream.h>
void main()
{
for(int i=1;i<=5;i++)
{
for( int j=1;j<=5;j++)
{
cout<<j<<“\t”;
}
cout<<“\n”;
}
Write a program in C++ to display the multiplication
table of 4 and 5

#include<iostream>
void main()
{
cout << "\nMultiplication Table for 4 and 5 are\n";
for (int i = 4; i < 6; i++)
{
for (int j = 1; j <= 10; j++)
{
cout << i << " * " << j << " = " << i * j <<"\n";
}
cout <<"\n ==========\n";
}
}
Functions in C++
• To make program manageable functions are
used in c++.
• Functions/Methods/Operations/Messages/
Procedures/Subprograms
• There are two types of functions –
• 1. Built in Functions – exit(), main()
• 2. User defined Functions
Syntax
Return type function name (parameter/argument list)
{
Local variable;
Body of function;
Return statement;
}
void area(double); //function prototype
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
double r;
cout<<"Enter the radius value:";
cin>>r;
area(r);
}
void area(double r)
{
double area1;
area1=3.142*r*r;
cout<<"The area of circle is:"<<area1;
}
Passing Techniques in C++ functions
• Pass by Value
• Pass by reference
• Reference using reference
Pass by value: In this technique, if user passes the
value by using pass by value technique, then copy
of original variable will be created in the body of
function. So whatever changes made by you in the
body of the function will not be reflected in the
main function. You can see the unchanged output
on the output screen.
Function overloading
• If a function is declared more than once with
the same name in the program then it is said
to be function overloading.
• But function should differ in the number of
parameters.
void area(double);void area(double,double);
#include<iostream.h>
#include<conio.h>
void main()
{clrscr();
double r,l,b;
cout<<"Enter the radius value:";
cin>>r;
area(r);
cout<<"Enter tha values of length and breadth";
cin>>l>>b;
area(l,b);
}
void area(double r)
{
double area1;
area1=3.142*r*r;
cout<<"The area of circle is:"<<area1;
}
void area(double l,double b)
{
double area2;
area2=l*b;
cout<<"The area of rectangle is:"<<area2;
}
Arrays in C++
• Array is a set of elements which are of same type.
• Array starts from 0 index number and last position is
for null value i.e. reserved
• Array size or dimension can not be changed during the
execution of the program.
Declaration syntax :
datatype arrayname[size/dimension];
e.g. int roll_no[10];
Int roll_no[10]={101,102,103,104,105,106,107,108,109,
110};
#include<iostream.h>
void main()
{
int rollno[10];
cout<<"Enter any ten roll numbers";
for( int i=0;i<10;i++)
{
cin>>rollno[i];
}
cout<<"The ten roll numbers are";
for(int j=0;j<10;j++)
{
cout<<rollno[j]<<"\n";
}
}
Multidimensional Array
• Syntax : datatype arrayname[row][column];

e.g. int number[3][3];


0,0 0,1 0,2
1,0 1,1 1,2
2,0 2,1 2,2
Array of Characters (String)
• Syntax: datatype arrayname[size];
• E.g. char str[10];

e.g char str[5]={‘H’,’E’,’L’,’L’,’O’};

Cout<<str;
String Functions
• There are four string functions in C++
1. Strcat(): String concatenate
2. Strcmp(): String comparison
3. Strcpy(): String copy
4. Strlen(): String length

It requires a special header file i.e.


#include<string.h>
String Concatenate
• It appends the second string at the end of first string

Syntax : char* strcat ( char*src, char *dest)

2. String comparison:
It compares two strings and returns the value
int strcmp( char *s1, char *s2)
S1>s2 returns 1
s1=s2 returns 0
S1<s2 returns -1
String copy
• It copies the first string and paste it in another
string
Syntax : char* strcpy(char *src, char * dest)

String length:
It returns the length(no of characters) of the
string
Syntax : int strlen(string s1)
Pointers in c++
• Pointer is nothing but the address of a memory
location.
1. & - reference operator -
2. * - dereference operator –
Int a =10;
a++; 12 30 21
Int *ptr; 0 1 2

Ptr=&a[2]; pointer arithmetic


Cout<<*ptr;
Ptr++;
Syntax : datatype *pointervariable;
e.g. int *ptr;
Int *ptr;
int a = 10;
ptr=&a;
cout<<*ptr;

Memory management Operators:-


1.new – allocates the memory
2. delete – releases the memory

int *ptr;
pointervariable=new datatype value;
e.g. ptr=new int 50;
cout<<*ptr;
delete ptr;
W a p in C++ to accept 10 elements using an array and display the
elements using pointers

#include<iostream.h>
void main()
{
int rollno[10];
cout<<"Enter any ten roll numbers";
for( int i=0;i<10;i++)
{
cin>>rollno[i];
}
int *ptr;
ptr=rollno; // equivalent to ptr = & rollno[0]
cout<<"The ten roll numbers are";
for(int j=0;j<10;j++)
{
cout<<*ptr<<"\n";
ptr++;
}
}

You might also like