0% found this document useful (0 votes)
22 views74 pages

CPP Notes

Notes for c++

Uploaded by

Sai Vighnesh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views74 pages

CPP Notes

Notes for c++

Uploaded by

Sai Vighnesh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 74

UNIT-VI

C++ Character Set:

A programming language is designed to help process certain kinds of data containing of numbers,
characters and strings and to provide useful output known as information

The task of processing data is accomplished by executing a sequence of precise instructions called a
program.

These instructions are formed using certain symbols and words accordingly to some rigid rules known
as syntax rules.

Every program instruction must confirm precisely to the syntax rules of the program.

The characteristics in C++ are grouped into the following categories.

1. Letters.
Uppercase(A-Z), Lower Case(a-z)

2. Digits:- 0..9
3.Special characters:-
, & . ^ ; * : - ? + ‘ < > “ # ! | \(backslash) /(slash) ~ {} [] () $ % etc.

4.White Spaces:
Blank Space.
Horizontal tab
Vertical tab.
New Line
Form Feed

Trigraph characters:

Many non- English keywords do not support all the special characters. The concept of trigraph
sequences to provide a way to enter certain characters that are not available on some keyboards. Each
trigraph sequence consists of three characters (two question marks followed by another character).

Trigraph Characters:

Trigraph Sequence Translation Character

??= #

??( [

??/ \
??) ]

??‘ ^

??< {

??! | (Vertical Bar)

??> }

??- ~ (Tilde)

C++ Tokens: Tokens are individual words and punctuation marks in passage of text. In C++, program
the smallest individual units are known as C++ Tokens. C has six types of Tokens.

1. Keywords- Example: int,while

2. Identifiers- Example: amount,name

3. Constants- Example: 65,-76

4. Strings- Example: “hello” “CPP”

5. Operators: Example: +,-,*, /

6. Special Symbols- Example: $,[],()

Keywords:
keywords are the words that convey a special meaning to the c compiler. The keywords cannot be used
as variable names because by doing so.

auto break case char const continue default do double else enum extern float
for goto if int long register return short signed sizeof static struct switch

typedef union unsigned void volatile while asm dynamic_cast namespace


reinterpret_cast bool explicit new static_cast false catch operator template friend
private class this inline public throw const_cast delete mutable protected true
try typeid typename using virtual wchar_t

Identifiers:
Identifiers are used as the general terminology for the names of variables, functions and arrays. These
are user defined names consisting of arbitrarily long sequence of letters and digits with either a letter or
the underscore(_) as a first character.

There are certain rules that should be followed while naming c identifiers:

They must begin with a letter or underscore (_).

They must consist of only letters, digits, or underscore. No other special character is allowed.
It should not be a keyword.

It must not contain white space.

It should be up to 31, first 31 characters are significant.

Examples:

Name Remark
_ a9 Valid
void Invalid as it is a keyword
a_b valid
x* Invalid
ab Invalid –blank space not allowed.

Constants:
The constants refer to fixed values that the program may not alter during its execution. These fixed
values are also called literals.
Constants can be of any of the basic data types like an integer constant, a floating constant, a character
constant, or a string literal. There are also enumeration constants as well.
The constants are treated just like regular variables except that their values cannot be modified after their
definition.

Integer literals
An integer literal can be a decimal, octal, or hexadecimal constant. A prefix specifies the base or radix:
0x or 0X for hexadecimal, 0 for octal, and nothing for decimal.

An integer literal can also have a suffix that is a combination of U and L, for unsigned and long,
respectively. The suffix can be uppercase or lowercase and can be in any order.

Here are some examples of integer literals:


212 /* Legal */
215u /* Legal */

0xFeeL /* Legal */
85 /* decimal */
0213 /* octal */
0x4b /* hexadecimal */
30 /* int */
30u /* unsigned int */
30l /* long */
30ul /* unsigned long */

Floating-point literals

A floating-point literal has an integer part, a decimal point, a fractional part, and an exponent part. We
can represent floating point literals either in decimal form or exponential form.

While representing using decimal form, we must include the decimal point, the exponent, or both and
while representing using exponential form; you must include the integer part, the fractional part, or both.
The signed exponent is introduced by e or E.

Examples of floating-point literals:

3.14159 /* Legal */

314159E-5L /* Legal */

510E /* Illegal: incomplete exponent */ 210f /* Illegal: no decimal or exponent */

.e55 /* Illegal: missing integer or fraction */

Character constants

Character literals are enclosed in single quotes, e.g., 'x' and can be stored in a simple variable of char
type.

A character literal can be a plain character (e.g., 'x'), an escape sequence (e.g., '\t').

There are certain characters in C++ when they are preceded by a backslash they will have special
meaning and they are used to represent. Here, we have a list of some of such escape sequence codes:

Escape sequence Meaning

\\ \ character

\‘ ' character

\“ " character

\? ? Character

\a Alert or bell

\b Backspace

\f Form feed

\n Newline

\r Carriage return
\t Horizontal tab

\v Vertical tab

\ooo Octal number of one to three digits

\xhh . . . Hexadecimal number of one or more digits

String literals

String literals or constants are enclosed in double quotes "". A string contains characters that are similar
to character literals: plain characters, escape sequences.

We can break a long line into multiple lines using string literals and separating them using whitespaces.

Here are some examples of string literals. All the three forms are identical strings.

"hello,how are you“

Defining Constants

There are two simple ways in C++ to define constants:

Using #define preprocessor.

Using const keyword.

The #define Preprocessor

Syntax:

#define identifier value;

Program using #define

#include <iostream.h>

#define LENGTH 10

#define WIDTH 5

int main()

int area;

area = LENGTH * WIDTH;

cout<<"value of area :"<< area;

return 0;

}
The const Keyword
we can use const prefix to declare constants with a specific type as follows:

const type variable = value;

Example :

#include <iostream.h>

void main()

const int LENGTH = 10;

const int WIDTH = 5;

int area;

area = LENGTH * WIDTH;

cout<<"value of area : “<< area;

Variables:
A variable is nothing but a name given to a storage area that our programs can manipulate.

The name of a variable can be composed of letters, digits, and the underscore character. It must begin
with either a letter or an underscore. Upper and lowercase letters are distinct because C is case-sensitive.

TYPE DESCRIPTION

char Typically a single octet (one byte). This is an integer type.

int The most natural size of integer for the machine

Float A single-precision floating point value

double A double-precision floating point value

void Represents the absence of type.

Variable Definition in C++:


A variable definition means to tell the compiler where and how much to create the storage for the
variable. A variable definition specifies a data type and contains a list of one or more variables of that
type as follows:
type variable_list;

Here, type must be a valid C data type .variable_list may consist of one or more identifier names
separated by commas. Some valid declarations are shown here:

Examples:

int i, j, k;

char c, ch;

float f, salary;

double d;

Variables can be initialized (assigned an initial value) in their declaration. The initializer consists of an
equal sign followed by a constant expression as follows:

type variable_name = value;

Examples are:

extern int d = 3, f = 5; // declaration of d and f.

int d = 3, f = 5; // definition and initializing d and f.

char x = 'x'; // the variable x has the value 'x'.

Data Types:
In the C++ programming language, data types refer to an extensive system used for declaring variables
or functions of different types. The type of a variable determines how much space it occupies in storage
and how the bit pattern stored is interpreted.

The types in C++ can be classified as follows:

1. Basic Types:

They are arithmetic types and consist of the three types:

Integer types and (b) floating-point types) character.

2. Enumerated Type

They are again arithmetic types and they are used to define variables that can only be assigned certain
discrete integer values throughout the program.

3. The type void:

The type specifier void indicates that no value is available.

4. Derived Data types:


They include (a) Pointer types, (b) Array types, (c) Structure types, (d) Union types and (e) Function
types.

Data Types :

Type Storage size Value range


char 1 byte -128 to 127 or 0 to 255
unsigned char 1 byte 0 to 255
signed char 1 byte -128 to 127
int 2 or 4 bytes -32,768 to 32,767 or -2,147,483,648 to 2,147,483,647
unsigned int 2 or 4 bytes 0 to 65,535 or 0 to 4,294,967,295
short 2 bytes -32,768 to 32,767
unsigned short 2 bytes 0 to 65,535
long 4 bytes -2,147,483,648 to 2,147,483,647
unsigned long 4 bytes 0 to 4,294,967,295
float 4 byte 1.2E-38 to 3.4E+38
double 8 byte 2.3E-308 to 1.7E+308
long double 10 byte 3.4E-4932 to 1.1E+4932

Operators:
An operator is a symbol that tells the compiler to perform specific mathematical or logical
manipulations. C++ language is rich in built-in operators and provides the following types of operators:

 Arithmetic Operators

 Relational Operators

 Logical Operators

 Bitwise Operators

 Assignment Operators

 Misc Operators.

Arithmetic Operators.

1 + Addition or Unary plus

2 - Subtraction or Unary Minus

3 * Multiplication

4 / Division
5 % Modulus

/* Program to demonstrate the working of arithmetic operators in C. */

#include

void main()

int a=9,b=4,c;

c=a+b;

cout<<"a+b=\n"<<c;

c=a-b;

cout<<"a-b=\n"<<c;

c=a*b;

cout<<"a*b=\n"<<c;

c=a/b;

cout<<"a/b=\n"<<c;

c=a%b;

cout<<"Remainder when a divided by b=\n"<<c;

Increment and decrement operators


 In C++, ++ and -- are called increment and decrement operators respectively. Both of these
operators are unary operators, i.e, used on single operand. ++ adds 1 to operand and – subtracts 1 to
operand respectively.

Difference between ++ and -- operator


 as postfix and prefix When i++ is used as prefix(like: ++var), ++var will increment the value of var and
then return it but, if ++ is used as postfix(like: var++), operator will return the value of operand first and
then only increment it.
Assignment Operators.
The most common assignment operator is =. This operator assigns the value in right side to the left side.

Operator Example Equals to

= a=b a=b

+= a+=b a=a+b

-= a-=b a=a-b

*= a*=b a=a*b

/= a/=b a=a/b

%= a%=b a=a%b

Relational Operator:
Relational operators checks relationship between two operands. If the relation is true, it returns value 1
and if the relation is false, it returns value 0.

Operator Meaning Example

== Equal to 4==2(false)

> Greater than 4>2,returns 1.

< Less than 4<2,returns 0.

>= Greater than or equal to 4>=2,returns 1.

<= Less than or equal to 4<=2,returns 0.

!= Not equal to 4!=2,returns 1.


Logical Operators:
Logical operators are used to combine expressions containing relation operators. In C++, there are 3
logical operators:

Operator Meaning Example

&& Logical AND If c=5 and d=2 then,((c==5) && (d>5)) returns false.

|| Logical OR If c=5 and d=2 then, ((c==5) || (d>5)) returns true.

! Logical NOT If c=5 then, !(c==5) returns false.

Conditional Operator
Conditional operator takes three operands and consists of two operators ? And :. Conditional operators
are used for decision making in C++.

For example: c=(c>0) ? 10 : -10;

If c is greater than 0, value of c will be 10 but, if c is less than 0, value of c will be -10.

Bitwise Operators.
A bitwise operator works on each bit of data. Bitwise operators are used in bit level programming.

Operator Meaning

& Bitwise AND

| Bitwise OR

^ Bitwise XOR

~ Bitwise Complement

<< Left Shift

>> Right Shift


Other Operators

Comma Operator:
Comma operators are used to link related expressions together.

For example:

int a,c=5,d;

The sizeof operator


It is a unary operator which is used in finding the size of data type, constant, arrays, structure etc.

Address Operator: & Returns the address of an variable

Indirection Operator: * Pointer to a variable

Program:
#include <iostream.h>

int main()

int a;

float b;

double c;

char d;

cout<<"Size of int=<<sizeof(a)<<”\n”;

cout<<"Size of float= "<<sizeof(b)<<”\n”;

cout<<"Size of double="<<sizeo©<<”\n”;

cout<<"Size of char="<<sizeof(d)<<”\n”;

return 0;

Precedence and Associativity.


Precedence is used to determine the order in which different operators in a complex expression
are evaluated. Associativity is used to determine the order in which operators with the same precedence
are evaluated in a complex expression.
SNO Operator Associativity

1 (expr) [index] -> . Left ==> Right

2 ! ~ ++ -- Right  Left
(type) sizeof
Unary operator: + - * &

3 * / % Left ==> Right

4 + - Left ==> Right

5 << >> Left ==> right

6 < <= > >= Left ==> Right

7 == != Left ==> Right

8 Binary operator: & Left ==> Right

9 Binary operator: ^ Left ==> Right

10 Binary operator: | Left ==> Right

11 && Left ==> Right

12 || Left ==> Right

13 expr ? true_expr : false_expr Right  Left

14 += -= *= /= <<= Right  Left


&= ^= |= %= >>= =

15 , Left ==> Right

Increment and Decrement Operators


 prefix increment (++a)

 postfix increment (a++)

 prefix decrement(- -a)

 postfix decrement (a- -)

 /* prefix operators */
#include<iostream>

using namespace std;

void main()

cout<<”enter a,b values”;

cin>a>>b;

c = b * (++a) + 5 * (a++);

cout<<“ a = ”<< a;

cout<<“\n b =”<<b;

cout<<“\n c =”<<c;

Output:

a=9

b = 12

c = 153 ( 12 * 9 + 5 * 9)

If ++ is after the operand, as in a++, the increment takes place after the expression is evaluated.

If ++ is before the operand, as in ++a, the increment takes place before the expression is evaluated.

 /* prefix and postfix operators */

#include<iostream.h>

void main()

int a = 7, b = 12, c;

c = b * (a++) + 5 * (++a);

cout<<“ a =”<< a;

cout<<“\n b = ”<<b;

cout<<“\n c =”<<c;
}
Output:

a=9

b = 12

c = 136 ( 12 * 8 + 5 * 8) .

 /* postfix operators */

#include<iostream.h>

int main() {

int a = 7, b = 12, c;

c = b * (a++) + 5 * (a++);

cout<<“ a = ”<< a;

cout<<“\n b =”<<b;

cout<<“\n c =”<<c;

• C++ Program to find area and circumference of circle

#include<iostream>
using namespace std;

int main()

{ int rad;

float pi=3.14,area,ci;
cout<<"\n Enter radius of circle: ";
cin>>rad;
area = pi * rad * rad;
cout<<"\n Area of circle : “<<area;
ci = 2 * pi * rad;
cout<<"\n Circumference : "<<ci;
}
Type Conversion:
The type conversion or type casting refers to the process of changing an entity of one type into another.

There are two types of conversion.

1.Implicit conversion.

2.Explicit Conversion

• Implicit Conversion:

It is an automatic type conversion. In a mixed type expression ,data of one or more sub types can be
converted to a super type as needed at runtime. So the program will run correctly.

Ex: long b;

int c;

if (c>b) b=c;

if(b==c) a+=2

Although a, b, c belong to different data types, they will be automatically converted to equal data types
each time.

Data can be lost when floating point representations are converted to integral representations as the
fractional components of the floating point values will be truncated.

Conversely, converting from an integral representation to a floating point one can also lose precision,
since the floating point may be unable to represent the integer exactly.

• Explicit Conversion

The explicit conversion can be made possible to convert one data type to another by forcefully and it is
different from the implicit conversion.

Syntax: variable1=(data type) variable2

int a=10;

float (a);

Now float(a) will contain 10.000000.

• Example2:

double d=6.5;

double b=8.5;

int result=(int)(d)+(int)(b)

result is 14 not 15.


• Input & Output in C++
We have two methods for providing data to the program.

1.Assigning the data to the variables in a program.

2.By using the input/output statements several functions are available for input/output operations

cout<<”factorial of number=”<<fact ;

Control Statements
In a program all the instructions are executed sequentially by default. In some situation we may have to
change the execution order of statements based on condition or to repeat a set of statements until certain
conditions are met .In such situations conditional and control statements are very useful.

C++ language provides 3 types of control statements.


1) Sequential statements: In which instructions are executed in sequence.

Example:

i=i+1;

j=j+1;

These statements are executed one by one.

2) Selection statements: Here the sequence of the instructions are determined by using the result of the
condition.

Example:

if(x>y)

i=i+1;

else

j=j+1

3) Iteration Structure: In which statements are repeatedly executed .These forms program loops.

Example:

for(i=0;i<=9;i++)
{
i=i+1;
}
where the statement i=i+1 will be executed 10 times.

If Statement:
The if staement is a decision making statement.It is used to control the flow of execution of statements
and also used to test logically whether the condition is true or false .It is always used in conjunction with
condition .The statement is used when a question require answer.

Syntax1:
if(condition)
statement;
Syntax2:
if(condition)
{
statements;
}
If the condition is true, then the statements are executed. The statements may be a single or group of
statements.

If-else Statement:

It is two way decision making statement and always used in conjunction with condition .It is used to
control the flow of execution and also used to carry out the logical test and then pickup one of the two
possible actions on the logical test.

It is used to execute some statements when the condition is true and execute some other statements,
when the condition is false.

Syntax:

if(condition)

statements;

else

statements;

Nested if-else Statement:

When a series of if-else statements are occurred in a program. we can write an entire if-else statement in
another if-else statement called nesting and the statement is called nested if.

Syntax: if(condition)
{ if(condition)

{ statement2;

else {

statement3; }

} else

statement1;

If–else ladder:

Nested if statements can become complex if there are more than 3 alternatives and indentation is not
consistent, it may be different for us to determine the logical structure of the if statement. In this
situation we can use the nested if as the else if ladder.

Syantax: if(condition1)

{ staement1;

else if(condition2)

{ statement2;

else if(condition3)

{ staement3;

else { default statement;

Flowchart:

simple if:
• /* check a citizen is eligible for voting */
#include<iostream.h>

int main()

int age;

cout<<“Enter the age : ”;

cin>>age;

if(age >= 18)

cout<<“Eligible for voting…”;

IF-ELSE FLOW CHART


/* print a number is even or odd */
#include<iostream.h>

int main()

int number;

cout<<“Enter a number : “;

cin>>number;

if((number %2) == 0)

cout<<“ even number=”<<number;

else

cout<<”odd number=.”<<number;

}
• /* check whether a year is leap year or not */
#include<iostream.h>

void main()

int year;

cout<<"Enter the year ?";

cin>>year;

if((year %100) == 0)

if((year % 400) == 0)

cout<<"leap year=."<<year;

else

cout<<"not leap year=."<<year;

else

if((year % 4) == 0)
cout<<"leap year.="<<year;

else

cout<<"not leap year.="<<year;

/* program to print the grade of student */


#include<iostream.h>

void main()

int marks;

cout<<"Enter marks ? ";

cin>>marks;

if(marks >= 75)

cout<<"Distinction";

else if(marks >= 60)

cout<<"First class";

else if(marks >= 50)


cout<<"Second class";

else if(marks >= 35)

cout<<"Third class";

else

cout<<"Failed";

/* Write a C++ program to find the roots of a quadratic equation. */


#include<iostream.h>

#include<math.h>

void main()

float a,b,c,root1,root2;

clrscr();

cout<<"\n Enter values of a,b,c for finding roots of a quadratic eq:\n";

cin>>a>>b>>c;

/*checking condition*/

if(b*b>4*a*c)

root1=-b+sqrt(b*b-4*a*c)/2*a;

root2=-b-sqrt(b*b-4*a*c)/2*a;

cout<<"\n*****ROOTS ARE*****\n";

cout<<"\n root1=”<<root1<<” “<<”\n root2="<<root2;

else

cout<<"\n Imaginary Roots.";

}
SWITCH CASE:
A switch statement allows a variable to be tested for equality against a list of values. Each value is called
a case, and the variable being switched on is checked for each switch case.

SYNTAX:
switch(expression)

case constant-expression : statement(s); break;

case constant-expression : statement(s); break;

/* you can have any number of case statements */

default : statement(s);

The following rules apply to a switch statement:

 The expression used in a switch statement must have an integral or enumerated type, or be of a
class type in which the class has a single conversion function to an integral or enumerated type.

 You can have any number of case statements within a switch. Each case is followed by the value
to be compared to and a colon.

 The constant-expression for a case must be the same data type as the variable in the switch, and
it must be a constant or a literal.

 When the variable being switched on is equal to a case, the statements following that case will
execute until a break statement is reached.

 When a break statement is reached, the switch terminates, and the flow of control jumps to the
next line following the switch statement.

 Not every case needs to contain a break. If no break appears, the flow of control will fall through
to subsequent cases until a break is reached.

 A switch statement can have an optional default case, which must appear at the end of the
switch. The default case can be used for performing a task when none of the cases is true. No
break is needed in the default case.
• /* program to simulate a simple calculator */
#include<iostream.h>
void main()
{
float a,b;

char opr;
cout<<"Enter number1 operator number2 : ";
cin>>a>>opr>>b;
switch(opr)
{
case '+':

cout<<"Sum : “<<(a + b);


break;
case '-':
cout<<"Difference : "<<(a - b);
break;
case '*':
cout<<"Product : "<<(a * b);
break;
case '/':

cout<<"Quotient : "<<(a / b);


break;
default:
cout<<"Invalid Operation!";
}
}

/* Write a C++ program, which takes two integer operands and one operator form
the user, performs the operation and then prints the result. (Consider the
operators +,-,*, /, % and use Switch Statement) */
#include<iostream.h>

#include<conio.h>

void main()

int a,b,res,ch;

cout<<"\t *********************";

cout<<"\n\tMENU\n";

cout<<"\t********************";

cout<<"\n\t(1)ADDITION";

cout<<"\n\t(2)SUBTRACTION";

cout<<"\n\t(3)MULTIPLICATION";

cout<<"\n\t(4)DIVISION";

cout<<"\n\t(5)REMAINDER";

cout<<"\n\t(0)EXIT";

cout<<"\n\t********************";

cout<<"\n\n\tEnter your choice:";


cin>>ch;

if(ch<=5 & ch>0)

cout<<"Enter two numbers:\n";

cin>>a>>b;

switch(ch)

case 1:

res=a+b;

cout<<"\n Addition:"<<res;

break;

case 2:

res=a-b;

cout<<"\n Subtraction:%d",res;

break;

case 3:

res=a*b;

cout<<"\n Multiplication:"<<res;

break;

case 4:

res=a/b;

cout<<"\n Division:”<<res;

break;

case 5:

res=a%b;

cout<<"\n Remainder:"<<res;

break;
case 0:

cout<<"\n Choice Terminated";

exit();

break;

default:

cout<<"\n Invalid Choice";

LOOPS:
There may be a situation, when you need to execute a block of code several number of times.

Programming languages provide various control structures that allow for more complicated execution
paths.

A loop statement allows us to execute a statement or group of statements multiple times and following is
the general form of a loop statement in most of the programming languages:

FOR LOOP
A for loop is a repetition control structure that allows you to efficiently write a loop that needs to
execute a specific number of times.

Syntax:

The syntax of a for loop in C programming language is:

for ( init; condition; increment )


{

statement(s);

Here is the flow of control in a for loop:

The init step is executed first, and only once. This step allows you to declare and initialize any loop
control variables. You are not required to put a statement here, as long as a semicolon appears.

Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body of
the loop does not execute and flow of control jumps to the next statement just after the for loop.

After the body of the for loop executes, the flow of control jumps back up to the increment statement.
This statement allows you to update any loop control variables. This statement can be left blank, as long
as a semicolon appears after the condition.

The condition is now evaluated again. If it is true, the loop executes and the process repeats itself (body
of loop, then increment step, and then again condition). After the condition becomes false, the for loop
terminates.

• FLOWCHART
FORLOOP

/* check whether a number is prime or not */


#include<iostream.h>

int main()

int n,i,factors = 0;

cout<<"Enter a number : ";

cin>>n;

for(i = 1; i <= n; i++)

if((n % i)==0) ++factors;

if (factors == 2)

cout<<"prime number."<<n;

else

cout<<" not prime number."<<n;

}
/* Write a C++ program to generate all the prime numbers between 1 and n, where n is a
value supplied by the user. */
#include <iostream.h>

void main()

int no,counter,counter1,check;

cout<<"<-----------------------PRIME NO. SERIES------------------------>";

cout<<"\n\n\n\t\t\tINPUT THE VALUE OF N: ";

cin>>no;

cout<<"\n\nTHE PRIME NO. SERIES B/W 1 TO \n\n"<<no;

for(counter = 1; counter <= no; counter++)

check = 0;

//THIS LOOP WILL CHECK A NO TO BE PRIME NO. OR NOT.

for(counter1 = counter-1; counter1 > 1 ; counter1--)

if(counter%counter1 == 0)

check++; // INCREMENT CHECK IF NO. IS NOT A PRIME NO.

break;

if(check == 0)

cout<<counter;

}
/* Write a C++ program to calculate the following Sum:

Sum=1-x2/2! +x4/4!-x6/6!+x8/8!-x10/10! */
#include <iostream.h>

#include <math.h>

void main()

int counter,f_coun;

float sum=0,x,power,fact;

cout<<"<-----------------------PROGRAM FOR SUM OF EQ. SERIES----------------------->";

cout<<"\n\n\tEQUATION SERIES : 1- X^2/2! + X^4/4! - X^6/6! + X^8/8! - X^10/10!";

cout<<"\n\n\n\tENTER VALUE OF X : ";

cin>>x;

for(counter=0, power=0; power<=10; counter++,power=power+2)

fact=1;

//CALC FACTORIAL OF POWER VALUE

for(f_coun=power; f_coun>=1; f_coun--)

fact *= f_coun;

//EQ. FOR SUM SERIES

sum=sum+(pow(-1,counter)*(pow(x,power)/fact));

cout<<"SUM : %f",sum);

}
Program to display 10 numbers
#include <iostream.h>
int main ()
{
for( int a = 0; a <=9; a = a + 1 )
{

cout<<"value of a: =\n"<< a;
}
}

/* The total distance travelled by vehicle in ’t’ seconds is given by distance =


ut+1/2at2 where 'u' and 'a' are the initial velocity (m/sec.) and acceleration
(m/sec2). Write C++ program to find the distance travelled at regular intervals of
time given the values of 'u' and 'a'. The program should provide the flexibility to the
user to select his own time intervals and repeat the calculations for different values
of 'u' and 'a'.*/
#include <iostream.h>
#include <math.h>
void main()
{
int tim_intrval, counter,time;
float accl, distance=0, velos;
cout<<"PROGRAM FOR CALC TOTAL DISTANCE TRAVELED BY A VECHIAL”;
cout<<"\n\n\n\t\t\tNO OF TIME INTERVALS : ";
cin>>tim_intrval;
for(counter = 1; counter <= tim_intrval; counter++)
{
cout<<"\n\t\t\tAT T TIME(sec) : "<<counter;

cin>>time;
cout<<"\t\t\tVELOCITY AT sec (m/sec) : "<<time;
cin>>velos;
cout<<"\t\t\tACCLERATION AT sec (m/sec^2): "<<time;
cin>>accl;
distance += (velos*time + (accl*pow(time,2))/2);
}
cout<<"\n\n\n\tTOTAL DISTANCE TRAVELLED BY VEHICLE IN INTERVALS OF TIME :
"<<tim_intrval<<distance;
}

/*Write a C++ program to read in two numbers, x and n, and then compute the sum of this
geometric progression:1+x+x2+x3+………….+xn For example: if n is 3 and x is 5, then the
program computes 1+5+25+125.Print x, n, the sum Perform error checking. For example, the
formula does not make sense for negative exponents - if n is less than 0. Have your program print
an error message if n<0, then go back and read in the next pair of numbers of without computing
the sum.Are any values of x also illegal ? If so, test for them too. */
#include<iostream.h>
#include<math.h>
void main()
{

int s_sum,i,x,n;
cout<<"Enter the values for x and n:";
cin>>x>>n;
if(n<=0 || x<=0)
{
cout<<"Value is not valid\n";

}
else
{
cout<<"Value is valid\n";
s_sum=1;
for(i=1;i<=n;i++)

{
s_sum=s_sum+pow(x,i);
}
cout<<"Sum of series=\n"<<s_sum;
}
}

WHILE LOOP
A while loop statement in C programming language repeatedly executes a target statement as long as a
given condition is true.

Syntax:

The syntax of a while loop in C programming language is:

while(condition)

statement(s);

Here, statement(s) may be a single statement or a block of statements. The condition may be any
expression, and true is any nonzero value. The loop iterates while the condition is true.

When the condition becomes false, program control passes to the line immediately following the loop

FLOW CHART

Here, key point of the while loop is that the loop might not ever run. When the condition is tested and the result
is false, the loop body will be skipped and the first statement after the while loop will be executed

/* Write a C++ program to find the sum of individual digits of a positive integer.*/

#include<iostream.h>

#include<conio.h>

void main()

{
int num, k=1, sum=0;

cout<<"Enter the number whose digits are to be added:";

cin>>num;

while(num!=0)

k=num%10;

sum=sum+k;

k=num/10;

num=k;

cout<<"Sum of the digits:",sum;

getch();

PROGRAM TO DIPLAY 10 NUMBERS

#include <iostream.h>
void main ()
{
int a = 0;

while( a <=10 )
{
cout<<"value of a:\n"<< a;
a++;
}
}

DO WHILE:
Unlike for and while loops, which test the loop condition at the top of the loop, the do...while loop in
C++ programming language checks its condition at the bottom of the loop.

A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at least
one time.
Syntax:

The syntax of a do...while loop in C programming language is:

do

statement(s);

}while( condition );

Notice that the conditional expression appears at the end of the loop, so the statement(s) in the loop
execute once before the condition is tested.

If the condition is true, the flow of control jumps back up to do, and the statement(s) in the loop execute
again. This process repeats until the given condition becomes false.

PROGRAM TO DISPLAY 10 NUMBERS

#include <iostream.h>

int main ()

int a = 0;

do

cout<<"value of a: \n"<< a;

a = a + 1;
}

while( a < 9 );

C++ Programming break and continue Statement


There are two statements built in C, break; and continue; to interrupt the normal flow of control of a
program. Loops perform a set of operation repeatedly until certain condition becomes false but, it is
sometimes desirable to skip some statements inside loop and terminate the loop immediately without
checking the test expression. In such cases, break and continue statements are used.

break Statement

In C++ programming, break is used in terminating the loop immediately after it is encountered. The
break statement is used with conditional if statement.

Syntax of break statement

break;

continue Statement

It is sometimes desirable to skip some statements inside the loop. In such cases, continue statements are
used.

Syntax of continue Statement

continue;

goto Statement

In C++ programming, goto statement is used for altering the normal sequence of program execution by
transferring control to some other part of the program.

Syntax of goto statement

goto label; ............. ............. label: statement;

In this syntax, label is an identifier. When, the control of program reaches to goto statement, the control
of the program will jump to the label: and executes the code/s after it.

Functions
A function is as self contained block of statements that perform a task .Every C++ program can
be thought of as a collection of these functions. In C++ every program must have a main function to
indicate where the program has to begin its executions.

The program may become too large and complex and as result the task of debugging, testing and
maintaining becomes defficult.If a program is divided into functional part may be independently coded
and later combined into a single unit. These independently coded programs are called subprograms that
are much easier to understand, debug and test. In C, such subprograms are referred to as functions.

Concepts of functions
1. Function Declaration or Function Proto Type.

2. Function Definition.

3. Function Body

4. Function Arguments.

5. Function Call.

6. Function Return Type.

Function Declaration

A function declaration can appear outside of all functions

A function declaration can also appear inside function main.

All functions know about other declarations and can call these functions

A function declaration provides the following information to the compiler

The name of the function.

The type of the value returned (Optional, Default integer)

The number and the type of arguments that must be supplied in a call to the function.

When a function call is encountered, the compiler checks the function call its declaration. So that correct
argument types are used.

Syntax:

ret_type function_name (type, type,…);

ret_type specifies the data type of the value in the return statement.

A Function can return any data type; if there is no return value, the keyword void is placed before the
function name.

The function declaration terminates with a semicolon.


Function Definition:

The function definition is similar to the function declaration but does not have the semicolon.

The first line of the function is called a function declarator.This is followed by the function body. It is
composed of the statements that make up the function, delimited by braces.

The declarator and declaration must use the same function name, number of arguments, argument types,
and the return type.

No function definition allowed within a function definition

If the functions are defined before they are called, then the declarations are unnecessary.

Function Call:

A function is a dormant entity, which comes to life when a call is made to the function. A function call
is specified by the function name followed by the values of the parameters enclosed within parentheses,
terminated by a semicolon.

When the compiler encounters a function call, the control is transferred to the function. Then the
function executed line by line.

Function Return Type:

Function in C++ may or may not have return values

If a function does not return a value, the return type in the function definition and declaration is
specified as void. Otherwise, the return type is specified as a valid data type.There may be multiple
return statements.

Function parameters

Function parameters are the means of communication between the calling and the called functions. They
can be classified into Actual parameters and Formal Parameters.

The formal Parameters are parameters given in the function declaration and function definition.

The actual parameters, often known as arguments, are specified in the function call.

Formal parameters are known as dummy parameters or placeholders.

//Program to display message using functions.

#include<iostream.h>
void main()
{
void message();
cout<<"welcome to main function \n";
message();
}
void message()
{
cout<<"welcome to user defined functions";
}
//Program using alert using function.

#include<iostream.h>
void main()
{
void beep();

beep();
}
void beep()
{
cout<<"\a";
}

//Program to find biggest of three numbers using functions.

#include<iostream.h>
void main()
{
float maximum(float a,float b,float c);
float x,y,z,max;
cout<<"enter x,y,z values \n";
cin>>x>>y>>z;
max=maximum(x,y,z);
cout<<“Max==\n"<<max;
}
float maximum(float a,float b,float c)
{
if(a>b)
If(a>c)
return(a);
else
return(c);
else
{
if(b>c)
return(b);
else
return(c);
}
}

//Program to display cube value using functions.

#include<iostream.h>
void main()
{
Int cube(int);
int n;
cout<<"Result== \n",cube(10);
cout<<"Enter n value \n";
cin>>n;
cout<<"Result== \n"<<cube(n);
}
int cube(int i)
{
int r;
r=i*i*i;
return r;
}

//Program to find factorial of a numbers

#include<iostream.h>
void main()
{
long int fact(long int);
long int n,x;
cout<<"Enter n value \n";
cin>>n;
x=fact(n);
cout<<"fact==\n"<<x;
}
long int fact(long int n)
{
long int v=1,i;
if(n==1)
return(v);
else
{
for(i=1;i<=n;i++)
v=v*i;
return(v);
}
}

OUTPUT:
n=5
fact=120.

n=2
v=1*1==>1
v=1*2==>2

n=3
v=1*1==>1
v=1*2==>2
v=2*3==>6

n=4

v=1*1==>1
v=1*2==>2
v=2*3==>6
v=6*4==>24

n=5

v=1*1==>1
v=1*2==>2
v=2*3==>6
v=6*4==>24
v=24*5==>120

//Program to find sum of numbers using functions

#include<iostream.h>
void main()
{
int sum(int,int,int);
int x,y,z,total;
cout<<"Enter x,y,x \n";
cin>>x>>y>>z;
total=sum(x,y,z);
cout<<"sum==” \n"<<total;
}
int sum(int a,int b,int c)
{
int t;
t=a+b+c;
return(t);
}
//Program to find biggest of three numbers using functions.

#include<iostream.h>
void main()
{
void square(int);
int max,i;
cout<<"Enter a value \n";
cin>>max;
for(i=0;i<=max-1;i++)
square(i);
}
void square(int n)
{
float value;
value=n*n;
cout<<"i==”<<n<<”sq==”<<value;
}

OUTPUT:

i=0 sq=0
i=1 sq=1
i=2 sq=4
i=3 sq=9

Actual parameters and formal parameters

There are two categories of “parameters".

Actual parameters are parameters as they appear in function calls.

Formal parameters are parameters as they appear in function declarations.

Formal parameters are known as dummy parameters or placeholders.

A parameter cannot be both a formal and an actual parameter, but both formal parameters and actual parameters
can be either value parameters or variable parameters

C++ provides two mechanisms to pass arguments to a function.


1. Pass by value

2. Pass by address or by pointers.

1. Pass by Value:

Functions in C++ pass all arguments by value. Passing arguments by value means that the contents of
the arguments in the calling function are not changed, even if they are changed in the called function.
This is because the content of the variable is copied to the formal parameters of the function definition,
thus preserving the contents of the arguments in the calling function.

PROGRAM USING CALL BY VALUE

#include<iostream.h>

void main()

{ void swap(int x,int y);

int a,b;

cout<<“enter a,b values \n”;

cin>>a>>b;

swap(a,b);

cout<<a<<b;

void swap(int x,int y)

{ int t;

t=a;

a =b;

b=t;

2. Pass by address:

In Call by reference, a function receives implicit references to the argument rather than a copy of its
value. Therefore, the function can modify the value of the variable and that change will be reflected in
the calling function as well.

To indicate that an argument is passed using call by reference, an ampersand sign (&) is placed after the
type in the parameter list.

Advantages
1. Arguments are not copied into new variables, so it provides good time and space efficiency.

2. The function change the value of the argument and change is reflected in the caller.

3. A function can return only one value. In this case we can return multiple values, so pass arguments by
reference .Those modified values are visible in the calling function.

PROGRAM USING CALL BY ADDRESS

#include<iostream.h>

#include<conio.h>

void main()

{ void swap(int *x,int *y);

int a,b;

cout<<“enter a,b values \n”;

cin>>a>>b;

swap(&a,&b);

cout<<a<<b;

void swap(int *x,int * y)

Int t;

t=*a;

*a =*b;

*b=t;

PROGRAM TO FIND FACTORIAL OF A NUMBER USING NON RECURSION

#include<iostream.h>

void main()

long int fact(long int);

int n,x;
cout<<“enter n value”;

cin>>n;

x=fact(n);

cout<<factorial=”<<x;

long int fact(long int n)

int v=1;

if(n==1)

return v;

else

for(i=1;i<=n;i++)

v=v*I;

return v;

Recursion
A recursive function is defined as a function that calls itself to solve a task until a last call is made which
does not require a call to itself.

#include<iostream.h>

void main()

long fact(long num);

long n,x;

cout<<“enter integer”;

cin>>n;

x=fact(n);
cout<<“n==<<n<<” factorial ==<<x;

long fact(long num)

long int fact(long int);

int value=1;

if(num==1)

return (value);

else

value=num*fact(num-1);

return (value);

/* Write C++ programs that use both recursive and non-recursive functions

To find the GCD (greatest common divisor) of two given integers.*/

#include<iostream.h>

#include<math.h>

unsigned int GcdRecursive(unsigned m, unsigned n);

unsigned int GcdNonRecursive(unsigned p,unsigned q);

int main(void)

int a,b,iGcd;

clrscr();

cout<<"Enter the two numbers whose GCD is to be found: ";

cin>>a>>b;

cout<<"GCD Using Recursive Function is<<a<<b<<GcdRecursive(a,b);

cout<<"GCD of Using Non-Recursive Function is \n"<<a<<b<<GcdNonRecursive(a,b);


}

/* Recursive Function*/

unsigned int GcdRecursive(unsigned m, unsigned n)

if(n>m)

return GcdRecursive(n,m);

if(n==0)

return m;

else

return GcdRecursive(n,m%n);

/* Non-Recursive Function*/

unsigned int GcdNonRecursive(unsigned p,unsigned q)

unsigned remainder;

remainder = p-(p/q*q);

if(remainder==0)

return q;

else

GcdRecursive(q,remainder);

//PROGRAM TO FIND SUM OF NUMBERS USING RECURSION.

#include<iostream.h>
#include<conio.h>
void main()
{
int sum(int);
int x,n;
cout<<“enter n value\n”;
cin>>n;
cout<<“sum==”<<sum(n);
}
int sum(int n)
{
int sum(int n);
int v;
v=0;
If(n==0)
return (v);
else
{
v=n+sum(n-1);
return(v);
}
OUTPUT”
Enter value
10
Sum==55
//PROGRAM TO FIND SUM OF NUMBERS

#include<iostream.h>
void main()
{
int sum(int);
int x,n;
cout<<“enter n value\n”;
cin>>>n;
cout<<“sum==”<<sum(n);
}
int sum(int n)
{
int v;
v=0;
if(n==0)
return (v);
else
{
for(i=0i<=n;i++)
v=v+I;
return(v);
}
}
OUTPUT”
Enter value
10
Sum==55
Scope and Extent:

Scope: The region of source code which the declaration of an identifier is visible is called the scope of
the identifier.

Extent: The period of time during which memory is associated with a variable is called the extent of
variable.

Scope categorized into two types.


1. Block scope.

2. File scope.

1. Block Scope: A block is defined as a sequence of statements enclosed between curly braces{ and }.In
other words a block is a compound statement.

2. File scope:
Variables declared outside all functions are said to have global scope. Global variables can be classified under
two categories:

1. Static or File static variables, whose scope is limited to the file in which it is declared,.

2. Global variables, which accessed across files which are linked together.

Storage Classes:
The life time of a variable is characterized by its storage class. The storage class of a variable indicates the
allocation of storage space to the variable.

Local variables:
Local variables scope is confined within the block or function where it is defined. Local variables must always be defined
at the top of a block.
When a local variable is defined - it is not initialized by the system, programmer must initialize it .
When execution of the block starts the variable is available, and when the block ends the variable 'dies'.(OR) Variable
whose existence is known only to the main program or functions are called local variables. Local variables are
declared within the main program or a function.
Global variables:

Global variable is defined at the top of the program file and it can be visible and modified by any function that
may reference it.

Global variables are initialized automatically by the system when you define them!
Data Type Initialser
int 0
char '\0'
float 0
pointer NULL

Variables whose existence is known to the both main() as well as other functions are called global variables.
Global variables are declared outside the main() and other functions.

PROGRAM USING LOCAL AND GLOBAL VARIABLES

#include<iostream.h>
int a = 10; /* global declaration */
int main()
{
int b; /* Local variable */
cout<<a;
b = value(a)
cout<<b;
}
int value(int x)
{
int c; /* Local variable */
c = x + 10;
return(c);
}
The storage classes define the extent of a variable. Storage classes are of four types.
1. auto.
2. register.

3. static.
4. extern.

1. auto variable:
All variables within a function are auto by default. The extent of a variable is defined by its scope.
Variables declared auto can only be accessed only within the function or the nested block within which
they are declared.

They are created when the block is entered into and destroyed when it is exited.

Program using auto variable:


#include<iostream.h>
void main()
{
int c=12;
cout<<c;
{
int c=13;
cout<<c;
}
cout<<c;
}
PROGRAM USING AUTO VARIBLE.

#include<iostream.h>
void autostorage();
void main()
{
int I;
for(i=1;i<=3;i++)
autostorage();
}
void autostorage()
{
auto int x=0;
x=x+1;
cout<<“x==\n”<<x;
}
OUTPUT:
X=1
X=1
X=1
//PROGRAM USING AUTO VARIABLE.

#include<iostream.h>
void main()
{
int fun(int x);
int i,x;
for(i=1;i<=10;i++)
{
value=fun(i);
cout<<i<<value;
}
}
int fun(int x)
{
int sum=100;
sum=sum+x;
return(sum);
}
OUTPUT:
1 101
2 102
3 103
4 104
5 105
6 106
7 107
8 108
9 109
10 110

//PROGRAM USING SfTATIC VARIABLE.

#include<iostream.h>
void main()
{
int fun(int x);
int i,x;
for(i=1;i<=10;i++)
{
value=fun(i);
cout<<i<<value;
}
}
int fun(int x)
{
static Int sum=100;
sum=sum+x;
return(sum);
}

OUTPUT:

1 101
2 103
3 106
4 110
5 115
6 121
7 128
8 136
9 145
10 155

2. Register variables:
C++ allows the use of the prefix register in primitive variable declarations. Such variables are
called register variables, and are stored in the registers of the microprocessor. The numbers of variables
which can be declared register are limited.

If more variables are declared register variables, they are treated as auto variables.

A program that uses register variables executes faster as compared to a similar program without register
variables.

It is responsibility of the compiler to allot register variables .In case the compiler is unable to do so;
these variables are treated as auto variables.

//PROGRAM USING REGISTER VARIABLE.

#include<iostream.h>
void main()
{
register int;
for(i=0;i<=2;i++)
{
cout<<“i==\n”<<i;
}
}
3. Static variables:
Static variables are two types

1. Static variables that are declared within function (function static variables) .These variables retain their
values from the previous call i.e., the values which they had before returning from the function.

2. File static variables. These variables are declared outside any function using the keyword static .File
static variables are accessible only in the file which they are declared.

PROGRAM USING STATIC VARIBLE.

#include<iostream.h>
#include<conio.h>
void staticstorage();
void main()
{
int I;
for(i=1;i<=3;i++)
staticstorage();
}
Void static storage()
{
static int x=0;
x=x+1;
cout<<“x==\n”<<x;
}
OUTPUT:
X=1
X=2
X=3
4. Extern variables:
Global static variables are global to the file in which they are defined. They are used when the same
global variable is referenced in each of the files and these variables must be independent of each other across
files.

The use of global variables is not recommended, as function independence is one of the basic ideas of
modular programming.

When a program spans across different files and we want to have a global variable accessible to all
functions in these files, the keyword extern should be used before the data type name in the declarations in all
the files where it is accessed.

PROGRAM USING EXTERN VARIABLE.

#include<iostream.h>
extern int x=10;
void main()
{
int y=20,z;
z=x+y;
cout<<“z==”<<z;
}
//PROGRAM USING GLOBAL VARIABLE.

#include<iostream.h>
int x;
int y=10;
void main()
{
x=10;
void sum();
Sum();
}
void sum()
{
int sum;
sum=x+y;
cout<<“x==”<<x;
cout<<“y=”<<y;
cout<<“sum==”<<sum;
}
Arrays:
An array is a sequence of data in memory, wherein all data are of the same type, and are placed
in physically adjacent locations.
In C++ .arrays are two types: one dimensional and multidimensional.
The C++ language treats strings as an array of characters, the last of which is the null
character(character with an ASCII value zero).
An array is fundamental data structure that enables the storing and manipulation of potentially huge
quantities of data.
An array stores ordered sequence of homogeneous values.
Homogeneous means that all the values are of the same type.

Single Dimensional Array:

In The single dimensional array, there will be a single subscript or index whose value refers to the
individual array element which ranges from 0 to (n-1), where n is the total number of elements in the
array.

Declaration:

We must declare the array. It is done at the beginning of the function main () with statement.

Syntax

Data type name_of_the array Size _of array;

Example:

int a[15];//an array with 15 int elements.

char c[25];//an array with 25 char elements

Each individual array element is called an indexed variable or a subscripted variable, since both a variable name
and an index or a subscript value must be used to reference the element.

The index or subscript value gives the position of the element in the array

An array size must be a positive integer number or an expression that evaluates to a positive integer number.

Initializing Integer Arrays:


Arrays can be initialized during declaration.

Example:

int a[5]={1,5,8,9,0};

Automatic Sizing:
While initializing, the size of a one dimensional array can be omitted.

Example: int x [] = {0,8,7,6,4};


Accessing Array Elements:
Single operations, which involve entire arrays are not permitted in C.Arrays must be carried out an
element by element basis. This is usually accomplished within a loop or within nested loops for
multidimensional arrays.

For initializing an individual array element, a particular array index has to be used.

Example:

a [0]=7;

a [5]=8;

Strings[One Dimensional Character Array]:

Strings in C++ are represented by arrays of characters. The end of string is marked with a special
character, the null character, which is a character all of whose bits are zero.

The NULL character or string terminator character is represented by another character escape sequence
\0.

Example:

char name [25];

Strings can be initialized.

Example:

char name [25]=“ramakrishna”;

Multidimensional Arrays:

Arrays with more than one dimension are called multidimensional arrays.

Two dimensional Arrays:

Syntax:

datatype array_name [size1][size2];

Here size1,size2 indicates dimensions.

int a[9][9]; Here we can store 81 elements.

Three dimensional Array:

Syntax:

data type array_name[size1][size2][size3];

Example:
int a[2][6][8];

Initializing Multidimensional array:

int a[3][2]={ 1,1, 2,2, 3,3};

Passing arrays to functions

Like values, it is also possible to pass values of an array to function. To pass a one dimensional
an array to a called function, it is sufficient to list the of the array, without any subscripts, and size of the
array as arguments.

Example:

int simple(int array1[],int size);

Here array1 indicates name of the array.


Size indicates size of the array.
In C++, the name of the array represents the address of its first element .By passing the array name, we
are in fact, and passing the address of the array to the called function .The array in the called function
now refers to the same array stored in the memory. Therefore, any changes in the array in the called
function will be reflected in the original array.
Passing strings to functions

The strings are as characters arrays in C++ and therefore the rules for passing strings to functions are
very similar to those for passing arrays to functions.

Example:

void output (char str[]);

output(name);

//PROGRAM USING ARRAY INITIALIZATION.

#include<iostream.h>
#include<conio.h>
Void main()
{
int a[7]={1,2,3,4,5,6,7};
int I;
cout<<“CONTENTS OF THE ARRAY \n”;
for(i=0;i<=6;i++)
cout<<“\t”<<a[i];
}
//PROGRAM TO READ THE NUMBERS USING ARRAYS.

#include<iostream.h>
#include<conio.h>
void main()
{
int a[50],I,n;
cout<<“HOW MANY NUMBERS ARE IN THE ARRAY \n”;
cin>>n;
cout<<“ENETR ELEMENTS \n”;
for(i=0;i<=n-1;i++)
{
cin>>a[i];
}
cout<<“CONTENTS OF THE ARRAYS \n”;
for(i=0;i<=n-1;i++)
cout<<“\t”<<a[i];
}
//PROGRAM TO FIND LARGEST AND SMALL ELEMENT IN THE ARRAY.

#include<iostream>
Using namespace std;
void main()
{
int i,n;
int a[25],large,small;
cout<<“ENTER SIZE OF THE ARRAY \n”;
cin>>n;
cout<<“\n Enter ARRAY ELEMENTS \n”;
for(i=0;i<n;i++)
cin>>a[i];
large=a[0];
small=a[0];
for(i=1;i<n;i++)
{
if(a[i]>large)
large=a[i];
else
if(a[i]<small)
small=a[i];
}
cout<<“\n LARGE==”<<large;
cout<<“\n SMALL==”<<small;
}

OUTPUT:

ENTER SIZE OF THE ARRAY

24 6 14 11 8
LARGE==24

SMALL==6

//PROGRAM TO SORT ELEMENTS IN THE ASCENDING ORDER.

#include<iostream>
using namespace std;
void main()
{
int i,j,k,n;
int a[100],temp;
cout<<“\n ENTER SIZE OF THE ARRAY”;
cin>>n;
cout<<“\n Enter ARRAY ELEMENTS \n;
for(i=0;i<n;i++)
cin>>a[i];
for(i=0;i<n-1;i++)
for(j=i+1;j<n;j++)
{
If(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
cout<<“\n ELEMENTS IN ASCENDING ORDER \n;
for(i=0;i<n;i++)
cout<<a[i);
}
OUTPUT:
ENTER SIZE OF ARRAY.
8
ARRAY ELEMENTS ARE
91 21 10 7 24 11 2 8
2 7 8 10 11 21 24 91

//PROGRAM TO ADD MATRICES.


#include<iostream.h>
void main()
{
int a[10][10],b[10][10],c[10][10];
int i,j,m,n,p,q;
cout<<“ENTER ROW AND COLUMN OF A MATRIX \n”;
cin>>n>>m;
cout<<“ENETR ROW AND COLUMN OF B MATRIX \n”;
cin>>p>>q;
if((n==p)&&(m==q))
{
cout<<“MATRIX CAN BE ADDED \n”;
cout<<“enter a matrix \n”;
for(i=0;i<n;i++)
for(j=0;j<m;j++)
cin>>a[i][j];
cout<<“ENTER B MATRIX \n”;
for(i=0;i<n;i++)
for(j=0;j<m;j++)
cin>>b[i][j]);
cout<<“SUM OF A AND B MATRICES \n”;
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
c[i][j]=a[i][j]+b[i][j];
}
cout<<"\nThe Addition of two matrix is\n";
for(i=0;i<n;i++)
{
cout<<"\n";
for(j=0;j<m;j++)
cout<<"\t"<<c[i][j];
}
}
else
cout<<“MATRICES CAN NOT BE ADDED \N”;
}

//PROGRAM TO FIND TRACE MATRIX.

#include<iostream.h>
void main()
{
int a[10][10],I,j,n,trace;
cout<<“ENTER THE ORDER OF A MATRIX\n”;
cin>>n;
cout<<“ENTER A MATRIX \n”;
for(i=0;i<n;i++)
for(j=0;j<n;j++)
cin>>a[i][j];
trace=0;
for(i=0;i<n;i++)
trace=trace+a[i][i];
cout<<“trace= \n”<<trace;
}

OUTPUT:ENTER THE ORDER OF MATRIX


3
1 2 3
4 5 6
7 8 9
TRACE=15

//PROGRAM TO FIND MULTIPLICATION OF MATRIX.

#include<iostream.h>
#include<conio.h>
int main()
{
int a[10][10],b[10][10],c[10][10];
int m,n, i, j, k, l,g;
cout<<"Enter the number of rows and column of first matrix\n";
cin>>m>>n;

cout<<"\nEnter the elements of first matrix\n";


for (i=0; i< m; i++)
{
for(j=0; j<n; j++)
{
cin>>a[i][j];
}
}
s1 : cout<<"\nEnter the number of rows and column of second matrix\n");
cin>>g>>l;
if(n!=g)
{
cout<<"\nIn matrix multiplication first column and second row
number should be the same \n");
goto s1;
}

cout<<"\nEnter the elements of second matrix";


for(i = 0; i <n; i++)
{
for (j = 0; j < l; j++)
{
cin>>b[i][j];
}
}
cout<<"\nThe first matrix is :-\n";
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
cout<<"\t"<< a[i][j];
}
cout<<"\n";
}
cout<<"\nThe second matrix is :-\n";
for (i = 0; i < n; i++)
{
for (j = 0; j < l; j++)
{
cout<<"\t"<< b[i][j];
}
cout<<"\n";
}
cout<<"\nMultiplication of the two matrices=\n";
for (i = 0;i < m; i++)
{
cout<<"\n");
for (j = 0; j < l; j++)
{
c[i][j]=0;
for(k=0;k<n;k++)

c[i][j] = c[i][j]+a[i][k] * b[k][j];


cout<<”\t”<< c[i][j];
}
}
getch();
}
//PROGRAM TO FIND TRANSPOSE OF MATRIX

#include<iostream.h>
#include<conio.h>
void main()
{
int a[10][10],b[10][10];
int I,j,m,n;
cout<<“ENTER ROW & COL OF A MATRIX\n”;
cin>n>>m;
cout<<“ENTER A MATRIX \n”;
for(i=0;i<n;i++)
for(j=0;j<m;j++)
cin>>a[i][j];
for(i=0;i<m;i++)
for(j=0;j<n;j++)
b[i][j]=a[j][i];
cout<<“\n TRANSPOSE OF A MTRIX\n”;
for(i=0;i<m;i++)
for(j=0;j<n;j++)
cout<<b[i][j];
cout<<“\n”;
}
OUTPUT:
ENTER ROW & COL OF A MATRIX: 3X4
ENTER A MATRIX
1 2 3 4
5 6 7 8
9 10 11 12
TRANSPOSE OF A MATRIX:
1 5 9
2 6 10
3 7 11
4 8 12

STRINGS
In C++, String is an array of characters. Every string is terminated by a null character. Null character is
indicated by ‘\0’.
Example:

char s [5] =”hello”;


Here, Null character will not be appended automatically to the character array. String s can hold only 5
characters.

Example:
char s[] =”hello”;
Here ,character array s have characters namely h,e,l,l,o. Apart from these characters a null characters(‘\0’) is
stored at the end of the string. So, the internal representation of the string becomes hello’\0’.
To use string functions, the header file string.h must be included in the program with the statement.

STRING MANIPULATION FUNCTIONS.

1. strlen() Function:
strlen() function computes the length of the string.

Syntax: size_t strlen(const char *str);

PROGRAM:
void main()
{
char str[]=”welcome”;
cout<<“\n Length==”<<strlen(str);
}
This function computes the length without including the null character.
2. strcpy() function:

Syntax: char *strcpy (char *str1, const char *str2);


strcpy () function copies the contents of string to string 1.

Program:
void main()
{
char str1[15],str2[15];
str2[15]=”welcome”;
strcpy(str1,str2);
cout<<“\nstring1==”<<str1;
}
3. Strcat () function:

Syntax: strcat (string1, string2);

The strcat () function joins or concatenates two strings together.

PROGRAM:
void main ()
{
char str1[15]=”welcome”;
char str2[]=”to c”;
strcat(str1,str2);
cout<<“\n str1==”<<str1;
}

4.strcmp() function:

Syntax: strcmp (str1, str2);


strcmp () function compares strings identified by the arguments. The function returns zero if the strings
are equal .Otherwise, it returns a value less than zero or greater than zero if str1 is less than or greater than str2
respectively.

PROGRAM:
void main()
{
char str1[10]=”welcome”;
char str2[10]=”you”;
If(strcmp(str1,str2)==0)
cout<<“\n strings are equal”;
else
cout<<“\n not equal”;
}

2.Strchr() Function:
strchr() function searches for the first occurrences of the character in the string pointed to by the argument str.

Syntax: char *strchr (const char *str, int c);

3.strrchr() function:

strrchr() function searches for the first occurrences of the character beginning at the rear end and working
towards the front in string pointed to by the argument str.

Syntax: char *strrchr(const char *str, int c);

4.strstr() function:

Syntax: char *strstr(const char *str1,const char *str2);

strstr() function is used to find the first occurrences of string str2 (terminating character not included) in the
str1.It returns a pointer to the first occurrences of str2 in str1.If match not found ,then null pointer is returned.

5.strspn() function:

strspn() function returns the index of the first character in str1 that doesn’t match any character in str2.

Syntax: size_t strspn(char the const char *str1,const char *str2);

6.strcspn() function:

Syntax: size_t strcspn(const char *str1,const char *str2);

strcspn() function returns the index of the first character in str1,that matches any of the characters in str2.
7. Strpbrk () function:

Syntax: char *strpbrk (const char *str1, const char * str2);

strpbrk () function returns a pointer to the first occurrence in str1 of any character in str2 or null if none are
present.

8. strtok () function:

Syntax: char *strtok (char *str1, const char *delimiter);

strtok () function is used to isolate sequential tokens in a null terminating string str.These tokens are separated
in the string using delimiters.

12. Strncpy () function:

Syntax: char *strncpy (char *str1, const char *str2);

strncpy () function copies only left most n characters of the source string to the target string variable.

PROGRAM:

void main()
{
char str1[5]=”abc”;
char str2[5]=”def”;
strncat(str1,str2,2);
cout<<“\n str1==”<<str1;
}
13. Strncmp () function:

Syntax: strncmp () (const char *str1, const char *str2), size_t n);

This function compares at most the first n characters of str1 and str2 .Otherwise, it returns a value less than zero
or greater than zero if str1 is less than or greater than str2, respectively.

PROGRAM:
void main ()
{
char str1 [10] =’abc”;
char str2 [10]=”abd”;
if (strncmp (str1,str2,2)==0)
cout<<“\n str and str2 equal”;
else
cout<<”\n both are not equal”;
}
14.strncat() function:

Syntax: strncat(str1,str2,2);

Adds the string pointed to by str2 to the end of the string pointed to by str1 upto n characters.

PROGRAM:

void main()
{
char str1[10]=”hello”;
char str2[10]=”how r u”;
strncat(str1,str2,2);
cout<<“\n str1==”<<str1;
}
15.atoi() function:

Syntax: int atoi(const char *s);

This function converts a string to an equivalent integer value.

16. atol() function:

Syntax: long atol(const char *s);

It converts a string to an equivalent long value.

17. atof () function:


Syntax: float atof (const char *s);
It converts a string to an equivalent floating value.

/* Write a C++ program that uses functions to perform the following operations:
To insert a sub-string in to given main string from a given position.*/
#include <iostream.h>
#include <conio.h>
#include <string.h>
void main()
{
char a[10];
char b[10];
char c[10];
int p=0,r=0,i=0;
int t=0;
int x,g,s,n,o;
puts("Enter First String:");
gets(a);
puts("Enter Second String:");
gets(b);
cout<<"Enter the position where the item has to be inserted: ";
cin>>p;
r = strlen(a);
n = strlen(b);
i=0;
// Copying the input string into another array
while(i <= r)
{
c[i]=a[i];
i++;
}
s = n+r;
o = p+n;

// Adding the sub-string


for(i=p;i<s;i++)
{
x = c[i];
if(t<n)
{
a[i] = b[t];
t=t+1;
}
a[o]=x;
o=o+1;
}
/* Write a C++ program to determine if the given string is a palindrome or not */

#include<iostream.h>
#include<string.h>
enum Boolean{false,true};
enum Boolean IsPalindrome(char string[])
{
int left,right,len=strlen(string);
enum Boolean matched=true;
if(len==0)
return 0;
left=0;
right=len-1;
/* Compare the first and last letter,second & second last & so on */
while(left<right&&matched)
{
if(string[left]!=string[right])
matched=false;
else
{
left++;
right--;
}
}
return matched;
}
int main()
{
char string[40];
cout<<"****Program to test if the given string is a palindrome****\n";
cout<<"Enter a string:";
cin>>string;
if(IsPalindrome(string))
cout<<"The given string %s is a palindrome\n"<<string;
else
cout<<"The given string %s is not a palindrome\n"<<string;
getch();
return 0;
}
/* Write a C++ program that uses functions to perform the following operations:
To delete n Characters from a given position in a given string.*/

#include <iostream.h>
#include <string.h>
void delchar(char *x,int a, int b);
void main()
{
char string[10];
int n,pos,p;
puts("Enter the string");
gets(string);
cout<<"Enter the position from where to delete";
cin>>"%d",&pos);
cout<<"Enter the number of characters to be deleted";
cin>>"%d",&n;
delchar(string, n,pos);
getch();
}
// Function to delete n characters
void delchar(char *x,int a, int b)
{
if ((a+b-1) <= strlen(x))
{
strcpy(&x[b-1],&x[a+b-1]);
puts(x);
}
}

/* Write a C++ program to count the lines, words and characters in a given text*/

#include <iostream.h>
void main()
{
char line[81], ctr;
int i,c,
end = 0,
characters = 0,
words = 0,
lines = 0;
cout<<"KEY IN THE TEXT.\n";
cout<<"GIVE ONE SPACE AFTER EACH WORD.\n";
cout<<"WHEN COMPLETED, PRESS 'RETURN'.\n\n";
while( end == 0)
{
/* Reading a line of text */
c = 0;
while((ctr=getchar()) != '\n')
line[c++] = ctr;
line[c] = '\0';
/* counting the words in a line */
if(line[0] == '\0')
break ;
else
{
words++;
for(i=0; line[i] != '\0';i++)
if(line[i] == ' ' || line[i] == '\t')
words++;
}
/* counting lines and characters */
lines = lines +1;
characters = characters + strlen(line);
}
Cout<<"\n";
cout<<"Number of lines = "<< lines;
cout<<"Number of words ="<< words;
cout<<"Number of characters = "<< characters;
}
Output
KEY IN THE TEXT.
GIVE ONE SPACE AFTER EACH WORD.
WHEN COMPLETED, PRESS 'RETURN'.
Admiration is a very short-lived passion.
Admiration involves a glorious obliquity of vision.
Always we like those who admire us but we do not
like those whom we admire.
Fools admire, but men of sense approve.
Number of lines = 5
Number of words = 36
Number of characters = 205
/* Write a C++ program that displays the position or index in the string S
where the string T begins, or - 1 if S doesn't contain T. */

#include<iostream.h>
#include<string.h>
void main()
{
char s[30], t[20];
char *found;
/* Entering the main string */
puts("Enter the first string: ");
gets(s);
/* Entering the string whose position or index to be displayed */
puts("Enter the string to be searched: ");
gets(t);
/*Searching string t in string s */
found=strstr(s,t);
if(found)
cout<<"Second String is found in the First String at %d position.\n"<<found-s;
else
cout<<"-1");
}

You might also like