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

C++ Programs

The document provides an index of 20 C++ programs covering topics like swapping numbers, checking vowels, finding the largest number, Fibonacci series, reversing integers, printing patterns with asterisks, checking prime numbers, multiplying matrices, copying strings, using structures, calculating string length, building a simple calculator, finding factors of a number, calculating sums with recursion, using classes and objects, constructor parameters, and creating/writing to files.

Uploaded by

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

C++ Programs

The document provides an index of 20 C++ programs covering topics like swapping numbers, checking vowels, finding the largest number, Fibonacci series, reversing integers, printing patterns with asterisks, checking prime numbers, multiplying matrices, copying strings, using structures, calculating string length, building a simple calculator, finding factors of a number, calculating sums with recursion, using classes and objects, constructor parameters, and creating/writing to files.

Uploaded by

Om Dwivedi
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 25

INDEX

S. Program Name Page


No No.
1 Swap Numbers (Using Temporary Variable) 2
2 Check Vowel or a Consonant Manually 3
3 Find Largest Number Using if Statement 4
4 Fibonacci Series up to n number of terms 5
5 C++ Program to Reverse an Integer 6
6 Program to print half pyramid using * 7
7 Prime Numbers Between two Intervals 8
8 Multiply two matrices without using functions 10
9 Copy String Object 13
10 Store and Display Information Using Structure 14
11 Length of String Object 15
12 Simple Calculator using switch statement 16
13 Display all Factors of a Number 17
Calculate Sum of Natural numbers using Recursion
14 18
15 WAP displaying any info using Class and Object. 19
16 CLASS Programs 20
17 Constructor Parameters 21
18 constructors can also be defined outside the class 22
19 Polymorphism Example 23
20 Create and Write To a File 24

1
Program 1.
Swap Numbers (Using Temporary Variable)
#include <iostream>
using namespace std;

int main ()
{
int a = 5, b = 10, temp;

cout << "Before swapping." << endl;


cout << "a = " << a << ", b = " << b
<< endl;

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

cout << "\nAfter swapping." << endl;


cout << "a = " << a << ", b = " << b
<< endl;

return 0;
}

Output
Before swapping.
a = 5, b = 10

After swapping.
a = 10, b = 5

2
Program 2.
Check Vowel or a Consonant Manually
#include <iostream>
using namespace std;

int main()
{
char c;
int isLowercaseVowel, isUppercaseVowel;

cout << "Enter an alphabet: ";


cin >> c;

// evaluates to 1 (true) if c is a
lowercase vowel
isLowercaseVowel = (c == 'a' || c == 'e' ||
c == 'i' || c == 'o' || c == 'u');

// evaluates to 1 (true) if c is an
uppercase vowel
isUppercaseVowel = (c == 'A' || c == 'E' ||
c == 'I' || c == 'O' || c == 'U');

// evaluates to 1 (true) if either


isLowercaseVowel or isUppercaseVowel is true
if (isLowercaseVowel || isUppercaseVowel)
cout << c << " is a vowel.";
else
cout << c << " is a consonant.";

return 0;
}
Output
Enter an alphabet: u
u is a vowel.

3
Program 3.
Find Largest Number Using if Statement
#include <iostream>
using namespace std;

int main() {
float n1, n2, n3;

cout << "Enter three numbers: ";


cin >> n1 >> n2 >> n3;

if(n1 >= n2 && n1 >= n3)


cout << "Largest number: " << n1;

if(n2 >= n1 && n2 >= n3)


cout << "Largest number: " << n2;
if(n3 >= n1 && n3 >= n2)
cout << "Largest number: " << n3;
return 0;
}

Output
Enter three numbers: 2.3
8.3
-4.2
Largest number: 8.3

4
Program 4.
Fibonacci Series up to n number of terms
#include <iostream>
using namespace std;

int main() {
int n, t1 = 0, t2 = 1, nextTerm = 0;

cout << "Enter the number of terms: ";


cin >> n;

cout << "Fibonacci Series: ";

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


// Prints the first two terms.
if(i == 1) {
cout << t1 << ", ";
continue;
}
if(i == 2) {
cout << t2 << ", ";
continue;
}
nextTerm = t1 + t2;
t1 = t2;
t2 = nextTerm;
cout << nextTerm << ", ";
}
return 0;
}

Output

Enter the number of terms: 10


Fibonacci Series: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34,

5
Program 5.
C++ Program to Reverse an Integer
#include <iostream>
using namespace std;

int main() {
int n, reversedNumber = 0, remainder;

cout << "Enter an integer: ";


cin >> n;

while(n != 0) {
remainder = n%10;
reversedNumber = reversedNumber*10 +
remainder;
n /= 10;
}

cout << "Reversed Number = " <<


reversedNumber;

return 0;
}

Output

Enter an integer: 12345


Reversed number = 54321

6
Program 6.
Program to print half pyramid using *
*
* *
* * *
* * * *
* * * * *

#include <iostream>
using namespace std;

int main ()
{
int rows;

cout << "Enter number of rows: ";


cin >> rows;

for(int i = 1; i <= rows; ++i)


{
for(int j = 1; j <= i; ++j)
{
cout << "* ";
}
cout << "\n";
}
return 0;
}

7
Program 7.
Prime Numbers Between two Intervals

#include <iostream>
using namespace std;

int checkPrimeNumber(int);

int main() {
int n1, n2;
bool flag;

cout << "Enter two positive integers: ";


cin >> n1 >> n2;

if (n1 > n2) {


n2 = n1 + n2;
n1 = n2 - n1;
n2 = n2 - n1;
}

cout << "Prime numbers between " << n1 << "


and " << n2 << " are: ";

for(int i = n1+1; i < n2; ++i) {


// If i is a prime number, flag will be
equal to 1
flag = checkPrimeNumber(i);

if(flag)
cout << i << " ";
}

return 0;
}

8
int checkPrimeNumber(int n) {
bool isPrime = true;

// 0 and 1 are not prime numbers


if (n == 0 || n == 1) {
isPrime = false;
}
else {
for(int j = 2; j <= n/2; ++j) {
if (n%j == 0) {
isPrime = false;
break;
}
}
}

return isPrime;
}

Output
Enter two positive integers: 12
55
Prime numbers between 12 and 55 are: 13 17 19
23 29 31 37 41 43 47 53

9
Program 8.
Multiply two matrices without using functions
#include <iostream>
using namespace std;

int main()
{
int a[10][10], b[10][10], mult[10][10], r1, c1,
r2, c2, i, j, k;

cout << "Enter rows and columns for first matrix:


";
cin >> r1 >> c1;
cout << "Enter rows and columns for second
matrix: ";
cin >> r2 >> c2;

// If column of first matrix in not equal to row


of second matrix,
// ask the user to enter the size of matrix
again.
while (c1!=r2)
{
cout << "Error! column of first matrix not
equal to row of second.";

cout << "Enter rows and columns for first


matrix: ";
cin >> r1 >> c1;

cout << "Enter rows and columns for second


matrix: ";
cin >> r2 >> c2;
}

// Storing elements of first matrix.


cout << endl << "Enter elements of matrix 1:" <<
endl;
for(i = 0; i < r1; ++i)
for(j = 0; j < c1; ++j)
{

10
cout << "Enter element a" << i + 1 << j +
1 << " : ";
cin >> a[i][j];
}

// Storing elements of second matrix.


cout << endl << "Enter elements of matrix 2:" <<
endl;
for(i = 0; i < r2; ++i)
for(j = 0; j < c2; ++j)
{
cout << "Enter element b" << i + 1 << j +
1 << " : ";
cin >> b[i][j];
}

// Initializing elements of matrix mult to 0.


for(i = 0; i < r1; ++i)
for(j = 0; j < c2; ++j)
{
mult[i][j]=0;
}

// Multiplying matrix a and b and storing in


array mult.
for(i = 0; i < r1; ++i)
for(j = 0; j < c2; ++j)
for(k = 0; k < c1; ++k)
{
mult[i][j] += a[i][k] * b[k][j];
}

// Displaying the multiplication of two matrix.


cout << endl << "Output Matrix: " << endl;
for(i = 0; i < r1; ++i)
for(j = 0; j < c2; ++j)
{
cout << " " << mult[i][j];
if(j == c2-1)
cout << endl;
}

return 0;
}

11
Output
Enter rows and column for first matrix: 3
2
Enter rows and column for second matrix: 3
2
Error! column of first matrix not equal to row of
second.

Enter rows and column for first matrix: 2


3
Enter rows and column for second matrix: 3
2

Enter elements of matrix 1:


Enter elements a11: 3
Enter elements a12: -2
Enter elements a13: 5
Enter elements a21: 3
Enter elements a22: 0
Enter elements a23: 4

Enter elements of matrix 2:


Enter elements b11: 2
Enter elements b12: 3
Enter elements b21: -9
Enter elements b22: 0
Enter elements b31: 0
Enter elements b32: 4

Output Matrix:
24 29
6 25

12
Program 9.

Copy String Object


#include <iostream>
using namespace std;

int main()
{
string s1, s2;

cout << "Enter string s1: ";


getline (cin, s1);

s2 = s1;

cout << "s1 = "<< s1 << endl;


cout << "s2 = "<< s2;

return 0;
}

Output
Enter string s1: C++ Strings
s1 = C++ Strings
s2 = C++ Strings

13
Program 10.
Store and Display Information Using Structure
#include <iostream>
using namespace std;

struct student
{
char name[50];
int roll;
float marks;
};

int main()
{
student s;
cout << "Enter information," << endl;
cout << "Enter name: ";
cin >> s.name;
cout << "Enter roll number: ";
cin >> s.roll;
cout << "Enter marks: ";
cin >> s.marks;

cout << "\nDisplaying Information," << endl;


cout << "Name: " << s.name << endl;
cout << "Roll: " << s.roll << endl;
cout << "Marks: " << s.marks << endl;
return 0;
}

Output

Enter information,
Enter name: Bill
Enter roll number: 4
Enter marks: 55.6

Displaying Information,
Name: Bill
Roll: 4

14
Marks: 55.6
Program 11.
Length of String Object
#include <iostream>
using namespace std;

int main()
{
string str = "C++ Programming";

// you can also use str.length()


cout << "String Length = " << str.size();

return 0;
}

Output
String Length = 15

15
Program 12.
Simple Calculator using switch statement
# include <iostream>
using namespace std;

int main()
{
char op;
float num1, num2;

cout << "Enter operator either + or - or * or /: ";


cin >> op;

cout << "Enter two operands: ";


cin >> num1 >> num2;

switch(op)
{
case '+':
cout << num1+num2;
break;

case '-':
cout << num1-num2;
break;

case '*':
cout << num1*num2;
break;

case '/':
cout << num1/num2;
break;

default:
// If the operator is other than +, -, * or /,
error message is shown
cout << "Error! operator is not correct";
break;
}

return 0;
}

Output
Enter operator either + or - or * or divide: -
Enter two operands:

16
3.4
8.4
Program 13.
Display all Factors of a Number
#include <iostream>
using namespace std;

int main()
{
int n, i;

cout << "Enter a positive integer: ";


cin >> n;

cout << "Factors of " << n << " are: " << endl;
for(i = 1; i <= n; ++i)
{
if(n % i == 0)
cout << i << endl;
}

return 0;
}

Output
Enter a positive integer: 60
Factors of 60 are: 1 2 3 4 5 6 12 15 20 30 60

17
Program 14.

Calculate Sum of Natural numbers using Recursion


#include<iostream>
using namespace std;

int add(int n);

int main()
{
int n;

cout << "Enter a positive integer: ";


cin >> n;

cout << "Sum = " << add(n);

return 0;
}

int add(int n)
{
if(n != 0)
return n + add(n - 1);
return 0;
}

Output
Enter an positive integer: 10
Sum = 55

18
Program 15.
WAP displaying any info using Class and Object.
#include <iostream>
#include <string>
using namespace std;

class MyClass { // The class


public: // Access specifier
int myNum; // Attribute (int variable)
string myString; // Attribute (string variable)
};

int main() {
MyClass myObj; // Create an object of MyClass

// Access attributes and set values


myObj.myNum = 15;
myObj.myString = "Some text";

// Print values
cout << myObj.myNum << "\n";
cout << myObj.myString;
return 0;
}

OUT PUT is:


15
Some text

19
Program 16.
#include <iostream>
#include <string>
using namespace std;

class Car {
public:
string brand;
string model;
int year;
};

int main() {
Car carObj1;
carObj1.brand = "BMW";
carObj1.model = "X5";
carObj1.year = 1999;

Car carObj2;
carObj2.brand = "Ford";
carObj2.model = "Mustang";
carObj2.year = 1969;

cout << carObj1.brand << " " << carObj1.model << "
" << carObj1.year << "\n";
cout << carObj2.brand << " " << carObj2.model << "
" << carObj2.year << "\n";
return 0;
}

Output is:

BMW X5 1999
Ford Mustang 1969

20
Program 17.
Constructor Parameters
#include <iostream>
using namespace std;

class Car { // The class


public: // Access specifier
string brand; // Attribute
string model; // Attribute
int year; // Attribute
Car(string x, string y, int z) { // Constructor
with parameters
brand = x;
model = y;
year = z;
}
};

int main() {
// Create Car objects and call the constructor with
different values
Car carObj1("BMW", "X5", 1999);
Car carObj2("Ford", "Mustang", 1969);

// Print values
cout << carObj1.brand << " " << carObj1.model << "
" << carObj1.year << "\n";
cout << carObj2.brand << " " << carObj2.model << "
" << carObj2.year << "\n";
return 0;
}

OUT PUT IS:

BMW X5 1999
Ford Mustang 1969

21
Program 18.
constructors can also be defined outside the class

#include <iostream>
using namespace std;

class Car { // The class


public: // Access specifier
string brand; // Attribute
string model; // Attribute
int year; // Attribute
Car(string x, string y, int z); // Constructor
declaration
};

// Constructor definition outside the class


Car::Car(string x, string y, int z) {
brand = x;
model = y;
year = z;
}

int main() {
// Create Car objects and call the constructor with
different values
Car carObj1("BMW", "X5", 1999);
Car carObj2("Ford", "Mustang", 1969);

// Print values
cout << carObj1.brand << " " << carObj1.model << "
" << carObj1.year << "\n";
cout << carObj2.brand << " " << carObj2.model << "
" << carObj2.year << "\n";
return 0;
}

22
Output is:

BMW X5 1999
Ford Mustang 1969

Program 19.
Polymorphism Example
#include <iostream>
#include <string>
using namespace std;

// Base class
class Animal {
public:
void animalSound() {
cout << "The animal makes a sound \n" ;
}
};

// Derived class
class Pig : public Animal {
public:
void animalSound() {
cout << "The pig says: wee wee \n" ;
}
};

// Derived class
class Dog : public Animal {
public:
void animalSound() {
cout << "The dog says: bow wow \n" ;
}
};

int main() {
Animal myAnimal;
Pig myPig;
Dog myDog;

myAnimal.animalSound();
myPig.animalSound();
myDog.animalSound();
return 0;
}

Output is :

23
The animal makes a sound
The pig says: wee wee
The dog says: bow wow

Program 20.

Create and Write To a File


#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main () {
// Create a text file
ofstream MyWriteFile("filename.txt");

// Write to the file


MyWriteFile << "Files can be tricky, but it is fun
enough!";
// Close the file
MyWriteFile.close();

// Create a text string, which is used to output


the text file
string myText;

// Read from the text file


ifstream MyReadFile("filename.txt");

// Use a while loop together with the getline()


function to read the file line by line
while (getline (MyReadFile, myText)) {
// Output the text from the file
cout << myText;
}

24
// Close the file
MyReadFile.close();
}

Output is :

Files can be tricky, but it is fun enough!

25

You might also like