ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

Learning C++: How to Program Conceptually

Updated on September 9, 2015
Working in CodeBlocks for developing programs written in C++
Working in CodeBlocks for developing programs written in C++ | Source

This article is intended for readers who have some knowledge with C language or even C++. We will focus on some examples in order to understand programming better and also utilize the concept of object-oriented programming.

C++ is an object-oriented programming language developed by Bjarne Stroustrup. C++ is a superset of C. In simpler terms, C++ is an ‘extended version’ of C language. C does not support class or templates. Because of the introduction of ‘class’ in C++, it is also known as ‘C with classes’. The etymology of C++ (pronounced as C plus plus) is based on the increment operator (++) which increases the value of a variable by 1. Since C++ is a successor of C language with different new features and functionalities, it’s logical to call it C++.

Enough with the introduction; let’s begin programming. First, we will write a program which converts a decimal number into its fractional form. We will call it DecimalToFraction.


User enters 2.5 as the decimal number

The fractional form for this number is 5/2

User enters 34.46 as the decimal number

The fractional form for this number is 1723/50

This program is meant to develop our programming skills. It involves the use of a class, and the mathematical concept of HCF (Highest Common Factor). For any given two or more integers, HCF is the largest positive number which divides all of the numbers without leaving any remainder.


#include <iostream>

using namespace std;

 class FractionIt
    int numerator, denominator;
    double number;

     FractionIt(double n)

    void setNumAndDen()
        double divisor=1,multi;

        } while (!isDivisible(multi));



    bool isDivisible(double,double val=1); //declaration of method Divisible

    void toFraction()
        int MaximumDivisor=denominator;
        int num=numerator,den=denominator;
        for(int i=2;i<=MaximumDivisor;i++)
            if(isDivisible(numerator,i) && isDivisible(denominator,i))
        cout<<"The fractional form is "<<num<<"/"<<den;

bool FractionIt::isDivisible(double num,double div) //definition of method Divisible
        int absvalue;
        double extvalue;
        if(absvalue==extvalue) return true;
        else return false;
int main()
    double inputNumber;
    cout<<"Enter the number: ";

    FractionIt oNumber(inputNumber);


Now let’s discuss the parts of the program one by one.

Class FractionIt

This class is the heart of our program. A class in programming refers to a collection of functions (called methods) and variables which can be assigned to an entity (called object). Call them member methods and member variables. We assumed the readers to have brief knowledge of C/C++ programming, but let us warm up.

A little warm-up

Say, there is a pizza cafe with 10 customers. Everyone has the menu list at their tables. The menu says “Pizzas” and a list of pizzas available is provided. Some select the first item, some the last while some select multiple items. Now, the menu is a class, and the items are the member methods. The customers are objects who called for different items (methods). The behavior of the menu never changes, it remains the same. But, the customers can use it to get different results, although all of them have come to eat pizza.

Let’s convert the above example into code:


#include <iostream>

using namespace std;
class Pizzas

int cheesePizza, thinCrustPizza,specialPizza, coupon;

    int getCheesePizza()

        return cheesePizza;

    int getThinCrustPizza()
        return thinCrustPizza;

    int getSpecialPizza()
        return specialPizza;

    void setCoupon(int codeNumber)


int main()
    Pizzas customer1;
    cout<<"Customer 1: "<<endl;

    Pizzas customer2;
    cout<<"Customer 2:";

    Pizzas customer3;
    cout<<"Customer 3:";

Output of pizzas.cpp
Output of pizzas.cpp

Three objects of Pizza class have been declared. Each object calls a different method. Thus, each object performs some different activity from the same common class. Since our customer3 ordered for 2 pizzas, he got a coupon with a code in it. Then, he gave the code to the cashier who will check for any special prizes the café has to offer. This was done by the setCoupon () method. Also, note that the methods are called by adding a dot operator and the method name at the end of the object.

Let’s get back to our FractionIt class. It has three member variables: numerator (int), denominator (int) and number (double). The variable ‘number’ stores the number entered by the user. The class has one parameterized constructor which assigns the input number to the member variable ‘number’.

As I mentioned earlier, the heart of our program is this class. Well, this heart has 3 chambers:

- setNumAndDen (void)

- isDivisible (bool)

- toFraction (void)

isDivisible(bool) method

Let’s start with the isDivisible method. This method checks whether any given two numbers can be divided by a specific number or not. By ‘divided’, you have to understand it the number divides any other number without leaving any remainder. For example, consider two numbers 12 and 28. Other than 1, there are only two numbers in this entire universe that can divide 12 and 28 without leaving any remainder. They are 2 and 4. I know you started thinking of other numbers that may divide 12 and 28, but trust me on this one and let’s continue further. So, if you passed 12 and 28 as the two arguments to isDivisible, it would return true. We will soon come to know how isDivisble is connected to both setNumAndDen and toFraction methods.

setNumAndDen() method

You will need to pay a little more attention, now that the hero chamber of our class, setNumAndDen will be introduced. The sole purpose of setNumAndDen is to convert the given number into fractional form where the denominator is always a multiple of 10. For example, 4.32 can be written as 432/100 and 3.1 can be written has 31/10. What our little hero does is check if the number is finally divisible or not. If it is not, then it multiplies the number by 10 and reiterates the whole process. Let’s show this with an algorithm.

Step 1: Assign 1 to a variable.

Step 2: Multiply it by 10 and then multiply the given number with the variable.

Step 3: Is the given number now a non-decimal number? If yes, then go to step 4, else go to Step 2.

Step 4: That’s it. No more steps.

As you noticed, setNumAndDen method uses isDivisible too. However, it uses it in a different way. Notice that isDivisible’s second parameter has a default value i.e. 1 for the denominator. Even if only one argument is passed to this method, the compiler will not show an error because this is completely valid in C++ (Note: this is not valid in Java). So, how does isDivisible check whether the number is non-decimal or not when the second parameter is 1? The variables ‘absvalue’ and ‘extvalue’ in indivisible are of int and double types respectively. One limitation of int type is that variables of this type cannot store decimal numbers whereas a double type allows this. Also, C++ allows comparison of these types. Say, if the number passed to isDivisible as the first parameter is 4.2. An int variable would store 4 if 4.2 was assigned to it because it doesn’t store decimal numbers. But, if 4.2 was assigned to a double variable, then it would store 4.2 without altering the value. Now let’s pass 42 as the first parameter. Both the variables are going to store 42 without any alterations. This means, the number is indeed divisible by some integer other than 1.

When a number is found which is divisible, the loop breaks. The loop gives us two new numbers: The denominator and the numerator which when evaluated will give us the decimal number that was entered by the user. These are divisor and multi variables, respectively. We then assign these two variables to the member variables (denominator and numerator) of the object oNumber belonging to FractionIt class.

A sample output of DecimalToFraction
A sample output of DecimalToFraction

toFraction() method

We now have a fraction representation of the given number, but still, it could be simplified. 25/10 can be simplified to 5/2. This is what our final method, toFraction, will be doing.

The algorithm of toFraction is quite simple. A loop checks whether the denominator and numerator can be divided by some other number. It keeps checking for the number which may range from 2 to the value of denominator. For example, if the numerator and denominator are 10 and 4 respectively, then the maximum value of that particular number is 4 and the minimum is 2.

First, the numbers are divided by 2 and the result is a success; both the numbers are divisible. What if there are other larger numbers that can divide these two numbers? The loop continues and divides the numbers by 3. Oops! It continues to 4. The denominator is divisible by itself, but 10 isn’t. So, our magic number is 2. Finally, the result is 5/2.This way, our program is completed.

The program is simple enough, but usually, simple is hard to obtain. This program could be written without the use of classes, but to clarify the concept of OOP (Object Oriented Programming), I made use of them.

The technique isn’t about learning some language from top to bottom; it’s about understanding the application of the language. We used common features of C++ to write the above program. So, even if you are just beginning with C++ programming or any kind of programming, always know that simple concepts can be formulated from simple knowledge. Have fun programming!


    0 of 8192 characters used
    Post Comment

    No comments yet.


    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at:

    Show Details
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the or domains, for performance and efficiency reasons. (Privacy Policy)
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)