Sei sulla pagina 1di 52

Program to find LCM and GCD/HCF of two numbers in C++

Algorithm:

1. Take two number’s as input.

2. Check if the given numbers are divisible by any number less than
the number itself using for loop.

3. If yes, then store it (in gcd) and continue ahead.

4. After termination of the loop, the last updated value in gcd will
be GCD.

5. To find LCM of the numbers apply the formula for lcm.

6. Now, Print the GCD and LCM


Code:

#include<iostream>
using namespace std;
int main()
{
int fnum,snum,gcd,lcm;
cout<<"Enter first number";
cin>>fnum;
cout<<"\nEnter second number";
cin>>snum;
//find factors of both numbers
for(int i=1;i<=fnum && i<=snum;i++)
{
if(fnum%i==0 && snum%i==0)
gcd=i;
}
//find lcm of both numbers
lcm = fnum*snum/gcd;
cout<<"\n GCD of given numbers is:"<<gcd;
cout<<"\n LCM of given numbers is:"<<lcm;
return 0;
}
Output:

Enter first number 10


Enter second number 5
GCD of given numbers is:5
LCM of given numbers is:10
Program to find Sum of n numbers in C++

Algorithm:

1. Take input of n till which we need to get the sum.

2. Initialize a variable sum and declare it equal to 0(to remove


garbage values).

3. Using while loop, add all numbers 1 to n.

4. Now, Print the sum.


Code:

#include<iostream>
using namespace std;
int main()
{
int n,sum=0;
cout<<"Enter number till which you would like to add";
cin>>n;
while(n>0)
{
sum+=n;
n--;
}
cout<<"\n sum is:"<<sum;
return 0;
}
Enter number till which you would like to add: 3

sum is:6
Program to Extract Substrings from a given string in C++

Algorithm:

1. Take string input in str

2. Store length of string in len

3. Next, get the starting index from user as, start

4. Get starting indes from user as endlen

5. Call the functions after checking the necessary constraints

6. In the function, take a for loop from start to endlen

7. Initialize another string as substr, copy characters of str in


substr.

8. Print substr.
Code:

#include <iostream>
#include <string>
using namespace std;
void substring(string str, int start, int length)
{
int i=start, j;
string substr;
for(j = 0; str[i] !='\0' && length > 0; i++, j ++)
{
substr[j] = str[i];
length--;
}
substr[j] = '\0';
cout<<"\n";
for(int k=0;substr[k]!='\0';k++)
cout<<substr[k];
}
int main()
{
string str;
int start,endlen,len;
cout<<"Enter a string: ";
getline(cin,str);
len=str.length();
cout<<"\n Enter starting position of substring : ";
cin>>start ;
cout<<"\n Enter length of substring: " ;
cin>>endlen;
if(start > 0 && start < 30 && endlen<len )
substring(str,start,endlen);
else
cout<<"Values are invalid\n";
return 0;
}
Output:

Enter a string: GoodMorning


Enter starting position of substring :4
Enter length of substring: 7

Morning
Program to Sort Characters of string in alphabetical order in
C++

Algorithm:

1. Take a string as input.

2. Use nested for loop to compare and traverse the string.

3. Now, check if the previous element is smaller than the next


element, if yes, then do nothing.

4. If no, then swap the characters.

5. Print the sorted string.


Code:

#include <iostream>
#include <string>
using namespace std;
int main ()
{
string str;
cout<<"Enter the string to be sorted: ";
getline(cin,str);
int len = str.length();
cout<<"\n String before sorting: "<<str<<" \n";

//using bubble sort to sort the characters


for (int i = 0; i < len; i++)
{
for (int j = i+1; j < len; j++)
{
if (str[i] > str[j]) //if previous has bigger ascii value than
next,
{
//swapping the prev and next characters
char temp = str[i];
str[i] = str[j];
str[j] = temp;
}
}
}
cout<<"\n String after sorting: "<<str<<" \n";
return 0;
}
Output:

Enter the string to be sorted: quick brown fox jumps over the lazy dog
String before sorting: quick brown fox jumps over the lazy dog

String after sorting: abcdefghijklmnoooopqrrstuuvwxyz


Program to check Armstrong number in C++

Algorithm:

1. Run a for loop to find the number of digits in the number.

2. Create a function to calculate the product of the digit raised to


the power.

3. Add the calculated product to the final sum.

4. Compare the original number with the final sum and output
accordingly.
Code:

#include<iostream>
using namespace std;
int calc(int n, int power)
{
int product=1;
for(int i=0;i<power;i++)
{
product*=n;
}
return product;
}
int main()
{
int i,count=0,rem,sum=0;
cout<<"Enter a number";
cin>>i;
int num=i;
//count digits in number
while(i>0)
{
i=1/10;
count++;
}
i=num;
while(i>0)
{
rem=i%10;
sum=sum+calc(rem,count);//calculate power of rem
i=i/10;
}
if(num==sum)
cout<<"\nArmstrong number!";
else
cout<<" \n Not an Armstrong Number!";
return 0;
}
Output:

Enter a number 3
Armstrong number!
Program to print inverted Floyd’s triangle star pattern in
C++

Algorithm:

The algorithm to print inverted Floyd’s triangle is similar to that of Floyd’s


triangle.

1. Take input from the user for the number of rows.

2. Outer for loop will print the number of rows.

3. The inner loop will print the star pattern.


Code:

#include <iostream>
using namespace std;
int main()
{
int n;
cout<<"Enter number of rows: ";
cin>>n;
cout<<"\n";
for (int i = n; i >= 1; --i)
{
for (int j = 1; j<= i; ++j)
{
cout<<"* ";
}
cout<<"\n";
}
return 0;
}
Output:

Enter number of rows: 5

* * * * *

* * * *

* * *

* *

*
Program to Add two numbers using pointers in C++

Algorithm:

1. Initialize two integer variables.

2. Initialize two integer pointers.

3. Reference the pointers to variables using ‘&’ operator.

4. Now, using * operator, access the address pointed by pointers.

5. Add the values, and store it.

6. Print the sum.


Code:

#include <iostream>
using namespace std;
int main()
{
int num1, num2;
int *ptr1,* ptr2;
int sum;
cout<<"\n Enter first number: ";
cin>>num1;
cout<<"\n Enter second number: ";
cin>>num2;
ptr1 = &num1; //assigning an address to pointer
ptr2 = &num2;
sum = *ptr1 + * ptr2; //values at address stored by pointer
cout<<"\n Sum is: "<< sum;
return 0;
}
Output:

Enter first number: 3


Enter second number: 4
Sum is: 7
Program to find Factorial in C++

Algorithm:

1. Take input.

2. Initialize a variable to store product of numbers.

3. Run a for loop which runs from 1 till the given number.

4. Multiply each number with the fact variable.

5. Print the output.


Code:

#include<iostream>
using namespace std;
int main()
{
int n,fact=1;
cout<<"Enter number";
cin>>n;
for(int i=1;i<=n;i++)
fact=fact*i;
cout<<"\n Factorial of given number is:"<<fact;
return 0;
}
Output:

Enter number: 6
Factorial of given number is:720
Program to print Fibonacci Series in C++

Algorithm:

1. Take the input for the series of elements to be printed.

2. Take two variable, pre and next and assign pre = 0 and next = 1.

3. Take another variable, last which will be the sum of pre and next.

4. Run a while loop.

5. Print the value of pre.

6. Change the values of pre, next and last in the loop.

7. End loop after n iterations.


Code:

#include<iostream>
using namespace std;
int main()
{
int n,pre,next,last;
cout<<"How many numbers of fibonacci series do you want to
print?";
cin>>n;
pre=0; //previous number
next=1; //next number
last=pre+next;
while(n>0)
{
cout<<"\n"<<pre;
pre=next; //pushing the three values ahead
next=last;
last=pre+next; //third number is sum of new first and
second number
n--;
}
return 0;
}
Output:

How many numbers of Fibonacci series do you want to print? 10


0
1
1
2
3
5
8
13
21
34
Program to Concatenate two strings in C++

Algorithm:

1. Take two strings as input.


2. Initialize i as length of string1 -1
3. Run a loop with characters of j
4. Store characters of string2 in 1, and then, increment i.
5. Terminate the string1 with ‘\0’
6. Output the resultant string.
Code:

#include <iostream.h>
#include<conio.h>
#include<string.h>
void main()
{
char str1[30]="blue";
char str2[30] = "oceans";
int i=0,stop;

//to get the last index containing character


do {
stop=i++;
}while(str1[i]!='\0');

i=stop+1;
//concate strings
for(int j = 0; str2[j] != '\0'; j++, i++)
str1[i] = str2[j]; //copying chars of string2 in 1, one
by one

str1[i] = '\0'; //to terminate resultant string


cout<<"\n Resultant string is: "<< str1;
getch();
}
Output:

Enter string 1: Good


Enter string 2: Morning
Concated String: GoodMorning
Program to find the vowels in given string

Algorithm:

1. Take a string as input.


2. Declare an array of size 5.
3. Traverse the string and print the count array.
Code:

#include <iostream>
#include <string>
using namespace std;
int vowel(char c)
{
switch(c)
{
case 'a' :
{return 0;break;}
case 'A' :
{return 0;break;}
case 'e':
{return 1;break;}
case 'E':
{return 1;break;}
case 'i' :
{return 2;break;}
case 'I':
{return 2;break;}
case 'o':
{return 3;break;}
case 'O':
{return 3;break;}
case 'u' :
{return 4;break;}
case'U':
{return 4;break;}
default:
{return 5;break;}
}
}int main()
{
string str;
int count[5]={0},x;
cout<<"Enter a string: ";
getline(cin,str);
int len=str.length();
for(int i = 0; i<len; i++)
{ x=vowel(str[i]);
if(x<5)
count[x]+=1;
}
cout<<"\n a:"<< count[0];
cout<<"\n e:"<<count[1];
cout<<"\n i:"<<count[2];
cout<<"\n o:"<<count[3];
cout<<"\n u:"<<count[4];

return 0;
}
Output:

Enter a string: aeiouaeiou


a:2
e:2
i:2
o:2
u:2
Program to delete vowels from a given string

Algorithm:

1. Input a string.

2. Run a for loop to traverse the given string.

3. Check each character is a vowel or not, using the function.

4. Copy the contents of the new string in the old string.

5. Print the modified string


Code:

#include <iostream>
#include <cstring>
using namespace std;
int vowel(char c)
{
if (c == 'a' || c == 'A' || c == 'e' || c == 'E' || c == 'i' || c
== 'I' || c =='o' || c=='O' || c == 'u' || c == 'U')
return 1; // a vowel
else
return 0; // not a vowel
}
int main()
{
string str,newstr;
cout<<"Enter a string: ";
getline(cin,str);
int len=str.length();
int j=0;
for(int i = 0; i<len; i++)
{
if(vowel(str[i]) == 0)
{
newstr[j] = str[i]; //newstr is string without
vowels
j++;
}
}
newstr[j] = '\0'; //terminate the string
strcpy(str, newstr); //copying the new string,
cout<<"Modified String:"<<str;
return 0;
}
Output:

Enter a string: Vowels will be deleted

Modified string: Vwls wll b dltd


Program to Extract Substrings from a given string in C++

Algorithm:

1. Take string input in str

2. Store length of string in len

3. Next, get the starting index from user as, start

4. Get starting indes from user as endlen

5. Call the functions after checking the necessary constraints

6. In the function, take a for loop from start to endlen

7. Initialize another string as substr, copy characters of str in


substr.

8. Print substr.
Code:

#include <iostream>
#include <string>
using namespace std;
void substring(string str, int start, int length)
{
int i=start, j;
string substr;
for(j = 0; str[i] !='\0' && length > 0; i++, j ++)
{
substr[j] = str[i];
length--;
}
substr[j] = '\0';
cout<<"\n";
for(int k=0;substr[k]!='\0';k++)
cout<<substr[k];
}
int main()
{
string str;
int start,endlen,len;
cout<<"Enter a string: ";
getline(cin,str);
len=str.length();
cout<<"\n Enter starting position of substring : ";
cin>>start ;
cout<<"\n Enter length of substring: " ;
cin>>endlen;
if(start > 0 && start < 30 && endlen<len )
substring(str,start,endlen);
else
cout<<"Values are invalid\n";
return 0;
}
Output:

Enter a string: GoodMorning


Enter starting position of substring :4
Enter length of substring: 7

Morning
Program to Swap two strings in C++

In this method,

 We copy the contents of the first string to a temporary array.


 The, we copy the contents of the second array in the first character array.
 Next, we copy the contents of the temporary array to second character array.
Code:

#include <iostream>

#include <cstring> //string library

using namespace std;

int main() {
int n; //length of string
cin>>n;
char s1[n];
char s2[n];
char s3[n]; //temporary string
//Input String 1
cin>>s1;
//Input String 2
cin>>s2;
strcpy(s3,s1); //copy contents of s1 in s3
strcpy(s1,s2); // similar to s1=s2
strcpy(s2,s3);
cout<<s1<<"\n";
cout<<s2;
return 0;
}
Advantage:

 It is faster than the previous method.

Disadvantage:

 We need to use three strings, which is a waste of memory.


Program to Convert strings to uppercase or lowercase in
C++

Algorithm for upper case -> lower case:

1. Check if the character is between A and Z i.e. it is a capital letter,

2. If the character is a capital, we add 32 to it.

3. Else, the character is already in lower case. Do nothing.

Algorithm for lower case -> upper case:

1. Check if the character is between ‘a’ and ‘z’ i.e. it is a lower case
letter.

2. If the character is a lower case letter, we subtract 32 from it.

3. Else, the character is already in upper case. Do nothing.


Code:

#include <iostream>
using namespace std;

void lower_string(string str)


{
for(int i=0;str[i]!='\0';i++)
{
if (str[i] >= 'A' && str[i] <= 'Z') //checking for
uppercase characters
str[i] = str[i] + 32; //converting uppercase
to lowercase
}
cout<<"\n The string in lower case: "<< str;
}

void upper_string(string str)


{
for(int i=0;str[i]!='\0';i++)
{
if (str[i] >= 'a' && str[i] <= 'z') //checking for
lowercase characters
str[i] = str[i] - 32; //converting lowercase
to uppercase
}
cout<<"\n The string in upper case: "<< str;
}

int main()
{
string str;
cout<<"Enter the string ";
getline(cin,str);
lower_string(str); //function call to convert to lowercase
upper_string(str); //function call to convert to uppercase
return 0;
}
Output:

Enter the string Hola Amigos!


The string in lower case: hola amigos!
The string in upper case: HOLA AMIGOS!
Hello World Program
#include <stdio.h>

int main()
{
printf("\n\n\t\tStudytonight - Best place to learn\n\n\n");
int num;
printf("\nHello world!\nWelcome to Studytonight: Best place to learn\n");
printf("\n\n\t\t\tCoding is Fun !\n\n\n");
return 0;
}
Output:
Program to take input of various datatypes in
C

#include<stdio.h>

int main()
{
printf("\n\n\t\tStudytonight - Best place to learn\n\n\n");

int num1, num2;


float fraction;
char character;

printf("Enter two numbers number\n");

// Taking integer as input from user


scanf("%d%i", &num1, &num2);
printf("\n\nThe two numbers You have entered are %d and %i\n\n", num1, num2);

// Taking float or fraction as input from the user


printf("\n\nEnter a Decimal number\n");
scanf("%f", &fraction);
printf("\n\nThe float or fraction that you have entered is %f", fraction);

// Taking Character as input from the user


printf("\n\nEnter a Character\n");
scanf("%c",&character);
printf("\n\nThe character that you have entered is %c", character);

printf("\n\n\t\t\tCoding is Fun !\n\n\n");

return 0;
}
Output:
A C++ program to read an array of 10 elements and print the sum of all elements of array:

#include <iostream.h>
void main()
{
int a[10], sum=0;
for(int j=0; j<10; j++) //loop for reading
{
cout<< “Enter Element “<< j+1<<”:”;
cin>> a[j]
sum=sum+a[j]`;
}
cout<<”Sum : “<<sum;
}
Program: Here’s another example of an array this program , invites the user to enter a series of six
values representing sales for each day of the week (excluding Sunday), and then calculates the
average sales
#include <iostream.h>
void main()
{
const int SIZE = 6; //size of array
double sales[SIZE]; //array of 6 elements
double total = 0;
cout<< “Enter sales for 6 days\n”;
for(int j=0; j<SIZE; j++) //put figures in array
cin>> sales[j];
for(j=0; j<SIZE; j++) //read figures from array
total += sales[j]; //to find total
double average = total / SIZE; // find average
cout<< “Average = “ << average << endl;
}
Output:-

Enter sales for 6 days


352.64
867.70
781.32
867.35
746.21
189.45
Average = 634.11

Potrebbero piacerti anche