 # C++ Programming Code Examples

## C++ > Mathematics Code Examples

### Program to print first 100 Ramanujan Numbers by two ways

/* Program to print first 100 Ramanujan Numbers by two ways */ /* Description: Programme to Print first 100 Ramanujan Numbers by TWO WAYS 1st way is printing Ramunajan Numbers from RN taking RN from 0 to INFINITY and print first 100 numbers. 2nd way is to clacualte RN numbers from L M N P of formula RN= L^3 + M^3 = N^3 + P^3 and sort the RN numbers and print first 100 Numbers RN=RAMANUJAN NUMBERS */ #include<iostream.h> //Include Header Files #include<math.h> using namespace std; template <class X>X cube(X a)//TEMPLATE to calculate CUBE of a number and { //Return the CUBE return (a*a*a);//Return CUBE } class Ramanujan{//CLASS to PRINT RN in two ways public: void fromRN();//PRINT RN from RN void fromLMNP();//PRINT RN from LMNP values }; void Ramanujan::fromLMNP()//Start of LMNP { int L=0,M=0,N=0,P=0;//integer L,M,N,P to calculate RN int a;//ARRAY to store RN calculated from L,M,N,P int temp;//Integer to SWAP for sorting. int i=0,j=0;//Integer's for sorting ARRAY int CAL;//Integer to store how many values calculated for RN cout<<" Calculating RN numbers from LMNP values Please Wait......... "; for(L=0;L<128;L++)//L for(M=0;M<170;M++)//M for(N=0;N<170;N++)//N for(P=0;P<205;P++)//P {if(L<M && M<N && N<P)//if the Condition Satisfy { //FINDING the PAIRS MATCHING RN numbers if((cube(L)+cube(M))==(cube(N)+cube(P))) { a[i]=cube(L)+cube(M);i++;} else if((cube(L)+cube(N))==(cube(M)+cube(P))) {a[i]=cube(L)+cube(N);i++;} else if((cube(L)+cube(P))==(cube(N)+cube(M))) {a[i]=cube(N)+cube(M);i++;} }//END of IF }//END of FOR LOOP CAL=i;//CAL stores how many values calculated for RN i=0; cout<<" SORTING Please Wait......... "; for (i=0; i<CAL-1; i++) //For LOOP TO SORT THE ARRAY { for (j=0; j<CAL-1-i; j++) if (a[j+1] < a[j]) { // compare the two values temp = a[j]; //swap a[j] and a[j+1] a[j] = a[j+1]; a[j+1] = temp; } } i=0;//i=0 cout<<" Ramanujan Numbers are.........."; //TO print 100 RN numbers do { cout<<" "<<(i+1)<<" : "<<a[i]; i++; }while(i<100);//condition for i }//END of the MEMEBER fromLNMP void Ramanujan::fromRN()//Start of RN { double k,l,mk,care=0,kmk=0; int ri=0;//RN Nunber int h,mc,m,Lo;//h is HIGEST (ie L) //mc is to calculate MINIMUM(i.e M) //MINIMUM (i.e M) int i,j,flag=1;//FLAG to track the NUMBER of RN NUMBERS l=(1.00/3.00);//for CUBE ROOT cout<<"SLno L M N P =RN "; for(ri=0;flag<=100;ri++)//FOR loop taking RN from 0 { care=0;//FLAG to track number of times M occured kmk=0;//FLAG to track number of NP occurance k=(pow(ri,l)); for(;k>0&&care==0;k--){//LOOP to find M value h=(int)k; mc=((int)(ri-cube(h))); mk=(pow(mc,l)); m=(int)mk; if(m<mk) m=m+1; else m=(int)mk; if(cube(m)+cube(h)==ri) { care++;//to break the LOOP to find M value }//END of IF }//END of for LOOP to find M value if((double)(cube(h)+cube(m))==ri)//IF LM found then calculate OP for(i=m;i<=h;i++)//to calculate RN for(j=h;j>=m;j--) if((cube(i)+cube(j))==cube(m)+cube(h))//if FINDED NP also {//then check the condition if(i!=j&&i!=h&&i!=m&&j!=h&&j!=m&&h!=m&&(double)(cube(h)+cube(m))==ri&&(dou ble)(cube(i)+cube(j))==ri) {if(kmk==0){//if LMNP if found then PRINT RN //printf(" %d: %d %d %d %d = %d",flag,i,j,h,m,ri); cout<<" "<<flag<<" "<<h<<" "<<m<<" "<<i<<" "<<j<<"= "<<ri; flag++;//to increment the RN found flag and kmk++;//TO break the LOOP to find LM }//END of IF }//END of IF //flag++; } //END of FOR LOOP LM found } //END of FOR LOOP taking RN from } //END of RN int main(){//MAIN PROOGRAMME char choice; Ramanujan rn;//object of Ramnujan class do{ system("clear");//CLEAR SCREEN //PRINT THE MENU cout<<"##########Menu to Calculate Ramanujan Numbers############################### "; cout<<"1: Calculate RN number by checking RN number and print first 100 Numbers "; cout<<" (Takes more time........) "; cout<<"2: Calculate RN fumber by claculating L, M, N,P and print first 100 Numbers "; cout<<"3: Quit from Menu "; cout<<"################################################################### ######### "; cout<<"Enter Your choice :"; cin>>choice;//USER to select choice if(choice=='1')//If choice 1 then print RN from RN number { rn.fromRN();//calling member to print RN from RN number cout<<" Do you want to Continue(y or Y) else Any key to exit :"; cin>>choice; } else if(choice=='2')//If choice 2 then print RN from LNMP { rn.fromLMNP();//calling member to print print RN from LNMP values cout<<" Do you want to Continue(y or Y) else Any key to exit :"; cin>>choice; } else if(choice=='3')//to QUIT { cout<<" Bye:.............. "; } else//if worng choice entered { cout<<" You Entered Wrong Choice Please select correct "; cout<<" Do you want to Continue(y or Y) else Any key to exit :"; cin>>choice; } }while(choice=='y'||choice=='Y');//condition for choice return 0; //return 0 } //End of main Programme

Consider a situation, when we have two persons with the same name, jhon, in the same class. Whenever we need to differentiate them definitely we would have to use some additional information along with their name, like either the area, if they live in different area or their mother's or father's name, etc. Same situation can arise in your C++ applications. For example, you might be writing some code that has a function called xyz() and there is another library available which is also having same function xyz(). Now the compiler has no way of knowing which version of xyz() function you are referring to within your code.

Arithmetic Operator is used to performing mathematical operations such as addition, subtraction, multiplication, division, modulus, etc., on the given operands. For example: 6 + 3 = 9, 5 - 3 = 2, 3 * 4 = 12, etc. are the examples of arithmetic operators. Let's discuss the different types of Arithmetic Operators in the C programming. Plus Operator is a simple Plus (+) Operator used to add two given operands. We can use Plus Operator with different data types such as integer, float, long, double, enumerated and string type data to add the given operand. The minus operator is denoted by the minus (-) symbol. It is used to return the subtraction of the first number from the second number. The data type of the given number can be different types, such as int, float, double, long double, etc., in the programing language.

In while loop, condition is evaluated first and if it returns true then the statements inside while loop execute, this happens repeatedly until the condition returns false. When condition returns false, the control comes out of loop and jumps to the next statement in the program after while loop. The important point to note when using while loop is that we need to use increment or decrement statement inside while loop so that the loop variable gets changed on each iteration, and at some point condition returns false. This way we can end the execution of while loop otherwise the loop would execute indefinitely. A while loop that never stops is said to be the infinite while loop, when we give the condition in such a way so that it never returns false, then the loops becomes infinite and repeats itself indefinitely.

In computer programming, we use the if statement to run a block code only when a certain condition is met. An if statement can be followed by an optional else statement, which executes when the boolean expression is false. There are three forms of if...else statements in C++: • if statement, • if...else statement, • if...else if...else statement, The if statement evaluates the condition inside the parentheses ( ). If the condition evaluates to true, the code inside the body of if is executed. If the condition evaluates to false, the code inside the body of if is skipped.

Logical Operators are used to compare and connect two or more expressions or variables, such that the value of the expression is completely dependent on the original expression or value or variable. We use logical operators to check whether an expression is true or false. If the expression is true, it returns 1 whereas if the expression is false, it returns 0. Assume variable A holds 1 and variable B holds 0:

In C++, constructor is a special method which is invoked automatically at the time of object creation. It is used to initialize the data members of new object generally. The constructor in C++ has the same name as class or structure. Constructors are special class functions which performs initialization of every object. The Compiler calls the Constructor whenever an object is created. Constructors initialize values to object members after storage is allocated to the object. Whereas, Destructor on the other hand is used to destroy the class object. • Default Constructor: A constructor which has no argument is known as default constructor. It is invoked at the time of creating object.

An array is defined as the collection of similar type of data items stored at contiguous memory locations. Arrays are the derived data type in C++ programming language which can store the primitive type of data such as int, char, double, float, etc. It also has the capability to store the collection of derived data types, such as pointers, structure, etc. The array is the simplest data structure where each data element can be randomly accessed by using its index number. C++ array is beneficial if you have to store similar elements. For example, if we want to store the marks of a student in 6 subjects, then we don't need to define different variables for the marks in the different subject. Instead of that, we can define an array which can store the marks in each subject at the contiguous memory locations.

Execute system command. Invokes the command processor to execute a command. If command is a null pointer, the function only checks whether a command processor is available through this function, without invoking any command. The effects of invoking a command depend on the system and library implementation, and may cause a program to behave in a non-standard manner or to terminate.

Templates are powerful features of C++ which allows us to write generic programs. Similar to function templates, we can use class templates to create a single class to work with different data types. Class templates come in handy as they can make our code shorter and more manageable. A class template starts with the keyword template followed by template parameter(s) inside <> which is followed by the class declaration. T is the template argument which is a placeholder for the data type used, and class is a keyword. Inside the class body, a member variable var and a member function functionName() are both of type T.

#include is a way of including a standard or user-defined file in the program and is mostly written at the beginning of any C/C++ program. This directive is read by the preprocessor and orders it to insert the content of a user-defined or system header file into the following program. These files are mainly imported from an outside source into the current program. The process of importing such files that might be system-defined or user-defined is known as File Inclusion. This type of preprocessor directive tells the compiler to include a file in the source code program.

C supports nesting of loops in C. Nesting of loops is the feature in C that allows the looping of statements inside another loop. Any number of loops can be defined inside another loop, i.e., there is no restriction for defining any number of loops. The nesting level can be defined at n times. You can define any type of loop inside another loop; for example, you can define 'while' loop inside a 'for' loop. A loop inside another loop is called a nested loop. The depth of nested loop depends on the complexity of a problem. We can have any number of nested loops as required. Consider a nested loop where the outer loop runs n times and consists of another loop inside it. The inner loop runs m times. Then, the total number of times the inner loop runs during the program execution is n*m.

The if...else statement executes two different codes depending upon whether the test expression is true or false. Sometimes, a choice has to be made from more than 2 possibilities. The if...else ladder allows you to check between multiple test expressions and execute different statements. In C/C++ if-else-if ladder helps user decide from among multiple options. The C/C++ if statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the C else-if ladder is bypassed. If none of the conditions is true, then the final else statement will be executed.

The cin object is used to accept input from the standard input device i.e. keyboard. It is defined in the iostream header file. C++ cin statement is the instance of the class istream and is used to read input from the standard input device which is usually a keyboard. The extraction operator(>>) is used along with the object cin for reading inputs. The extraction operator extracts the data from the object cin which is entered using the keyboard. The "c" in cin refers to "character" and "in" means "input". Hence cin means "character input". The cin object is used along with the extraction operator >> in order to receive a stream of characters.

A C++ template is a powerful feature added to C++. It allows you to define the generic classes and generic functions and thus provides support for generic programming. Generic programming is a technique where generic types are used as parameters in algorithms so that they can work for a variety of data types. We can define a template for a function. For example, if we have an add() function, we can create versions of the add function for adding the int, float or double type values. Where Ttype: It is a placeholder name for a data type used by the function. It is used within the function definition. It is only a placeholder that the compiler will automatically replace this placeholder with the actual data type. class: A class keyword is used to specify a generic type in a template declaration.

The cout is a predefined object of ostream class. It is connected with the standard output device, which is usually a display screen. The cout is used in conjunction with stream insertion operator (<<) to display the output on a console. On most program environments, the standard output by default is the screen, and the C++ stream object defined to access it is cout. The "c" in cout refers to "character" and "out" means "output". Hence cout means "character output". The cout object is used along with the insertion operator << in order to display a stream of characters.

The main purpose of C++ programming is to add object orientation to the C programming language and classes are the central feature of C++ that supports object-oriented programming and are often called user-defined types. A class is used to specify the form of an object and it combines data representation and methods for manipulating that data into one neat package. The data and functions within a class are called members of the class.

A program shall contain a global function named main, which is the designated start of the program in hosted environment. main() function is the entry point of any C++ program. It is the point at which execution of program is started. When a C++ program is executed, the execution control goes directly to the main() function. Every C++ program have a main() function.

In computer programming, loops are used to repeat a block of code. For example, when you are displaying number from 1 to 100 you may want set the value of a variable to 1 and display it 100 times, increasing its value by 1 on each loop iteration. When you know exactly how many times you want to loop through a block of code, use the for loop instead of a while loop. A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times.

Raise to power. The pow() function returns the result of the first argument raised to the power of the second argument. This function is defined in the cmath header file. pow() function is a library function of cmath header, it is used to find the raise to the power, it accepts two arguments and returns the first argument to the power of the second argument.

A 'prime number' is a natural number greater than 1 that has no positive divisors other than 1 and itself. The C++ Programming Language allows you to separate program-specific data