C++ get file name – How to Get Filename From a Path With or Without Extension in C++

How to Get Filename From a Path With or Without Extension in C++

Methods to get filename from a path with or without extension in c++

C++ get file name: In this article, we discuss the different methods to get filename from a path with or without extension in c++. Let’s see c get filename from path with extension, c get filename from path without extension, c remove path from filename, c find all files in directory with extension, c iterate through files in a directory, c filesystempath to string, c++ get filename from path, c get file path, c++ iterate through files in a directory, c++ get file path, c filesystem::path to string, How to get filename from a path with or without extension in c++. The method that we discuss are given below:-

Let’s first understand what we will be going to do in this article. Suppose there is a path name p="/home/user/c++/program.c++" then in this example filename with extension is program.c++ and filename without extension is program. So we will be writing code in c++ to do this task.

Let’s understand all the methods one by one.

Method 1-Using string functions

C++ get file extension: In this method, we use the string in c++ to do the task. We will use different functions that are used in c++ strings to extract the filename. Let see this with the help of an example.

#include <iostream>
#include <string>

using std::string;
string getFileNameWithExtension(const string& s) {
char sep = '/';
#ifdef _WIN32
sep = '\\';
#endif
size_t i = s.rfind(sep, s.length());
if (i != string::npos) 
{
string filename = s.substr(i+1, s.length() - i);
string rawname = filename.substr(0, s.length()); 
return(rawname);
}

return("");
}

string getFileNameWithoutExtension(const string& s) {
char sep = '/';
#ifdef _WIN32
sep = '\\';
#endif
size_t i = s.rfind(sep, s.length());
if (i != string::npos) 
{
string filename = s.substr(i+1, s.length() - i);
size_t lastindex = filename.find_last_of("."); 
string rawname = filename.substr(0, lastindex); 
return(rawname);
}

return("");
}

int main() {

string path = "/home/user/c++/program.c++";
string filename_with_extension = getFileNameWithExtension(path);
string filename_without_extension= getFileNameWithoutExtension(path);
std::cout << "The file name with extension  is \"" << filename_with_extension  << "\"\n";
std::cout << "The file name without extension  is \"" << filename_without_extension << "\"\n";
}

Output

The file name with extension is "program.c++"
The file name without extension is "program"

Method 2-Using C++17 Filesystem library

Java get filename without extension: The Filesystem library provides facilities for performing operations on file systems and their components, such as paths, regular files, and directories. So here we will use the Filesystem library to get filename from a path with and without extension. Let’s write code for this.

#include <iostream>
#include <filesystem>
namespace fs = std::filesystem;
 
int main()
{
    std::cout << "The file name with extension  is " <<fs::path( "/home/user/c++/program.c++" ).filename() << '\n';
    std::cout << "The file name without extension  is " <<fs::path( "/home/user/c++/program.c++" ).stem() << '\n';
        
}

Output

The file name with extension is "program.c++"
The file name without extension is "program"

So these are the methods to get filename with and without extension in c++.

Iterate over string c++ – C++ iterate over set – Different Ways to Iterate Over a Set in C++

C++ iterate over set: In the previous article, we have discussed about C++ Set example and Tutorial – Part 1. Let us learn how to Iterate Over a Set in C++ Program.

Iterate Over a Set

Print set c++: We are going to see how we can iterate over sets in C++.

Iterating over a Set using Iterators :

Iterate over string c++: We can use the std::set functions to iterate over the set. We will be using the begin( ) to point to the first element and then iterate until we reach end( ) i.e. the end of set.

#include <iostream>
#include <set>
#include <string>
#include <algorithm>

int main()
{
    std::set<std::string> setString = { "abc","fab","top","lol","right"};

    //Iterator pointing to the first element of the set
    std::set<std::string>::iterator iter = setString.begin();
    // Iterate the whole set and print all elements 
    while (iter != setString.end())
    {

        std::cout << (*iter) << " , ";
        //Iterator incrmentation
        iter++;
    }

    return 0;
}
Output :

abc , fab , lol , right , top ,

Iterating a set in backward direction using reverse_iterator :

C++ print set: Just like the previous example, we will be iterating through the begin and end, however here we will be suing the rbegin( ) and rend( ) operator. This rbegin() will point to the last element and the rend( ) will point to the first, returning an iterator pointing to the previous element.

#include <iostream>
#include <set>
#include <string>
#include <algorithm>

int main()
{
    std::set<std::string> setString = {"abc", "fab", "top", "lol", "right"};

    //Iterator that points to the first element of the set
    std::set<std::string>::reverse_iterator revIter = setString.rbegin();
    // Iterate the whole set and print all elements
    while (revIter != setString.rend())
    {

        std::cout << (*revIter) << " , ";
        //Iterator incrmentation
        revIter++;
    }

    return 0;
}
Output :

top , right , lol , fab , abc ,

Iterating over a set using Range based for loop :

#include <iostream>
#include <set>
#include <string>
#include <algorithm>

int main()
{
    std::set<std::string> setString = {"abc", "fab", "top", "lol", "right"};
    //Using range based for loop to iterate the set
    for (auto str : setString)
    {
        std::cout << str << " , ";
    }
    return 0;
}
Output :

abc , fab , lol , right , top ,

Iterating over a set using std::for_each and range based for loop :

#include <iostream>
#include <set>
#include <string>
#include <algorithm>

int main()
{
    std::set<std::string> setString = {"abc", "fab", "top", "lol", "right"};
    //Using range based for loop to iterate the set
    std::for_each(setString.begin(), setString.end(), [](const std::string &elem)
                  { std::cout << elem << " , "; });
    return 0;
}
Output :

abc , fab , lol , right , top ,

Answer these:

  1. Iterate through unordered set c?
  2. Iterate through unordered_set c++?
  3. How to iterate through a pair in c?
  4. How to iterate through a pair in c++?
  5. Iterate through unordered set c
  6. C set iterator to index
  7. Find in set c
  8. Iterate over a set python
  9. Ordered set c++
  10. C++ set iterator
  11. Iterator c++
  12. C++ set iterator to index

Python Program to Print the Equilateral Triangle Pattern of Star

Python Program to Print the Equilateral Triangle Pattern of Star

Are you wondering how to seek help from subject matter experts and learn the Java language? Go with these Basic Java Programming Examples and try to code all of them on your own then check with the exact code provided by expert programmers. They have tried to include all details like, python program to print equilateral triangle, print star pattern in python using for loop, python star pattern programs, python pattern programs, triangle pattern in python, star pattern in python using while loop, inverted equilateral triangle in python, python star pattern programs, python pattern programs, triangle pattern in python, python program to print the equilateral triangle pattern of star.

Given the number of rows, the task is to Print Equilateral triangle Pattern of Star in C, C++, and Python

Examples:

Example1:

Input:

Given number of rows = 8

Output:

              * 
             * * 
            * * * 
           * * * * 
          * * * * * 
         * * * * * * 
        * * * * * * * 
       * * * * * * * *

Example2:

Input:

Given number of rows = 10
Given Character to print ='$'

Output

                  $ 
                 $ $ 
                $ $ $ 
               $ $ $ $ 
              $ $ $ $ $ 
             $ $ $ $ $ $ 
            $ $ $ $ $ $ $ 
           $ $ $ $ $ $ $ $ 
          $ $ $ $ $ $ $ $ $ 
         $ $ $ $ $ $ $ $ $ $

Program to Print the Equilateral triangle Pattern of Star in C, C++, and Python

Below are the ways to Print the Equilateral triangle Pattern of Star in C, C++, and Python.

Method #1: Using For Loop (Star Character)

Approach:

  • Give the number of rows as static input and store it in a variable.
  • Take a variable to say g and initialize its value with (2*number of rows)-2.
  • Loop from 0 to the number of rows using For loop.
  • Loop from 0 to g using another For Loop(Inner For loop).
  • Print the space character in the inner For Loop.
  • Decrement the value of g by 1 after the end of the inner For loop.
  • Loop from 0 to m+1 using another For loop(Nested For loop) where m is the iterator value of the parent For loop.
  • Print the star character with space.
  • Print the Newline character after the end of the Two inner For loops.
  • The Exit of the Program.

1) Python Implementation

Below is the implementation:

# Give the number of rows as static input and store it in a variable.
numberOfRows = 8
# Take a variable to say g and initialize its value with (2*number of rows)-2.
g = (2*numberOfRows)-2
# Loop from 0 to the number of rows using For loop.
for m in range(0, numberOfRows):
    # Loop from 0 to g using another For Loop(Inner For loop).
    for n in range(0, g):
      # Print the space character in the inner For Loop.
        print(end=" ")
    # Decrement the value of g by 1 after the end of the inner For loop.
    g = g-1
    # Loop from 0 to m+1 using another For loop(Nested For loop)
    # where m is the iterator value of the parent For loop.
    for n in range(0, m+1):
      # Print the star character with space.
        print('*', end=" ")
    # Print the Newline character after the end of the Two inner For loops.
    print()

Output:

              * 
             * * 
            * * * 
           * * * * 
          * * * * * 
         * * * * * * 
        * * * * * * * 
       * * * * * * * *

2) C++ Implementation

Below is the implementation:

#include <iostream>
using namespace std;

int main()
{

    // Give the number of rows as static input and store it
    // in a variable.
    int numberOfRows = 8;

    // Take a variable to say g and initialize its value
    // with (2*number of rows)-2.
    int g = (2 * numberOfRows) - 2;
    // Loop from 0 to the number of rows using For loop.
    for (int m = 0; m < numberOfRows; m++) {
        // Loop from 0 to g using another For Loop(Inner For
        // loop).
        for (int n = 0; n < g; n++) {
            // Print the space character in the inner For
            // Loop.
            cout << " ";
        }
        // Decrement the value of g by 1 after the end of
        // the inner For loop.
        g = g - 1;
        // Loop from 0 to m+1 using another For loop(Nested
        // For loop) where m is the iterator value of the
        // parent For loop.
        for (int n = 0; n < m + 1; n++) {
            // Print the star character with space.
            cout << "* ";
        }
        // Print the Newline character after the end of the
        // Two inner For loops.
        cout << endl;
    }
    return 0;
}

Output:

              * 
             * * 
            * * * 
           * * * * 
          * * * * * 
         * * * * * * 
        * * * * * * * 
       * * * * * * * *

3) C Implementation

Below is the implementation:

#include <stdio.h>

int main()
{

    // Give the number of rows as static input and store it
    // in a variable.
    int numberOfRows = 13;

    // Take a variable to say g and initialize its value
    // with (2*number of rows)-2.
    int g = (2 * numberOfRows) - 2;
    // Loop from 0 to the number of rows using For loop.
    for (int m = 0; m < numberOfRows; m++) {
        // Loop from 0 to g using another For Loop(Inner For
        // loop).
        for (int n = 0; n < g; n++) {
            // Print the space character in the inner For
            // Loop.
            printf(" ");
        }
        // Decrement the value of g by 1 after the end of
        // the inner For loop.
        g = g - 1;
        // Loop from 0 to m+1 using another For loop(Nested
        // For loop) where m is the iterator value of the
        // parent For loop.
        for (int n = 0; n < m + 1; n++) {
            // Print the star character with space.
            printf("* ");
        }
        // Print the Newline character after the end of the
        // Two inner For loops.
        printf("\n");
    }
    return 0;
}

Output:

                        * 
                       * * 
                      * * * 
                     * * * * 
                    * * * * * 
                   * * * * * * 
                  * * * * * * * 
                 * * * * * * * * 
                * * * * * * * * * 
               * * * * * * * * * * 
              * * * * * * * * * * * 
             * * * * * * * * * * * * 
            * * * * * * * * * * * * *

Method #2: Using For Loop (User Input)

Approach:

  • Give the number of rows as static input and store it in a variable.
  • Scan the character to print as user input and store it in a variable.
  • Take a variable to say g and initialize its value with (2*number of rows)-2.
  • Loop from 0 to the number of rows using For loop.
  • Loop from 0 to g using another For Loop(Inner For loop).
  • Print the space character in the inner For Loop.
  • Decrement the value of g by 1 after the end of the inner For loop.
  • Loop from 0 to m+1 using another For loop(Nested For loop) where m is the iterator value of the parent For loop.
  • Print the star character with space.
  • Print the Newline character after the end of the Two inner For loops.
  • The Exit of the Program.

1) Python Implementation

  • Give the number of rows as user input using int(input()) and store it in a variable.
  • Give the Character as user input using input() and store it in another variable.

Below is the implementation:

# Give the number of rows as user input using int(input()) and store it in a variable.
numberOfRows = int(input('Enter some random number of rows = '))
# Give the character to print as user input using int(input()) and store it in another variable.
characte = input('Enter some random character to print = ')
# Take a variable to say g and initialize its value with (2*number of rows)-2.
g = (2*numberOfRows)-2
# Loop from 0 to the number of rows using For loop.
for m in range(0, numberOfRows):
    # Loop from 0 to g using another For Loop(Inner For loop).
    for n in range(0, g):
      # Print the space character in the inner For Loop.
        print(end=" ")
    # Decrement the value of g by 1 after the end of the inner For loop.
    g = g-1
    # Loop from 0 to m+1 using another For loop(Nested For loop)
    # where m is the iterator value of the parent For loop.
    for n in range(0, m+1):
      # Print the given character with space.
        print(characte, end=" ")
    # Print the Newline character after the end of the Two inner For loops.
    print()

Output

Enter some random number of rows = 10
Enter some random character to print = $
                  $ 
                 $ $ 
                $ $ $ 
               $ $ $ $ 
              $ $ $ $ $ 
             $ $ $ $ $ $ 
            $ $ $ $ $ $ $ 
           $ $ $ $ $ $ $ $ 
          $ $ $ $ $ $ $ $ $ 
         $ $ $ $ $ $ $ $ $ $

2) C++ Implementation

  • Give the number of rows as user input using cin and store it in a variable.
  • Give the Character as user input using cin and store it in another variable.

Below is the implementation:

#include <iostream>
using namespace std;

int main()
{

    // Give the number of rows as user input using
    // cin and store it in a variable.
    int numberOfRows;
    cin >> numberOfRows;
    // Create a character variable.
    char characte;
    // Give the character as user input using cin and store
    // it in another variable.
    cout << "Enter some random character to print = "
         << endl;
    cin >> characte;
    cout << endl;
    int g = (2 * numberOfRows) - 2;
    // Loop from 0 to the number of rows using For loop.
    for (int m = 0; m < numberOfRows; m++) {
        // Loop from 0 to g using another For Loop(Inner For
        // loop).
        for (int n = 0; n < g; n++) {
            // Print the space character in the inner For
            // Loop.
            cout << " ";
        }
        // Decrement the value of g by 1 after the end of
        // the inner For loop.
        g = g - 1;
        // Loop from 0 to m+1 using another For loop(Nested
        // For loop) where m is the iterator value of the
        // parent For loop.
        for (int n = 0; n < m + 1; n++) {
            // Print the given character with space.
            cout << characte << " ";
        }
        // Print the Newline character after the end of the
        // Two inner For loops.
        cout << endl;
    }
    return 0;
}

Output

10
Enter some random character to print = $
                  $ 
                 $ $ 
                $ $ $ 
               $ $ $ $ 
              $ $ $ $ $ 
             $ $ $ $ $ $ 
            $ $ $ $ $ $ $ 
           $ $ $ $ $ $ $ $ 
          $ $ $ $ $ $ $ $ $ 
         $ $ $ $ $ $ $ $ $ $

3) C Implementation

  • Give the number of rows as user input using scanf and store it in a variable.
  • Give the Character as user input using scanf and store it in another variable.

Below is the implementation:

#include <stdio.h>

int main()
{

    // Give the number of rows as user input using scanf and
    // store it in a variable.
    int numberOfRows;
    scanf("%d", &numberOfRows);
    // Create a character variable.
    // Give the character as user input using scanf and
    // store it in another variable.
    char characte;
    scanf("%c", &characte);
    printf("\n");
    // Take a variable to say g and initialize its value
    // with (2*number of rows)-2.
    int g = (2 * numberOfRows) - 2;
    // Loop from 0 to the number of rows using For loop.
    for (int m = 0; m < numberOfRows; m++) {
        // Loop from 0 to g using another For Loop(Inner For
        // loop).
        for (int n = 0; n < g; n++) {
            // Print the space character in the inner For
            // Loop.
            printf(" ");
        }
        // Decrement the value of g by 1 after the end of
        // the inner For loop.
        g = g - 1;
        // Loop from 0 to m+1 using another For loop(Nested
        // For loop) where m is the iterator value of the
        // parent For loop.
        for (int n = 0; n < m + 1; n++) {
            // Print the given character with space.
            printf("%c ",characte);
        }
        // Print the Newline character after the end of the
        // Two inner For loops.
        printf("\n");
    }
    return 0;
}

Output

10$
                  $ 
                 $ $ 
                $ $ $ 
               $ $ $ $ 
              $ $ $ $ $ 
             $ $ $ $ $ $ 
            $ $ $ $ $ $ $ 
           $ $ $ $ $ $ $ $ 
          $ $ $ $ $ $ $ $ $ 
         $ $ $ $ $ $ $ $ $ $

Related Programs:

C++ start thread – C++11 : Start thread by member function with arguments

C++ start thread: In the previous article, we have discussed about C++ : How to copy / clone a STL List or Sub List. Let us learn how to Start thread by member function with arguments in C++ Program.

Starting thread by member function with arguments

C++11 thread: We are going to see how to start threads by member function with arguments .

Starting thread with non static member function :

C++ thread class: We will be using the following class to demonstrate .

class Example
{
public:
    void exec(std::string command);
};

Class Example contains a non static member function Exec( ) .

We will now have to create an object of the class to call the function so that we can start it as thread function.

Now, to create the thread to run the function.

Example *ExamplePtr = new Example();
std::thread th(&Example::exec, ExamplePtr, "Example");

Here we have passed three arguments,

  1. &Example::exec – A pointer pointing to the member function. This will be used as the thread function.
  2.  ExamplePtr – This is a pointer pointing to the object of the class with which the above function is to be called. Every non -static member function’s first argument is the pointer to its class. Hence this will be passed as the first argument into the function by the thread class.
  3. “Example” – This is the string value. It is passed as second argument to the member function.

CODE:-

#include <iostream>
#include <thread>

class Example
{
public:
    void exec(std::string command)
    {
        for (int i = 0; i < 5; i++)
        {
            std::cout << command << " :: " << i << std::endl;
        }
    }
};
int main()
{
    //Creatig object
    Example *ExamplePtr = new Example();

    //Creatig thread
    std::thread th(&Example::exec, ExamplePtr, "Example");
    th.join();

    delete ExamplePtr;
    return 0;
}
Output :
Example :: 0
Example :: 1
Example :: 2
Example :: 3
Example :: 4

Starting thread with static member function :

We can call static member functions directly without requiring an object.

CODE:-

#include <iostream>
#include <thread>

class Example
{
public:
    static void exec(std::string command)
    {
        for (int i = 0; i < 5; i++)
        {
            std::cout << command << " :: " << i << std::endl;
        }
    }
};
int main()
{
    //Creatig thread
    std::thread th(&Example::exec, "Example");
    th.join();

    return 0;
}
Output :
Example :: 0
Example :: 1
Example :: 2
Example :: 3
Example :: 4

Answer these:

  1. C thread member function with arguments?
  2. C thread function with arguments?
  3. C thread as class member?
  4. C thread member function with arguments?
  5. C++ thread function with arguments?
  6. C++ thread as class member?
  7. Call function in another thread c++?
  8. C++ thread access member variable?
  9. C thread non static member function?

C++ list get element – C++ List – Find | Contains : How to Search an Element in std::list ?

C++ list get element: In the prior tutorials, we have discussed Different Ways to iterate over a List of objects in C++. Now, we have come up with a new tutorial on C++ concept ie., how to Search an Element in std::list in C++ Program.

std::find in C++

C++ std list example: C++ std::find function obtains the element in the given range of numbers. Also, it returns an iterator to the first element in the range [first,last) that compares equal to val. If no such element is found, the function returns last.

Template of the Function

InputIterator find (InputIterator first, InputIterator last, const T& val)

first,last:
Input iterators to the initial and final positions in a sequence. The range
searched is [first,last), which contains all the elements between first and
last, including the element pointed by first but not the element pointed by last.

val:
Value to be search in the range

Return Value:
An iterator to the first element in the range that compares equal to val.
If no elements match, the function returns last.

Examples:

Input : 10 20 30 40
Output : Element 30 found at position : 2 (counting from zero)  

Input : 8 5 9 2 7 1 3 10
Output : Element 4 not found.
// CPP program to illustrate 
// std::find
// CPP program to illustrate 
// std::find
#include<bits/stdc++.h>
  
int main ()
{
    std::vector<int> vec { 10, 20, 30, 40 };
      
    // Iterator used to store the position 
    // of searched element
    std::vector<int>::iterator it;
      
    // Print Original Vector
    std::cout << "Original vector :";
    for (int i=0; i<vec.size(); i++)
        std::cout << " " << vec[i];
          
    std::cout << "\n";
      
    // Element to be searched
    int ser = 30;
      
    // std::find function call
    it = std::find (vec.begin(), vec.end(), ser);
    if (it != vec.end())
    {
        std::cout << "Element " << ser <<" found at position : " ;
        std::cout << it - vec.begin() << " (counting from zero) \n" ;
    }
    else
        std::cout << "Element not found.\n\n";
          
    return 0;
}

Output: 

Original vector : 10 20 30 40
Element 30 found at position : 2 (counting from zero)

Find and  Contains: How to Search an Element in std::list?

Std find c++: In this article we are going to see multiple ways we can search an element inside a list.

As there are no methods available in the std::list to find an element we are going to manually iterate over the array and check if any of the elements matches ours.

By using std::find() to search an element in std::list :

std::find c++: The standard library has an algorithm find( )function.

Syntax:

<class InputIterator, class T>

InputIterator find (InputIterator first, InputIterator last, const T& val);

C++ std list: In the find( ) function, we can pass two iterators and a value with them. The function will check all the elements given between them and compare it with the value we have provided.

If a match is found it returns the iterator or else it would return the iterator pointing to the list end.

Program to search an element in std list using std find()

Let’s see the below program to understand the use of find()function.

#include <iostream>
#include <list>
#include <string>
#include <algorithm>
int main()
{
    std::list<std::string> stringList = {
        "I", "am",
        "the", "yes",
        "hey", "from"};

    // Create a Iterator for the list
    std::list<std::string>::iterator it;
    //Check for 'hey' inside the list
    it = std::find(stringList.begin(), stringList.end(), "hey");
    //Check if the iterator points to the end of the list
    if (it != stringList.end())
    {
        //If it does not point to end then the element exists
        std::cout << "'hey' exists in list " << std::endl;
    }
    else
    {
        //If it points to end, then the element does not exist
        std::cout << "'hey' not there" << std::endl;
    }
}
Output :
'hey' exists in list

By using generic contains() method for std::list :

C++ std find: Let’s create a generic contains() method to search for a given value.

Let’s see the below program to understand it clearly.

#include <iostream>
#include <list>
#include <string>
#include <algorithm>
/*
 *Creating a generic function to find an element inside the list
 */
template <typename T>
bool contains(std::list<T> &listOfElements, const T &element)
{
    // Find the iterator of element exists inside the list
    auto it = std::find(listOfElements.begin(), listOfElements.end(), element);
    //if iterator points to end return false
    return it != listOfElements.end();
}
int main()
{
    std::list<std::string> stringList =
        {"I", "am", "the", "yes", "hey", "from"};
    // Check for the element inside list
    bool res = contains(stringList, std::string("is"));
    std::cout << res << std::endl;
    res = contains(stringList, std::string("yes"));
    std::cout << res << std::endl;

    // List of ints
    std::list<int> numList =
        {10, 6, 89, 32, 3, 25};
    // Check if the number exists in list
    res = contains(numList, 3);
    std::cout << res << std::endl;
    res = contains(numList, 25);
    std::cout << res << std::endl;
}

Output :

0
1
1
1

Also Read: How to Access Element by Index in a Set

Python pythagorean triples – Program to Determine all Pythagorean Triplets in the Range in C++ and Python

Program to Determine all Pythagorean Triplets in the Range in C++ and Python

Python pythagorean triples: In the previous article, we have discussed about Program to Print Collatz Conjecture for a Given Number in C++ and Python. Let us learn Program to Determine all Pythagorean Triplets in C++ Program.

A Pythagorean triplet is a collection of three positive numbers, a, b, and c, such that a^2 + b^2 = c^2. Some things you have to notice while reading.

  • Program to check pythagorean triples in c
  • Pythagorean triples list
  • Pythagorean triples program in java
  • Pythagorean triples in python assignment expert
  • Pythagorean triples leetcode
  • Pythagorean triples hackerrank solution

Given a limit, find all Pythagorean Triples with values less than that limit.

Examples:

Example1:

Input:

given upper limit =63

Output:

printing the Pythagorean triplets till the upper limit 63 :
3 4 5
8 6 10
5 12 13
15 8 17
12 16 20
7 24 25
24 10 26
21 20 29
16 30 34
9 40 41
35 12 37
32 24 40
27 36 45
20 48 52
11 60 61

Example2:

Input:

given upper limit =175

Output:

printing the Pythagorean triplets till the upper limit 175 :
3 4 5
8 6 10
5 12 13
15 8 17
12 16 20
7 24 25
24 10 26
21 20 29
16 30 34
9 40 41
35 12 37
32 24 40
27 36 45
20 48 52
11 60 61
48 14 50
45 28 53
40 42 58
33 56 65
24 70 74
13 84 85
63 16 65
60 32 68
55 48 73
48 64 80
39 80 89
28 96 100
15 112 113
80 18 82
77 36 85
72 54 90
65 72 97
56 90 106
45 108 117
32 126 130
17 144 145
99 20 101
96 40 104
91 60 109
84 80 116
75 100 125
64 120 136
51 140 149
36 160 164

Find all Pythagorean triplets in the given range in C++ and Python

Pythagorean triples c program: A simple solution is to use three nested loops to generate these triplets that are less than the provided limit. Check if the Pythagorean condition is true for each triplet; if so, print the triplet. This solution has a time complexity of O(limit3), where ‘limit’ is the stated limit.

An Efficient Solution will print all triplets in O(k) time, where k is the number of triplets to be printed. The solution is to apply the Pythagorean triplet’s square sum connection, i.e., addition of squares a and b equals square of c, and then represent these numbers in terms of m and n.

For every choice of positive integer m and n, the formula of Euclid creates Pythagorean Triplets:

a=m^2 -n^2

b= 2 * m * n

c= m ^2 +n^2

Below is the implementation of efficient solution in C++ and Python:

Drive into Python Programming Examples and explore more instances related to python concepts so that you can become proficient in generating programs in Python Programming Language.

1)Finding all Pythagorean till the given limit in Python

Approach:

  • Scan the upper limit or give static input and save the variable.
  • Calculate the Pythagorean triplets using the formula with a while loop and for loop.
  • If the c value exceeds the upper limit, or if a number equals 0, break from the loop.
  • Print down all Pythagorean triplets’ three numbers.
  • Exit of program.

Below is the implementation:

# enter the upper limit till you find pythagorean triplets
upper_limit = 63
n3 = 0
a = 2
print("printing the pythagorean triplets till the upper limit", upper_limit, ":")
while(n3 < upper_limit):
    for b in range(1, a+1):
        n1 = a*a-b*b
        n2 = 2*a*b
        n3 = a*a+b*b
        if(n3 > upper_limit):
            break
        if(n1 == 0 or n2 == 0 or n3 == 0):
            break
        print(n1, n2, n3)
    a = a+1

Output:

printing the Pythagorean triplets till the upper limit 63 :
3 4 5
8 6 10
5 12 13
15 8 17
12 16 20
7 24 25
24 10 26
21 20 29
16 30 34
9 40 41
35 12 37
32 24 40
27 36 45
20 48 52
11 60 61

Explanation:

The upper limit / input should be entered by a user as static, and stored in a variable.
The value of Pythagorean triplets using the formula is used during and for loops.
The loop breaks out if the value of a side is greater than the upper boundary, or if one side is 0.
The triplets will then be printed.

2)Finding all Pythagorean till the given limit in C++

Approach:

  • Scan the upper limit using cin or give static input and save the variable.
  • Calculate the Pythagorean triplets using the formula with a while loop and for loop.
  • If the c value exceeds the upper limit, or if a number equals 0, break from the loop.
  • Print down all Pythagorean triplets’ three numbers.
  • Exit of program.

Below is the implementation:

#include <bits/stdc++.h>
using namespace std;
int main()
{

    // enter the upper limit till you find pythagorean
    // triplets
    int upper_limit = 175;
    int n3 = 0;
    int a = 2;
    cout << "printing the pythagorean triplets till the "
            "upper limit"
         << upper_limit << ":" << endl;
    while (n3 < upper_limit) {
        for (int b = 1; b <= a; b++) {
            int n1 = a * a - b * b;
            int n2 = 2 * a * b;
            n3 = a * a + b * b;
            if (n3 > upper_limit)
                break;
            if (n1 == 0 or n2 == 0 or n3 == 0)
                break;
            cout << n1 << " " << n2 << " " << n3 << endl;
        }
        a = a + 1;
    }
    return 0;
}

Output:

printing the Pythagorean triplets till the upper limit175:
3 4 5
8 6 10
5 12 13
15 8 17
12 16 20
7 24 25
24 10 26
21 20 29
16 30 34
9 40 41
35 12 37
32 24 40
27 36 45
20 48 52
11 60 61
48 14 50
45 28 53
40 42 58
33 56 65
24 70 74
13 84 85
63 16 65
60 32 68
55 48 73
48 64 80
39 80 89
28 96 100
15 112 113
80 18 82
77 36 85
72 54 90
65 72 97
56 90 106
45 108 117
32 126 130
17 144 145
99 20 101
96 40 104
91 60 109
84 80 116
75 100 125
64 120 136
51 140 149
36 160 164

Answer yourself:

  1. Write a program to print all pythagorean triplets between 1 to 100?
  2. Find all pythagorean triples below the given limit?
  3. Program to determine all pythagorean triplets in the range in c++ and python?

Related Programs:

C++ grading program example – C++ Program to Calculate Grade of Student Using Switch Case

C++ Program to Calculate Grade of Student Using Switch Case

C++ grading program example: In the previous article, we have discussed C++ Program to Find Power of Number using Recursion. In this article, we will see C++ Program to Calculate Grade of Student Using Switch Case. And see Grading System Using Switch Case In C, C Program For Grades Of Student Using Switch, Grading System In C Programming Using Switch, Grading System Using Switch In C++, Grade Program In C Using Switch, Grade System Using Switch Case, Grade Program In C++ Using Switch, Grade Of Student Using Switch In C, Grade Switch Statement C++, Grade Calculator C++, Grade Program In Java Using Switch Case.

C++ Program to Calculate Grade of Student Using Switch Case

C++ grade calculator: In this C++ program, we will calculate the grade of a student based on the total marks obtained by the student in five subjects. Here we will use a switch case statement, however you can write same program using if-else ladder statement also. Here is the range of Grades:
Marks >= 90 : Grade A
Marks >= 70 && < 90 : Grade B
Marks >= 50 && < 70 : Grade C
Marks < 50 : Grade D

We will first ask user to enter the marks of five subjects and calculate the total marks obtained by student. Then we will calculate the average marks by dividing total marks by 5. Now, we will use switch case statement to select the appropriate range for his average marks and print the grade accordingly.

C++ Program to Calculate Grade of Student Using Switch Statement

C++ Program to Calculate Grade of Student Using Switch Statement

// C++ Program to calculate grade of student 
#include <iostream>
using namespace std;
 
int main() {
    int score, i, average;
    float total=0;
  
    cout<< "Enter marks of 5 subjects\n";
  
    for(i=0; i<5; i++) {
 cin >> score;
 total += score;
    }
  
    average = total/5;
  
    cout<<"Grade : ";
    switch(average/10) {
       case 9 :
           cout << "A";
           break;
       case 8 :
       case 7 :
           cout << "B";
           break;
       case 6 :
       case 5 :
           cout << "C";
           break;
       default :
           cout << "D";  
    }
  
    return 0;
}

Output

Enter marks of 5 subjects
97 89 78 87 68
Grade : B

Are you fed up with browsing all concepts related to C++ Programming Programs? Not anymore because all the basic and complex Programs for C++ are covered on our main page just tap on the link available here & save your time to practice more.

Read more: C++ Program to Find Largest Element of an Array

Test yourself:

  1. Find Grade Using Switch Case In C++
  2. Write A C++ Program To Display Grade Of A Student Using Switch Statement
  3. Write A Program To Find Grade Of A Student Given His Marks Using Switch
  4. Write A C Program To Display Grade Of A Student Using Switch Statement
  5. C Program To Find Grade Of A Student Using Switch
  6. C Program To Print Grade Of Student Using Switch Statement
  7. C Program To Find Grade Of A Student Using Switch Case
  8. Java Program To Find Grade Of A Student Using Switch Case
  9. Write A Program To Find The Grade Of Student Using Switch Case
  10. Find Grade Using Switch Case In Java

Related Posts On:

C++ Program to Store Information of an Employee in Structure

C++ Program to Store Information of an Employee in Structure

In the previous article, we have discussed C++ Program to Add Two Distances in Inch and Feet Using Structures. In this article, we will see C++ Program to Store Information of an Employee in Structure. Along with that, C++ Program For Employee Details Using Structure, Structure Of C++ Program, Endl In C++, Employee Structure In C, Employee Details Using Structure In C, Name This Structure, C++ Employee Program, C++ Program For Employee Details, Employee Program In C++, Basic C++ Structure, Char Name C++, Structure Of Program In C++, Structure For Employee In C, Employee Details In C++, Geeks For Geeks C++ etc.. are discussed below not particularly.

C++ Program to Store Information of an Employee in Structure

  • Write a C++ program to store data of an Employee in a structure variable.

In this C++ program, we will store the information of an Employee in a structure variable and then display it in screen. We want to store following information for an employee Name, Salary, Employee Code and Department. Here is a sample employee record :

Name : Jason Donald
Salary : 53463
Employee Code : 1234
Department : CSE

To store the information of employee, we will define an Employee structure containing all required information of employee.

struct Employee {
    char name[50];
    int salary;
    int employeeCode;
    char dept[5];
};

Then we will create a variable of Employee structure, let’s say emp. Then to access the members of emp, we will use member access operator or dot(.) operator.

C++ Program to Store Information of an Employee in a Structure

C++ Program to Store Information of an Employee in a Structure

// C++ program to store data of an employee in a structure variable
#include <iostream>
using namespace std;
 
struct Employee {
    char name[50];
    int salary;
    int employeeCode;
    char dept[5];
};
 
int main() {
    Employee e;
     
    cout << "Enter name of employee : ";
    cin.getline(e.name, 50);
    cout << "Enter department : ";
    cin.getline(e.dept, 5);
    cout << "Enter salary of employee : ";
    cin >> e.salary;
    cout << "Enter employee code : ";
    cin >> e.employeeCode;
     
    // Printing employee details 
    cout << "\n*** Employee Details ***" << endl;
    cout << "Name : " << e.name << endl << "Salary : " << e.salary << endl;
    cout << "Employee Code : " << e.employeeCode << endl << "Department : " << e.dept;
    return 0;
}

Output

Enter name of employee : Jason Donald
Enter department : CSE
Enter salary of employee : 53463
Enter employee code : 1234

*** Employee Details ***
Name : Jason Donald
Salary : 53463
Employee Code : 1234
Department : CSE

In above program, we first declare a variable of type Employee as

Employee e;

Then we ask user to enter details of employee i.e Name, department, salary and department and store it in corresponding fields of structure variable e.Finally we print the information of variable e on screen using court.

Points to remember about Structures in C++

  • Structure in C++ programming language is a user defined data type that groups logically related information of different data types into a single unit.
  • Keyword struct is used to declare a structure.
  • We can declare any number of member variables inside a structure.
  • We can access the member of structure either using dot operator(.) or arrow operator(->) in case of structure pointer.

Print Hello World, Multiply two Numbers, Add Two Numbers, etc. are some of the basic-level Programs in C++. Want to practice advanced C++ Programs? Go with the available links & gain more coding knowledge.

Evaluate Yourself:

  1. Write The Structure Of C++ Program
  2. Create A Structure To Store Employee Details
  3. C Program For Employee Details Using Structure And Functions
  4. C Program For Employee Details Using Union
  5. C++ Program For Employee Details Using Functions
  6. Simple C Program For Employee Details Using Structure
  7. Struct Pioint Geek
  8. Structure Program In C For Employee

Related Posts On:

C++ set find – How to Access Element by Index in a Set | C++

How to Access Element by Index in a Set

Set: How to access set elements in c++ or access set elements c++.

C++ set find: A Set is used in programming to store unique values of a list while also automatically providing an ordering to its elements. The ordering is set to ascending by default.

The insert() method is used to insert the elements. If the same value is inserted more than once, the set automatically deletes the duplicates and stores only one copy of that variable.

The erase() method is used to remove the Set’s components.

Examples:

Input:

set ={ "hello", "this", "is" , "BTechGeeks" , "platform"} index =2

Output:

2rd Element in set = this

Accessing elements by index in a Set

C++ set find: std::set is an associative container that stores elements in a balanced binary search tree internally and does not support the random access operator [].

As a result, getting a random element from a set by index (C++ Set Get Element By Index) is a little tricky.

The elements of the set will be stored in sorted order.

There are several ways to access elements by index in a set some of them are:

Method #1:Using iterator and generic approach

Set find c++: To access an element at the nth index, we must first construct an iterator pointing to the starting position and continue to increment the iterator until the nth element is reached.

Below is the implementation:

#include <bits/stdc++.h>
using namespace std;
int main()
{
    // creating a string set and initializing with some
    // strings
    set<string> stringset = { "Hello", "this", "Hello",
                              "this", "BTechGeeks" };
    // given index
    int index = 2;
    set<string>::iterator setItr = stringset.begin();
    for (int i = 0; i < index; i++)
        setItr++;
    cout << index << "rd Element in set = " << *setItr
         << endl;
}

Output:

2rd Element in set = this

Method #2:Using std::advance

Find in set c++: std::advance takes an iterator and a value to advance the specified iterator. Let’s look at how to use std::advance to access an index feature.

Below is the implementation:

#include <bits/stdc++.h>
using namespace std;
int main()
{
    // creating a string set and initializing with some
    // strings
    set<string> stringset = { "Hello", "this", "Hello",
                       h3       "this", "BTechGeeks" };
    // given index
    int index = 2;
    set<string>::iterator setItr = stringset.begin();
    // It will advance the passed iterator by the index
    // value.
    advance(setItr, index);
    cout << index << "rd Element in set = " << *setItr
         << endl;
}

Output:

2rd Element in set = this

Method #3:Using std::next

Set string c++: It was implemented in C++11, and unlike std::advance, it does not increment the given iterator, but rather returns a new iterator that is n positions advanced to the given iterator.
Let’s look at how to use std::next to get to the index element.
Below is the implementation:

#include <bits/stdc++.h>
using namespace std;
int main()
{
    // creating a string set and initializing with some
    // strings
    set<string> stringset = { "Hello", "this", "Hello",
                              "this", "BTechGeeks" };
    // given index
    int index = 2;

    // Internally, std::next iterates over n elements to
    // reach the nth element and
    // returns the iterator of the set's index element.
    set<string>::iterator setItr
        = next(stringset.begin(), index);
    cout << index << "rd Element in set = " << *setItr
         << endl;
}

Output:

2rd Element in set = this

Recommended Reading On: Different ways to Erase / Delete an element from a Set in C++

Try these: 

  1. How To Access Elements In Set C++
  2. How To Access Elements Of Set
  3. How To Access An Element In A Set C++
  4. How To Access The Elements Of A Set In C++
  5. How To Access A Element In Set.
  6. Accessing Set Elements In C++
  7. Get Nth Element Of Set C++
  8. Access Nth Element In Set C++

Related Programs:

C++ reverse number – C++ Program to Reverse a Number

C++ Program to Reverse a Number

C++ reverse number: In the previous article, we have discussed about C++ Program to Calculate Power of a Number. Let us learn how to Reverse a Number in C++ Program.

Methods to Reverse a Number in C++

How to reverse a number c++: In this article, we will see different methods of how we can reverse a number in c++. Let see all the methods one by one.

Method1-Using while loop

get4321.com: In this method, we extract the digit of a number a through this we will make a new number which is the reverse of the given number. Let’s write the code to understand this.

#include <iostream>
using namespace std;

int main() {
    int n, reversedNumber = 0, remainder;
    n=1234;
    while(n != 0) {
        remainder = n%10;
        reversedNumber = reversedNumber*10 + remainder;
        n /= 10;
    }
    cout << "Reversed Number = " << reversedNumber;

    return 0;
}

Output

Reversed Number = 4321

Now lets see how this work. Suppose our number is 1234.

Iteration1- remainder-4  reversedNumber=(0*10)+4=4    number=1234/10=123

Iteration2- remainder-3  reversedNumber=(4*10)+3=43    number=123/10=12

iteration3- remainder-2   reversedNumber=(43*10)+2=432   number=12/10=1

iteration4- remainder-1    reversedNumber=(432*10)+1=4321   number=1/10=0

As the number become 0 so we come out of the loop and we get 4321 as our reversed number.

Method 2-By converting number to string

In this method first, we convert our number to a string. For this we use inbuilt method in c++ to_string().Then we reverse the string using the reverse() method in c++. And then we convert that reverse string again to a number using stoi() method. Let write the code for this.

#include <bits/stdc++.h>
using namespace std;

int main() {
    int n, reversedNumber = 0, remainder;
    n=1234;
    string s=to_string(n);
    reverse(s.begin(),s.end());
    n=stoi(s);
    cout << "Reversed Number = " << n;
    return 0;
}

Output

Reversed Number = 4321

So these are the methods to reverse a number in c++.