Program to Find Kth Largest Element of an Array.

Given an array of n distinct elements and we need to find the kth largest number from the given array where the value of k is larger than the size of the given array.

Example:

Input: arr[] = {4, 9, 2, 7, 3, 10}, k = 3
Output: 7

Input: arr[] = {4, 9, 2, 7, 3, 10}, k = 5
Output: 3

Approach 1: Using Sorting.

The simplest approach that anyone can think of is to sort the given array in ascending order and return the element present at index (n-k) and array elements are stored based on 0-based indexing. You can use the sort function given in almost all programming languages or you can use quick sort whose time complexity is O(nlogn).

C++ Code Implementation:
//C++ code to find the kth largest element of an array
#include<iostream>
#include<algorithm>
using namespace std;

//function to return kth largest element
int largestNumber(int arr[], int n, int k){
    //sort the array
    sort(arr, arr+n);

    return arr[n-k];
}

int main(){
    
    int arr[] = {4, 9, 2, 7, 3, 10};
    //size of given array
    int n = sizeof(arr)/sizeof(arr[0]);
    int k = 3;
    cout<<"The kth largest element is: "<<largestNumber(arr, n, k); 

    return 0;
}
Output:
The kth largest element is: 7
  • Time Complexity: O(nlogn)
  • Space Complexity: O(1)

Approach 2: Using Set data structure.

The set data structure is used to store unique elements same type in sorted order. As mentioned in the question itself that all elements are distinct which means if we store them in a set data structure we can easily find the kth largest element.

C++ Code Implementation:
//C++ code to find kth largest element of an array using set
#include<bits/stdc++.h>
using namespace std;

//function to return kth largest element
int largestNumber(int arr[], int n, int k){
    //set data structure
    set<int> s(arr, arr+n);
    //pointer to first element
    set<int>::iterator it = s.begin();
    advance(it, n-k);

    return *it;
}

int main(){
    
    int arr[] = {4, 9, 2, 7, 3, 10};
    //size of given array
    int n = sizeof(arr)/sizeof(arr[0]);
    int k = 2;
    cout<<"The kth largest element is: "<<largestNumber(arr, n, k); 

    return 0;
}
Output:
The kth largest element is: 9

String Class in C++

Many people get confused with the definition of string in C++ whether it is a class or a data type. Let's make it clear that string is not a built-in data type but its behavior is very much similar to the fundamental data types.

String Class in C++

A String is a class from the standard template library that defines objects and is used to store a sequence of variable-length characters surrounded by double quotes(" ") that end with a null character '\0'. 

We use String data type to store words or a sentence kind of data.

  • Example 1: "Algolesson"
  • Example 2: "We are learning C++ Programming"

Note: All the functionality that we need to work with String class is available in the <string> header file so it is good practice to include this header file while working with String.


Some important properties of String:

  • In string, memory allocation takes place dynamically at runtime so no memory is wasted.
  • String implementations are slower than character arrays.
  • String provides several inbuilt functionalities that we can use to perform operations on strings.


How do you Declare and Initialize a string in C++?

String declaration is very much like any other data type, we use the string keyword followed by string name (variable name) which is going to store our value. In the below example, str is the string name and the default initialization of this string is empty. 

ex: string str; //str is an empty string


There are multiple ways to initialize a string in C++ and below are a few examples:

String Initialization Examples Definition
string str; In this example, the string is empty which is a default Initialization whenever we create a string.
string str2(str1); In this example, we are copying the value of one string (str1) into another string (str2).
string str("algolesson"); In this example, the str string is copying the value of the string literal present in double quotes "algolesson".
string str = "algolesson"; In this example also, the str string is copying the value of the string literal present in double quotes "algolesson".
string str(n, 'e'); In this example also, we initialize the string with n copies of the character 'e'.

C++ Code for string declaration and Initialization.

//C++ Code example for initialization
#include<iostream>
#include<string>
using namespace std;

int main(){

    string str1; //empty string
    string str2 ("What is your name?");
    string answer = "My name is John";
    str1 = "I am a Software Engineer.";
    string copyChar (3, 'w');
    string companyName (".algolesson.com");

    //Printing the string values
    cout<<str2<<endl;
    cout<<answer<<" "<<str1<<endl;
    cout<<copyChar<<companyName<<endl;

    return 0;
}
Output:
What is your name?
My name is John I am a Software Engineer.
www.algolesson.com

There are several operations that you can perform on String in C++ programming language. Let's understand each of them one by one. 

Read and Write Operations on String in C++ (getline()).

There are multiple ways to perform read/write operations on a string one is by using cin (character input) and cout (character output) objects but there is one limitation the cin can read only one word and everything after the white space is discarded. Let's understand with one example:
//C++ code to read and write string
#include<iostream>
#include<string>
using namespace std;

int main(){
    //empty string
    string str;
    //input from the user
    cout<<"Enter a string: ";
    cin>>str;
    cout<<str<<endl;

    return 0;
}
Output:
Enter a string: Hello World
Hello

If you observe in the above example, we entered a two-word string "Hello World" separated by white space but our string variable str is able to only the first word. To overcome this problem and to read an entire line of string we use the getline() standard library function which read the input one line at a time until the EOF(End of File) is encountered. 

Let's understand getline()in C++ with one example:
//C++ code to read and write string using getline()
#include<iostream>
#include<string>
using namespace std;

int main(){
    //empty string
    string name, subject;

    cout<<"What is your name? ";
    //use of getline() function
    getline(cin,name); 
    cout<<name<<endl;

    cout<<"Enter your subject name: ";
    //use of getline() function with delimiting character
    getline(cin,subject,'-'); 
    cout<<subject;
    
    return 0;
}
Output:
What is your name? I am John Wick
I am John Wick
Enter your subject name: Operating-System
Operating
In the above example code, we have taken user input using the getline() function, and when we use it for the first time (getline(cin, name)) we can observe that the entire line is displayed which means that getline() function capture characters even after white spaces. 

When we use the getline() function for the second time (getline(cin, subject, '-')) we have added a delimiting character (-) that is added as the third parameter of the function and it means that any character that appears after this delimiting character is discarded.

How to Access String Elements in C++?

String class is used to store a sequence of characters and each character takes one byte of memory. There are several ways to access individual characters of a string. 
String Function Definition
operator [pos] This function is used to return a reference of the character at position pos in the string. We can also modify the character of that position (pos).
at() This function is used to return a reference of the character at position pos in the string. We can also modify the character of that position.
back() This function is used to return a reference of the last character of the string. We can also add one character at the end using this function.
front() This function is used to return a reference of the first character of the string. We can also add one character at the front using this function.

Let's understand the ways of accessing characters in a string in C++ code:
/*C++ program to access string elements*/
#include<iostream>
#include<string>
using namespace std;

int main(){

  string str = "Welcome to Algolesson";
  //working of [] operator
  for(int i = 0; i < str.size(); i++){
    cout<<str[i];
  }
  //working of at()
  cout<<endl;
  for(int i = 0; i < str.size(); i++){
    cout<<str.at(i);
  }
  cout<<endl;
  //working of back()
  str.back() = '!';
  cout<<"The last character of the string is: "<<str.back()<<endl;
  //working of front()
  str.front() = '@';
  cout<<"The first  character of the string is: "<<str.front()<<endl;

  cout<<"String after operation: "<<str<<endl;
  return 0;
}
Output:
Welcome to Algolesson
Welcome to Algolesson
The last character of the string is: !
The first  character of the string is: @
String after operation: @elcome to Algolesso!



I hope you found this post useful, please write a comment if you found anything incorrect or share your valuable feedback. 

C++ Program to Check if a Year is a Leap Year.

In this post, you will learn to check whether a year is a leap year or not using the C++ programming language. But before moving to the coding part it is important to get some basic understanding of Leap Year. Let's start this topic with our first question and that is:


What is Leap Year?

A Year that contains 366 days is known as Leap Year. We get one leap year every four years and this year February month contains 29 days which is one extra day than any usual year. Examples of Leap Years: 1968, 2000, 2004, 2012, etc. 


How to Check if a Year is Leap Year or not?

There are certain conditions that you can check to find out whether a year is a leap year or not. 

  • If the given year is divisible by 400 then it is a leap year.
  • If the given year is divisible by 100 but not divisible by 400 then it is not a leap year.

  • If the given year is divisible by 4 but is not divisible by 100 then it is a leap year.
  • If both the above conditions fail to satisfy then the given year is not a leap year.

C++ Program to check Leap Year using if else statement.

//C++ Code to check Leap year using if else.
#include<iostream>
using namespace std;

int main(){

    int year;

    cout<<"Enter a Year: ";
    cin>>year;

    //Year divisible by 400
    if(year % 400 == 0)
       cout<<year<<" is a Leap Year.";
    //Year divisible by 100 but not divisible by 400   
    else if(year % 100 == 0)
       cout<<year<<" is not a Leap Year.";
    //Year divisible by 4 but not divisible by 100   
    else if(year % 4 == 0)
       cout<<year<<" is a Leap Year.";
    else
       cout<<year<<" is not a Leap Year.";

    return 0;            
}
Output:
Enter a Year: 1968
1968  is a Leap Year.


C++ Program to check Leap Year using nested if else statement.

//C++ Code to check Leap year using nested if else.
#include<iostream>
using namespace std;

int main(){

    int year;

    cout<<"Enter a Year: ";
    cin>>year;

    if(year % 4 == 0){
        if(year % 100 == 0){
            if(year % 400 == 0){
                cout<<year<<" is a Leap Year.";
            }
            else{
                cout<<year<<" is not a Leap Year.";
            }
        }
        else{
            cout<<year<<" is a Leap Year.";
        }
    }
    else{
        cout<<year<<" is not a Leap Year.";
    }

    return 0;            
}
Output:
Enter a Year: 2006
2006  is not a Leap Year.

Here in the above program, first, check if the year is divisible by 4 or not if not divisible then the given year is not a leap year. If the year is divisible by 4 then check if it is divisible by 100 or not, if not divisible by 100 then it is a leap year else, not a leap year. If the year is divisible by 100 then it must be divisible by 400 to be a leap year.

C++ Program to Check an Armstrong Number.

In this post, we will learn to check if a given number is Armstrong's number or not. Before checking any number we first need to understand what an Armstrong number is? Any positive n digits integer is called an Armstrong number of order n when the number can be expressed in the below format:

[abcd... = pow(a, n) + pow(b, n) + pow(c, n) + pow(d, n) + ...]

Here n = number of digit present.


Example of Armstrong Numbers.

Input: num = 153
Output: 153 is an Armstrong number.

Explanation: 
1*1*1 + 5*5*5 + 3*3*3 = 1 + 125 + 27 = 153

Input: num = 135
OutL 135 is not an Armstrong number.

Explanation: 1*1*1 + 3*3*3 + 5*5*5 = 1 + 27 + 125 = 153  135

Input: num = 1634
Output: 1634 is an Armstrong number.

Explanation: 
1*1*1*1 + 6*6*6*6 + 3*3*3*3 + 4*4*4*4 = 1 + 1296 + 81 + 256 = 1634

C++ Program to check three Digit Armstrong numbers.

//C++ code to check the three-digit Armstrong number.
#include<iostream>
using namespace std;

int main(){
    
    int num, numCopy, remainder, ans = 0;
    cout<<"Enter a three digit integer: ";
    cin>>num;
    numCopy = num;

    while(numCopy != 0){
        //this remainder always contain last digit
        remainder = numCopy % 10;

        ans += remainder * remainder * remainder;

        //remove the last digit of a number.
        numCopy /= 10;
    }
    
    if(ans == num)
       cout<<num<<" is an Armstrong Number.";
    else
       cout<<num<<" is not an Armstrong Number.";   
    return 0;                    
}
Output:
Enter a three digit integer: 153
153 is an Armstrong Number.
The above program can only check three-digit Armstrong numbers but if we get any integer with more digits then the above program will fail. (alert-warning) 

C++ Program to check n Digits Armstrong number.

//C++ code to check n digit Armstrong number.
#include<iostream>
#include<math.h>
using namespace std;

int main(){
    
    int num, numCopy, remainder, ans = 0;
    cout<<"Enter an integer: ";
    cin>>num;
    numCopy = num;
    
    //variable to store a number of digits
    int n = 0;
    //counting number of digits present given num 
    while(numCopy != 0){
        numCopy /= 10;
        n++;
    }
    numCopy = num;

    while(numCopy != 0){
        //this remainder always contain the last digit
        remainder = numCopy % 10;

        ans += round(pow(remainder, n));

        //remove the last digit of number.
        numCopy /= 10;
    }
    
    if(ans == num)
       cout<<num<<" is an Armstrong Number.";
    else
       cout<<num<<" is not an Armstrong Number.";   
    return 0;                    
}
Output:
Enter a three digit integer: 1634
1634 is an Armstrong Number.

The above program can check an Armstrong number with n number of digits and to do so we first need to count the number of digits present in the user input and store it in a variable n. This calculation is done by the first while loop in the program.
 
Next, while loop will check if the number is an Armstrong number or not, and for that, we will use the math pow(a, n) function which is present inside <math.h> header file.

C++ Code to Convert Celsius to Fahrenheit (vice versa).

In this post, we will learn to write C++ code to convert Celsius to Fahrenheit. We can use below conversion formula for our temperature calculation. Let's understand with one example.


Formula to calculate Fahrenheit when Celsius is given:

F = (C * 1.8) + 32

In the above mathematical formula, C stands for temperature given in Degree Celsius and F stands for the Degree Fahrenheit temperature we will get after the calculation. In most countries, Celsius is used to measuring the temperature but in US Fahrenheit is used to measure temperature.

Example: Find the degree Fahrenheit when the celsius temperature is 50°C.

F = (C * 1.8) + 32

  = (50 * 1.8) + 32

  = (90) + 32

  = 122°F(alert-passed)


C++ Code Implementation for Celsius to Fahrenheit conversion.

//C++ code to convert celsius to Fahrenheit
#include<iostream>
using namespace std;

int main(){
    float celsius, fahrenheit; 
   
    cout<<"Enter the temperature in Celsius: ";
    cin>>celsius;
    fahrenheit = (celsius * 1.8) + 32;
    cout<<"The temperature in Fahrenheit is: "<<fahrenheit;

    return 0;                    
}
Output:
Enter the temperature in Celsius: 50
The temperature in Fahrenheit is: 122

Converting Fahrenheit to Celsius.
We can also convert Fahrenheit to Celsius by deriving a new formula using the same above formula. We just did some basic math to create Fahrenheit to Celsius formula as shown below.

F = (C * 1.8) + 32

F - 32 = (C * 1.8)

(F - 32)/1.8 = C

C = (F - 32)/1.8

Example: Find the degree Celsius when the Fahrenheit temperature is 122°F.

C = (F - 32)/1.8

  = (122 - 32)/1.8

  = (90)/1.8

  = 50°F(alert-passed)

C++ Code Implementation for Fahrenheit to Celsius Conversion.

//C++ code to convert Fahrenheit to celsius
#include<iostream>
using namespace std;

int main(){
    float celsius, fahrenheit; 
   
    cout<<"Enter the temperature in Fahrenheit: ";
    cin>>fahrenheit;
    celsius = (fahrenheit - 32) / 1.8;
    cout<<"The temperature in Celsius is: "<<celsius;

    return 0;                    
}

Output:

Enter the temperature in Fahrenheit: 122
The temperature in Celsius is: 50

C++ Program to Find Biggest of Three Numbers.

Here we will understand how to find the largest number among the three numbers using C++ code. 

Examples:
Input: int a = 5, b = 8, c = 2
Output: The Biggest number among the three is 8

Input: int a = 54, b = 21, c = 9
Output: The Biggest number among the three is 54

There are multiple ways to solve this problem:
  1. Using if statement.
  2. Using if-else statement.
  3. Using Ternary Operator.
1. Algorithm using if statement.
  • Take three input variables from the user and store them in three different variables a, b, and c.
  • Check condition if a >= b and a >= c, if both conditions are true then print "The Biggest number among three is a. 
  • Check condition if b >= a and b >= c, if both conditions are true then print "The Biggest number among three is b. 
  • Check condition if c >= a and c >= b, if both conditions are true then print "The Biggest number among three is c.  
  • Stop the Program.
//C++ Code to find Biggest among three numbers
#include<iostream>
using namespace std;

int main(){
    int a, b, c;

    cout << "Enter three numbers: ";
    cin >> a >> b >> c;

    if(a >= b && a >= c)
       cout<<"The Biggest number among the three is "<<a;

    if(b >= a && b >= c)
       cout<<"The Biggest number among the three is "<<b;

    if(c >= a && c >= b)
       cout<<"The Biggest number among the three is "<<c;
             
    return 0;                    
}
Output:
Enter three numbers: 10 34 54
The Biggest number among the three is 54

2. Algorithm using if-else statement
This algorithm is a little better than the previous one because here we are not going to check the remaining conditions once we find our first true condition.  
  • Take three input variables from the user and store them in three different variables a, b, and c.
  • Check first if-condition, a >= b and a >= c, if conditions are true then print "The Biggest number among three is a" and end the program.
  • Check the next else-if condition b >= a and b >= c, if conditions are true then print "The Biggest number among three is b" and end the program.
  • If both the above conditions fail then without checking any further conditions you can declare the third variable as the largest variable.
  • End the Program.
//C++ Code to find Biggest among three numbers
//using if-else 
#include<iostream>
using namespace std;

int main(){
    int a, b, c;

    cout << "Enter three numbers: ";
    cin >> a >> b >> c;

    if(a >= b && a >= c)
       cout<<"The Biggest number among the three is "<<a;
    else if(b >= a && b >= c)
       cout<<"The Biggest number among the three is "<<b;
    else
       cout<<"The Biggest number among the three is "<<c;
             
    return 0;                    
}
Output:
Enter three numbers: -5 4 5
The Biggest number among the three is 5

3. Algorithm using Ternary Operator.
The ternary operator is a shorter way of writing if-else conditions and based on the results of the condition a particular block of code executes.
  • (condition) ? expression 1 : expression 2
Here, if the condition is true then expression 1 will get executed and if the condition is false then expression 2 will get executed.
//C++ Code to find Biggest among three numbers 
//using ternary operator
#include<iostream>
using namespace std;

int main(){
    int a, b, c;
    int ans;
    cout << "Enter three numbers: ";
    cin >> a >> b >> c;

    //Ternary Operator
    ans = (a >= b ? (a >= c ? a : c) : (b >= c ? b : c));
    
    cout<<"The Biggest number among the three is "<<ans;
             
    return 0;                    
}
Output:
Enter three numbers: 5 3 12
The Biggest number among the three is 12

C++ Program to check a Prime Number.

To write code for Prime number checking first we need to understand what is Prime Number? Any number which is divisible only itself and 1 is known as Prime Number. Example: 2, 3, 5, 7, etc. You cannot divide these numbers with any other number except 1 and itself but one thing to make sure of here is that 0 and 1 are not Prime Numbers.


We can follow the below instructions to check if a number is Prime or not:

  • Create a boolean flag is_prime and mark and initially initialize it with true.
  • Check if the given number n is 0 or 1, if yes then set the is_prime flag value equal to false and print a message that the given number is not prime. 
  • If the n is greater than 1 then run a for loop from i = 2 up to i <= n/2 where n is the number that we need to check. Keep on incrementing the value of i by 1 with each iteration.

Note: We are running the loop up to n/2 because it is not possible to find any factor of n beyond n/2.(alert-passed)

  • In any iteration, the value of i perfectly divides the given value n then set the is_prime flag value equal to false and prints a message that the given number is not prime, else prints a message that the given number is a prime number.

Example: C++ Code to check Prime Number.

//C++ Code to check prime number
#include<iostream>
using namespace std;

int main(){

    int n;
    bool is_prime = true;

    cout<<"Enter a positive number: ";
    cin>>n;

    if(n == 0 || n == 1)
       is_prime = false;

    for(int i = 2; i <= n/2; i++){
        if(n % i == 0){
            is_prime = false;
            break;
        }
    }   

    if(is_prime)
       cout<<n<<" is a prime number.";
    else
       cout<<n<<" is not a prime number.";

    return 0;                    
}
Output:
Enter a positive number: 7
7 is a prime number.

DON'T MISS

Nature, Health, Fitness
© all rights reserved
made with by AlgoLesson