How to perform a single action in different ways in C++ ?


In C++, there are multiple ways to perform a single action. Here are some examples:

  • Printing a message to the console:
  • Using cout from the iostream library:
     #include <iostream>

     int main() {
         std::cout << "Hello, world!" << std::endl;
         return 0;
     }
  • Using printf from the cstdio library:
     #include <cstdio>

     int main() {
         printf("Hello, world!\n");
         return 0;
     }
  • Looping through an array:
  • Using a for loop:
     int arr[] = {1, 2, 3, 4, 5};
     for (int i = 0; i < 5; i++) {
         std::cout << arr[i] << " ";
     }
  • Using a while loop:
     int arr[] = {1, 2, 3, 4, 5};
     int i = 0;
     while (i < 5) {
         std::cout << arr[i] << " ";
         i++;
     }
  • Sorting an array:
  • Using std::sort from the algorithm library:
     #include <algorithm>

     int arr[] = {5, 3, 1, 4, 2};
     std::sort(arr, arr + 5);
     for (int i = 0; i < 5; i++) {
         std::cout << arr[i] << " ";
     }
  • Using a custom sorting algorithm:
     int arr[] = {5, 3, 1, 4, 2};
     for (int i = 0; i < 5; i++) {
         for (int j = i + 1; j < 5; j++) {
             if (arr[i] > arr[j]) {
                 int temp = arr[i];
                 arr[i] = arr[j];
                 arr[j] = temp;
             }
         }
     }
     for (int i = 0; i < 5; i++) {
         std::cout << arr[i] << " ";
     }


About the author

William Pham is the Admin and primary author of Howto-Code.com. With over 10 years of experience in programming. William Pham is fluent in several programming languages, including Python, PHP, JavaScript, Java, C++.