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

Program for practice

The document contains various C++ programs demonstrating different programming concepts such as string manipulation, loops, array operations, and functions. Key examples include calculating averages, finding prime numbers, generating Fibonacci sequences, and performing matrix operations. Each program is accompanied by explanations of the logic and structure used in the code.

Uploaded by

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

Program for practice

The document contains various C++ programs demonstrating different programming concepts such as string manipulation, loops, array operations, and functions. Key examples include calculating averages, finding prime numbers, generating Fibonacci sequences, and performing matrix operations. Each program is accompanied by explanations of the logic and structure used in the code.

Uploaded by

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

Program for practice:

write a program that inputs string from the user and print how many
digits are in the string:

#include <iostream>

using namespace std;

int main(){

string str ="hello world";

cout<< "string length="<<str.length();

return 0;}
C++ program for printing no from 1 to10:

#include <iostream>

using namespace std;

int main(){

int i;

for(i=0;i<=10;i++){

cout<<i<<"";

cout<<"/n";

return 0;}

Calculate avrg of an array


#include <iostream>

using namespace std;

int main(){

int age[5]={10,20,40,69,69};

int sum = 0;

float avg;

for(int i=0;i<5;i++){

sum+=age[i];

}cout<<sum<<endl;

int length(sizeof(age)/sizeof(age[0]));

cout<<length<<endl;

avg=sum/length;

cout<<"avg="<<avg<<endl;

return 0;

}
Calculate lowest age among different ages:

#include <iostream>

using namespace std;

int main(){

int age,lowestAge;

int ages[9]={3,6,46,78,9,6,5,4};

lowestAge =ages[0];

for(int i=0;i<9;i++)

if (lowestAge > age) {

lowestAge =ages[0];
}

cout<<"lowest age"<<lowestAge<<endl;

return 0;

Below is a C++ program that reads the temperature value and the unit (C for Celsius or F for
Fahrenheit), and then prints whether water is in a solid, liquid, or gas state at the given
temperature.

In this program:

 Water freezes at 0°C or 32°F (solid state).


 Water boils at 100°C or 212°F (gas state).
 Between these temperatures, water is in liquid state.

Here's the code

#include <iostream>
using namespace std;

int main() {
float temp;
char unit;

// Input temperature value and unit


cout << "Enter the temperature value: ";
cin >> temp;
cout << "Enter the unit (C for Celsius, F for Fahrenheit): ";
cin >> unit;

// Check the temperature range based on the unit


if (unit == 'C' || unit == 'c') {
if (temp <= 0) {
cout << "Water is solid (Ice)" << endl;
} else if (temp >= 100) {
cout << "Water is gas (Steam)" << endl;
} else {
cout << "Water is liquid" << endl;
}
} else if (unit == 'F' || unit == 'f') {
// Convert Fahrenheit to Celsius for the same checks
if (temp <= 32) {
cout << "Water is solid (Ice)" << endl;
} else if (temp >= 212) {
cout << "Water is gas (Steam)" << endl;
} else {
cout << "Water is liquid" << endl;
}
} else {
cout << "Invalid unit entered. Please use 'C' for Celsius or 'F' for
Fahrenheit." << endl;
}

return 0;
#include<iostream>

using namespace std;

int main(){

int n=5;

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

for(int j=1;j<=2*i+1;j++){

cout<<"*";

cout<<endl;
}

return 0;

Explanation of the formula:

1. i:
o This represents the current row index.
o In programming, loops often start counting from 0. So, for the first row, i = 0,
the second row i = 1, and so on.
2. 2 * i:
o This part ensures that the number of asterisks increases by 2 as you move from
one row to the next. This is because in an odd-number triangle, the difference
between the number of asterisks in consecutive rows is always 2 (e.g., 1, 3, 5,
7, ...).
3. + 1:
o Since we want the number of asterisks to start at 1 for the first row (not 0), we add
1 to the result of 2 * i.

How the formula works (Step-by-step):


Let's assume n = 5 rows:

Row (i) Formula: 2 * i + 1 Result: Number of Asterisks


0 2 * 0 + 1 1
1 2 * 1 + 1 3
2 2 * 2 + 1 5
3 2 * 3 + 1 7
4 2 * 4 + 1 9

Why this works for odd numbers:

 Odd numbers are evenly spaced, with a difference of 2 between consecutive odd
numbers.
 The general formula for the nth odd number (starting from 1) is 2 * i + 1, where i
starts from 0.

Prime numbers from a to b:

#include<iostream>

using namespace std;

int main(){

int a,b;

cin>>a>>b;

for(int num=a;num<=b;num++){

int i;

for(i=2;i<num;i++){

if(num%i ==0){

break;

}
} if(i ==num){

cout<<num<<endl;}

return 0;

}
Prime numbers using function:
#include<iostream>

using namespace std;

bool isPrime(int num){

for(int i=2;i<num;i++){

if(num%i==0){

return false;

return true;

int main(){

int a,b;

cin>>a>>b;

for(int i=a;i<=b;i++){

if (isPrime(i)){

cout<<i<<endl;

return 0;

}
Fibioncii sequence using function:
#include<iostream>

using namespace std;

void fib(int n){

int t1=0;

int t2=1;

int nextTerm;

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

cout<<t1<<endl;

nextTerm=t1+t2;

t1=t2;

t2=nextTerm;

return;

int main(){

int n;

cin>>n;

fib(n);

return 0;

Factorial using function:


#include<iostream>

using namespace std;

int fact(int n){

int factorial=1;

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

factorial*=i;

return factorial;

int main(){

int n;

cin>>n;

int ans=fact(n);

cout<<ans<<endl;

return 0;

}
Calculate nCr using function:
#include<iostream>

using namespace std;

int fact(int n){

int factorial=1;

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

factorial*=i;

return factorial;

int main(){

int n,r;

cin>>n>>r;

int ans=fact(n)/(fact(r)*fact(n-r));

cout<<ans<<endl;

return 0;
}

Pascal triangle using function:

#include<iostream>

using namespace std;

int fact(int n){

int factorial=1;

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

factorial*=i;

return factorial;

int main(){

int n;

cin>>n;

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

for(int j=0;j<=i;j++){

cout<<fact(i)/(fact(j)*fact(i-j))<<" ";}

cout<<endl;}
return 0;

Linear search arrays find keys by using function


#include<iostream>

using namespace std;

int linearSearch(int arr[],int n,int key){

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

if(arr[i]== key){

return i;

return -1;

int main(){

int n;
cin>>n;

int arr [n];

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

cin>>arr[i];

int key;

cin>>key;

cout<<linearSearch(arr,n,key);

return 0;

Binary search arrays find keys by using function


#include<iostream>

using namespace std;

int binarySearch(int arr[],int n,int key){


int s=0;

int e=n;

while(s<=e){

int mid= (s+e)/2;

if(arr[mid]=key){

return mid;

else if(arr[mid]> key ){

e=mid-1;

else e=mid+1;

return -1;

int main(){

int n;

cin>>n;

int arr [n];

for(int i=0;i<n;i++){
cin>>arr[i];

int key;

cin>>key;

cout<<binarySearch(arr,n,key);

return 0;

}
This question requires the implementation of a C++ function to merge
two sorted arrays A and B into a third array C in ascending order.

#include <iostream>

#include<algorithm>

using namespace std;

void mergearray(int a[],int m,int b[],int n,int c[]){

for(int i=0;i<m;i++)c[i]=a[i];

for(int i=0;i<n;i++)c[m+i]=b[i];//

sort(c,c+m+n);

int main(){

int n,m;

cout<<"enter the size of array a"<<endl;

cin>>m;

cout<<"enter the size of array b"<<endl;

cin>>n;

int a[m],b[n],c[m+n];

for(int i=0;i<m;i++){

cin>>a[i];

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

cin>>b[i];

}
mergearray(a,m,b,n,c);

for(int i=0;i<m+n;i++){

cout<<c[i]<<" ";

cout<<endl;

return 0;

Transeverse of 2 D array:
#include <iostream>

using namespace std;

int main() {

int A[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};

// Transpose the matrix (in-place for a square matrix)

for (int i = 0; i < 3; i++) {


for (int j = i +1; j < 3; j++) {

// Swap A[i][j] and A[j][i]

int temp = A[i][j];

A[i][j] = A[j][i];

A[j][i] = temp;

// Display the transposed matrix

cout << "Transposed Matrix: " << endl;

for (int i = 0; i < 3; i++) {

for (int j = 0; j < 3; j++) {

cout << A[i][j] << " ";

cout << endl;

return 0;

}
The outer loop iterates through rows (i), while the inner loop handles the columns (j), starting
at i + 1 to ensure only the upper triangle of the matrix is processed.

Iterations:

1. i = 0:
o j = 1: Swap A[0][1] (2) with A[1][0] (4).
o j = 2: Swap A[0][2] (3) with A[2][0] (7).
2. i = 1:
o j = 2: Swap A[1][2] (6) with A[2][1] (8).
3. i = 2:
o The loop doesn't execute because j = i + 1 = 3 exceeds the matrix size.

At the end of this process, the matrix is fully transposed.

Why Not j = 0?

If the inner loop started from j = 0, you would:

1. Redo swaps that have already been performed (e.g., swap A[1][0] with A[0][1] again).
2. Waste time processing diagonal elements that don't need to be swapped.

By starting from j = i + 1, the algorithm avoids these inefficiencies.


using namespace std;

int main() {

int n1, n2, n3;

cin >> n1 >> n2 >> n3;

int m1[n1][n2];

int m2[n2][n3];

// Input first matrix

for (int i = 0; i < n1; i++) {

for (int j = 0; j < n2; j++) {


cin >> m1[i][j];

// Input second matrix

for (int i = 0; i < n2; i++) {

for (int j = 0; j < n3; j++) {

cin >> m2[i][j];

int ans[n1][n3] = {0}; // Initialize result matrix with 0

// Matrix multiplication

for (int i = 0; i < n1; i++) {

for (int j = 0; j < n3; j++) {

for (int k = 0; k < n2; k++) {

ans[i][j] += m1[i][k] * m2[k][j];

// Output the result matrix

for (int i = 0; i < n1; i++) {


for (int j = 0; j < n3; j++) {

cout << ans[i][j] << " "; // Add space between numbers

cout << endl; // Move to the next row

return 0;

Matrix Search:
#include <iostream>

using namespace std;

int main() {

int n,m;

cin>>n>>m;

int target;cin>>target;

int mat[n][m];

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

for(int j=0;j<m;j++)

cin>> mat[i][j];

int r=0,c=m-1; //top right positon

bool found=false;

while(r<n && c>=0){


if(mat[r][c]==target){

found =true;

if(mat[r][c]>target){

c--;

else{

r++;

if (found)

cout<<"element found"<<endl;

else{

cout<<"element no exist";

return 0;

}
Running sum of an array using vector library like leetcode:

#include <vector>//used for dynamic library

#include <iostream>

using namespace std;

class Solution {

public:

vector<int> runningSum(vector<int>& nums) {

for (int i = 1; i < nums.size(); ++i) {

nums[i] += nums[i - 1]; // Add the previous element directly

return nums;

};

int main() {

Solution sol;

vector<int> nums = {1, 2, 3, 4};

vector<int> result = sol.runningSum(nums);

// Print the result

for (int num : result) {


cout << num << " ";

return 0;}

Running sum of array:

#include <iostream>

using namespace std;

void runningSum(int nums[], int n, int result[]) {

result[0] = nums[0]; // Initialize the first element

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

result[i] = result[i - 1] + nums[i]; // Add the previous sum to the current element

int main() {

int n;

cout << "Enter the size of the array: ";

cin >> n;

int nums[n]; // Input array


int result[n]; // Output array to store the running sum

cout << "Enter the elements of the array:\n";

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

cin >> nums[i];

// Calculate the running sum


runningSum(nums, n, result);

// Print the result

cout << "Running sum of the array:\n";

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

cout << result[i] << " ";

return 0;

}
Reverse of an array using 2 pointer approach:

#include <iostream>

using namespace std;

void arrayReverse(int arr[],int n){

int start=0,end=n-1;

while(start<=end){

swap(arr[start],arr[end]);

start++;

end--;

int main(){

int arr[]={1,6,7,8,9,4};

int n=6;

arrayReverse(arr,n);

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

cout<<arr[i]<<endl;

return 0;

}
Swap the largest and smallest number of an array:

#include <iostream>
#include <climits> // For INT_MIN and INT_MAX
using namespace std;

void swapMaxMin(int a[], int n) {


int smallest = INT_MAX, largest = INT_MIN;
int smallestIndex = 0, largestIndex = 0;

// Find the indices of the smallest and largest elements


for (int i = 0; i < n; i++) {
if (a[i] < smallest) {
smallest = a[i];
smallestIndex = i;
}
if (a[i] > largest) {
largest = a[i];
largestIndex = i;
}
}

// Swap the largest and smallest elements


int temp = a[smallestIndex];
a[smallestIndex] = a[largestIndex];
a[largestIndex] = temp;
}

int main() {
int a[] = {1, 6, 7, 8, 9, 4}; // Array of elements
int n = 6; // Size of the array

// Swap the maximum and minimum elements


swapMaxMin(a, n);

// Print the modified array


cout << "Array after swapping max and min: ";
for (int i = 0; i < n; i++) {
cout << a[i] << " ";
}
cout << endl;
return 0;
}

Print the unique value in array:


#include <iostream>

using namespace std;

void uniqueArray(int a[],int n){

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

int count=0;

for(int j=0;j<n;j++){

if(a[i]==a[j])

count++;

if(count==1){

cout<<a[i];

cout<<endl;

int main (){

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

int n=6;
uniqueArray( a,n);

return 0;

Intersection of two arrays

#include <iostream>

using namespace std;

void intersectionArray(int a1[],int n ,int a2[],int m){

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

int count=0;

for(int j=0;j<m;j++){
if(a1[i]==a2[i]){

cout<<a1[i]<<" ";

break;

cout<<endl;

int main (){

int a1[]={1,2,2,3,5,6};

int n=6;

int a2[]={1,4,2,3,8,9};

int m=6;

intersectionArray( a1, n ,a2, m);

return 0;

You might also like