C++ Programming
- Write a C++ Program to print a welcome text in a separate line.
- Write a Program in C++ to add two numbers.
- C++ program for addition of two numbers using functions.
- Add two numbers in C++ using class.
- Addition of two numbers using call by reference in C++
- C++ program to write a program to add two numbers using call by value.
- Swapping of two numbers in C++ without using third variable.
- Swap two numbers in C++ using function.
- C++ program to swap two numbers using class.
- C++ program to swap two numbers using call by value.
- C++ program to swap two numbers using pointers.
- Write a program to swap private data members of two classes using friend function.
- write a program to add data objects of two different classes using friend function.
- Threading in C++.
- C++ thread lambda
- C++ thread lambda with parameter
- C++ thread lambda pass by reference
- Singleton C++ example
Write a program to calculate the highest two numbers in an array with length n, and print these numbers with their indexes.
Method 1
#include <iostream>
using namespace std;
int main ()
{
//Function to implement bubble sort
void bubbleSorting(int arr[], int num);
int x, num;
cout << "Enter the number of elements " << "\n";
cin >> num;
int *arr = new int (num);
cout << "Enter " << num << " numbers" << endl;
for(x=0;x< num; x++)
{
cin >> arr[x];
}
bubbleSorting(arr, num);
}
void bubbleSorting(int arr[], int num)
{
int i, j;
for (i = 0; i < num - 1; i++)
for (j = 0; j < num - i - 1; j++){
if (arr[j] > arr[j + 1])
swap(arr[j], arr[j + 1]);
}
cout << "Largest number is : " << arr[num -1] << " at index: " << num -1 << endl;
cout << "Second Largest number is : " << arr[num -2] << " at index: " << num -2 << endl;
return;
}
Output
Enter the number of elements
6
Enter 6 numbers
23
32
45
12
8
37
Largest number is : 45 at index: 5
Second Largest number is : 37 at index: 4
Method 2
#include <iostream>
#include <climits> // For INT_MIN
using namespace std;
void findTwoHighest(int arr[], int n) {
int Highest = INT_MIN, secondHighest = INT_MIN;
int HighestIndex = -1, secondHighestIndex = -1;
for (int i = 0; i < n; i++) {
if (arr[i] > Highest) {
secondHighest = Highest;
secondHighestIndex = HighestIndex;
Highest = arr[i];
HighestIndex = i;
} else if (arr[i] > secondHighest && arr[i] != Highest) {
secondHighest = arr[i];
secondHighestIndex = i;
}
}
if (secondHighest == INT_MIN) {
cout << "There is no second highest number.\n";
} else {
cout << "Highest number: " << Highest << " at index " << HighestIndex << endl;
cout << "Second Highest number: " << secondHighest << " at index " << secondHighestIndex << endl;
}
}
int main() {
int n;
cout << "Enter the number of elements: ";
cin >> n;
int arr[n];
cout << "Enter the numbers:\n";
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
findTwoHighest(arr, n);
return 0;
}
Output
Enter the number of elements: 6
Enter the numbers:
23
105
25
12
36
58
Highest number: 105 at index 1
Second Highest number: 58 at index 5