Program To Check An Armstrong Number

This C program checks an input number whether it is an Armstrong number on not and prints the results. An Armstrong number is special number sum of the \Large n^{th} power of its every digit is equal to the original number. The \Large n is the number of digits in the input number. This concept is explained in more detail in the problem section.

Problem Definition

What is an Armstrong Number?

Suppose there is a number \Large N, this number has \Large n digits, if

  1. We take each digit of the number \Large N separately
  2. Compute \Large n^{th} power of each digit, and
  3. Take the sum, \Large S of all the power obtained in step 2.
  4. If the sum is equal to original number, \Large N
  5. Then the given number \Large N is an Armstrong number.

For Example

\Large \begin{aligned}
&371 = 3^3 + 7^3 + 1^3\\ \\
&= 27 + 343 + 1\\ \\
&=371
\end{aligned}

The number \Large N in above example is \Large 371 and number of digits \Large n = 3. So we raise each of the digits of \Large 371 to power to \Large 3. Then the sum of all power is equal to the original number if the number is an Armstrong number.

How do we process the Input number N?

Step 1 – Get the number \Large N

Step 2 – Split each digit of the number

Step 3 – Raise each digit to the power of \Large 3 and take a sum of all the powers.

Step 4 – Repeat step 1 to 3 if number \Large N not equal to \Large 0.

Step 5 – Check if \Large Sum == N after Step 4, \Large N == 0.

Step 6 – Print the Output.

Flowchart – Check Armstrong Number

Flowchart - C Program to check if a number is Armstrong number or not
Flowchart – C Program to check if a number is Armstrong number or not

Program Codes – Armstrong Number

#include <stdio.h>
#include <conio.h>
main()
{
    int n,i,n1,rem,num =0;
    /* Read the input number */
    printf("Enter a positive integer:");
    scanf("%d",&n);
    /*Get the sum of nth power of each digit */
    n1 = n;
    while(n1 != 0)
    {
        rem = n1 % 10;
        num += rem * rem * rem;
        n1/=10;
    }
    /* Check if the number is an Armstrong or Not */
    if(num == n)
    {
    /*Print the result */
        for(i =0;i<30;i++)
        {
            printf("_");
        }
    printf("\n\n");
    printf(" %d is an Armstrong number\n",n);
        for(i =0;i<30;i++)
        {
            printf("_");
        }
    printf("\n\n");
    }
    else
    {
        for(i =0;i<30;i++)
        {
            printf("_");
            printf("\n\n");
        }
    printf("%d is not an Armstrong number",n);
        for(i =0;i<30;i++)
        {
            printf("_");
            printf("\n\n");
        }
    }
    getch();
    return 0;
}
#include <iostream>
using namespace std;

int main() {
    int n, n1, rem, num = 0;

    cout << "Enter a positive integer: ";
    cin >> n;

    n1 = n;
    while (n1 != 0) {
        rem = n1 % 10;
        num += rem * rem * rem;
        n1 /= 10;
    }

    if (num == n) {
        for (int i = 0; i < 30; i++) cout << "_";
        cout << "\n\n" << n << " is an Armstrong number\n";
        for (int i = 0; i < 30; i++) cout << "_";
        cout << "\n";
    } else {
        for (int i = 0; i < 30; i++) cout << "_";
        cout << "\n\n" << n << " is not an Armstrong number\n";
        for (int i = 0; i < 30; i++) cout << "_";
        cout << "\n";
    }

    return 0;
}
import java.util.Scanner;

class ArmstrongNumber {
    public static void main(String[] args) {
        int n, n1, rem, num = 0;

        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a positive integer: ");
        n = sc.nextInt();

        n1 = n;
        while (n1 != 0) {
            rem = n1 % 10;
            num += rem * rem * rem;
            n1 /= 10;
        }

        if (num == n) {
            for (int i = 0; i < 30; i++) System.out.print("_");
            System.out.println("\n\n" + n + " is an Armstrong number");
            for (int i = 0; i < 30; i++) System.out.print("_");
            System.out.println();
        } else {
            for (int i = 0; i < 30; i++) System.out.print("_");
            System.out.println("\n\n" + n + " is not an Armstrong number");
            for (int i = 0; i < 30; i++) System.out.print("_");
            System.out.println();
        }

        sc.close();
    }
}
n = int(input("Enter a positive integer: "))
n1 = n
num = 0

while n1 != 0:
    rem = n1 % 10
    num += rem * rem * rem
    n1 //= 10

if num == n:
    print("_" * 30)
    print(f"\n{n} is an Armstrong number")
    print("_" * 30)
else:
    print("_" * 30)
    print(f"\n{n} is not an Armstrong number")
    print("_" * 30)

Output

Here is the output of the program for an input integer 371.

 Enter a positive integer:371
 ____________________________
 371 is an Armstrong number
 ____________________________
post

Program To Find Reminder And Quotient

This program uses a division operator on two input numbers. The output is a quotient and a remainder is printed to the console.

Problem Definition

When the program runs, it ask for two input numbers, a and b. The number a is dividend and b is divisor for the program which uses division operator (/) to divide the numbers and return the results.

The program performs the simple division as follows,

\begin{aligned}
&q = a/b\\ \\
&r = a % b
\end{aligned}

Where a and b are two integer values and q is quotient and r is remainder values respectively.

Flowchart – Program to find Quotient and Remainder

Figure 1 - Flowchart for Program to Find Quotient and Remainder
Figure 1 – Flowchart for Program to Find Quotient and Remainder

Program Codes – Remainder and Quotient

#include <stdio.h>
#include <conio.h>
main()
{
    int dnd, div, quotient, remainder;
    int i;
    //Enter Input Numbers 'a' and 'b'
    printf ("Enter the dividend:");
    scanf ("%d", &dnd);
    printf ("Enter the divisor :");
    scanf ("%d",&div);
    //Compute Quotient and Remainder
        quotient = dnd/div;
        remainder = dnd % div;
     //Print the Results
      for(i=0;i < 20;i++)
        printf("_");printf("\n\n");
        printf ("Quotient = %d\n", quotient);
        printf ("Remainder= %d\n", remainder);
    for(i=0;i<20;i++)
        printf("_");printf("\n");
    getch ();
    return 0;
}
#include <iostream>
using namespace std;

int main() {
    int dnd, div, quotient, remainder;
    int i;

    // Enter Input Numbers
    cout << "Enter the dividend:";
    cin >> dnd;
    cout << "Enter the divisor :";
    cin >> div;

    // Compute Quotient and Remainder
    quotient = dnd / div;
    remainder = dnd % div;

    // Print the Results
    for (i = 0; i < 20; i++)
        cout << "_";
    cout << "\n\n";

    cout << "Quotient = " << quotient << endl;
    cout << "Remainder= " << remainder << endl;

    for (i = 0; i < 20; i++)
        cout << "_";
    cout << endl;

    return 0;
}
import java.util.Scanner;

public class QuotientRemainder {
    public static void main(String[] args) {
        int dnd, div, quotient, remainder;
        int i;

        Scanner sc = new Scanner(System.in);

        // Enter Input Numbers
        System.out.print("Enter the dividend:");
        dnd = sc.nextInt();
        System.out.print("Enter the divisor :");
        div = sc.nextInt();

        // Compute Quotient and Remainder
        quotient = dnd / div;
        remainder = dnd % div;

        // Print the Results
        for (i = 0; i < 20; i++)
            System.out.print("_");
        System.out.print("\n\n");

        System.out.println("Quotient = " + quotient);
        System.out.println("Remainder= " + remainder);

        for (i = 0; i < 20; i++)
            System.out.print("_");
        System.out.println();

        sc.close();
    }
}
# Program to find quotient and remainder

# Enter Input Numbers
dnd = int(input("Enter the dividend:"))
div = int(input("Enter the divisor :"))

# Compute Quotient and Remainder
quotient = dnd // div
remainder = dnd % div

# Print the Results
for i in range(20):
    print("_", end="")
print("\n")

print("Quotient =", quotient)
print("Remainder=", remainder)

for i in range(20):
    print("_", end="")
print()

The most important code in the above program is as follows.

\begin{aligned}&
quotient = dnd/div \\ \\
&remainder = dnd \hspace{1mm} \%  \hspace{1mm}div;
\end{aligned}

The values of quotient and remainder is printed to console before the program terminates.

Output

In the results below, 34 is divided by 6 and results in quotient = 5 and remainder = 4 because

\begin{aligned}&
a = q * b + r \\ \\
&34 = 5 * 6 + 4\\ \\
&= 30 + 4
\end{aligned}
                     Enter the dividend:34
                     Enter the divisor :6
                     _____________________
                     Quotient = 5
                     Remainder= 4
                     _____________________
post

Program To Find Permutation And Combination

The program to find permutation and combination solves \Large 4 different types of problems. The permutation problems are arrangement problems and the combination problems are selection problems.

You will more details about each type of problem in the problem definition section.

The list of problems is given below

  1. \Large R-permutation of a set of \Large N distinct objects where \Large 1 \lt R \lt N.
  2. \Large R-permutation of a set of \Large N distinct objects with repetition allowed.
  3. Permutation of \Large N objects where \Large N is not distinct and contains indistinguishable objects of different types – \Large n_1 types, \Large n_2 types,\Large \cdots ,n_k types.
  4. \Large R-combination of a set of \Large N distinct objects where \Large 1 \lt R \lt N.
  5. \Large R -combination of a set of \Large N distinct objects with repetition allowed.

Problem Definition: R-permutation of N distinct objects

A permutation is the number of arrangement of \Large N distinct objects taken \Large R at a time. Suppose we have \Large N people sitting in a row of chairs, how many ways to change the sitting arrangement taken \Large R people at a time.

For example, suppose we have \Large 3 men sitting on \Large 3 chairs; let’s call them \Large A, B and \Large C . The number of arrangements of \Large 2 men out of \Large N i.e., \Large N = 3, R = 2 is given below.

AB          AC          BC
BA          CA          CB

In the above example, the order of the arrangement matters and each of these different orders is counted

\Large \begin{aligned}
& Formula for Permutation = \frac{N!}{(N-R)!}\\ \\
&nPr = n! / (n-r)!
\end{aligned}

Flowchart 1 – Permutation without Repetition

Flowchart - Permutation - No Repetition
Flowchart – Permutation – No Repetition

Program Code – Permutation No Repetition

The program for the \Large R permutation of \Large N distinct numbers is given below.

#include <stdio.h>
#include <conio.h>
int fact(int);
int main()
{
    int NPR,N,R,M,i;
    NPR=0;
    M=0;
    M= N-R;
    printf("Enter value for N and R:");
    scanf("%d %d",&N,&R);
    NPR = fact(N)/fact(M);
    for(i=0;i<45;i++)
    printf("_");printf("\n\n");
    printf("Number of %d-permutation of %d object 
    = %dn",R,N,NPR);
    for(i=0;i<45;i++)
    printf("_");printf("\n\n");
    system("PAUSE");
    return 0;
}

int fact(m)
{
    int i,fact=1;
    for(i=1;i<=m;i++)
    {
        fact=fact*i;
    }
    return(fact);
}
#include <iostream>
using namespace std;

long long fact(int m)
{
    long long f = 1;
    for (int i = 1; i <= m; i++)
        f *= i;
    return f;
}

int main()
{
    int N, R;
    long long NPR;

    cout << "Enter value for N and R: ";
    cin >> N >> R;

    NPR = fact(N) / fact(N - R);

    cout << "\n---------------------------------------------\n";
    cout << "Number of " << R << "-permutation of "
         << N << " objects = " << NPR << endl;
    cout << "---------------------------------------------\n";

    return 0;
}
import java.util.Scanner;

class NPR
{
    static long fact(int m)
    {
        long f = 1;
        for (int i = 1; i <= m; i++)
            f *= i;
        return f;
    }

    public static void main(String args[])
    {
        int N, R;
        long NPR;

        Scanner sc = new Scanner(System.in);
        System.out.print("Enter value for N and R: ");
        N = sc.nextInt();
        R = sc.nextInt();

        NPR = fact(N) / fact(N - R);

        System.out.println("\n---------------------------------------------");
        System.out.println("Number of " + R + "-permutation of "
                           + N + " objects = " + NPR);
        System.out.println("---------------------------------------------");
    }
}
def fact(m):
    f = 1
    for i in range(1, m + 1):
        f *= i
    return f

N = int(input("Enter value for N: "))
R = int(input("Enter value for R: "))

NPR = fact(N) // fact(N - R)

print("\n---------------------------------------------")
print(f"Number of {R}-permutation of {N} objects = {NPR}")
print("---------------------------------------------")

Output

The output of the first program is given below.

Enter value for N and R: 10 2
------------------------------------------------
Number of 2-permutation of 10 objects = 3628800
------------------------------------------------

Problem Definition: R-permutation of a set of N distinct objects with repetition allowed

In permutation without repetition, you select \Large R objects at a time from \Large N objects. Now you have \Large R positions to arrange \Large N objects.

\Large \begin{aligned}
&First \hspace{2px}position \hspace{2px}can \hspace{2px}have \hspace{2px} N \hspace{2px}choices.\\ \\
&The \hspace{2px}second\hspace{2px} position \hspace{2px}can \hspace{2px}have \hspace{2px}( N-1 ) \hspace{2px}choices.\\ \\
&The\hspace{2px} third \hspace{2px}position\hspace{2px} can \hspace{2px} have \hspace{2px}(N - 2) \hspace{2px}choices.\\ \\
&\cdots \\
&\cdots \\
&\cdots \\ \\
&R^{th} \hspace{2px}position \hspace{2px} can \hspace{2px} have \hspace{2px} ( N - R + 1 )\hspace{2px} choices.
\end{aligned}

For example

\Large \begin{aligned}&Let \hspace{2px} N = 6, R = 3\\ \\ &1^{st} \hspace{2px}Position \hspace{10px} 2^{nd} \hspace{2px} Position \hspace{10px} 3^{rd} \hspace{2px} Position\\ &6 \hspace{2px} choices \hspace{5px}\times \hspace{5px}  5 \hspace{2px}  choices \hspace{5px}\times \hspace{5px}4 \hspace{2px} choices = 120 \end{aligned}

However, with permutation with repetition allowed, the above example becomes

\Large \begin{aligned}&1^{st} \hspace{2px}Position \hspace{10px} 2^{nd} \hspace{2px} Position \hspace{10px} 3^{rd} \hspace{2px} Position\\ &6 \hspace{2px} choices \hspace{5px}\times \hspace{5px}  6 \hspace{2px}  choices \hspace{5px}\times \hspace{5px}6\hspace{2px} choices = 120 =N^R
\end{aligned}

In other words, the \Large N objects are repeated \Large R times which is \Large = N^R.

Flowchart 2 – Permutation with repetition allowed

Flowchart - Permutation With Repetition Allowed
Flowchart – Permutation With Repetition Allowed

Program Code – Permutation with repetition allowed

The C program for permutation with repetition allowed is given below.

/* program to find npr = n^r */
#include <math.h>
#include <stdio.h>
#include <conio.h>
main()
{
    int i,N,R,NPR;
    NPR =1;
    printf ("Enter the values for N and R:");
    scanf ("%d %d", &N, &R);
    for(i=0;i<R;i++)
    {
        NPR = NPR * N;
    }
    for(i=0;i<50;i++)
    printf("_");printf("\n\n");
    printf("Number of %d-permutation of %d with Repetition 
    = %d\n",R,N,NPR);
    for(i=0;i<50;i++)
    printf("_");printf("\n\n");
    system("PAUSE");
    return 0;
}
#include <iostream>
using namespace std;

int main()
{
    int N, R;
    long long NPR = 1;

    cout << "Enter the values for N and R: ";
    cin >> N >> R;

    for (int i = 0; i < R; i++)
    {
        NPR = NPR * N;
    }

    cout << "\n--------------------------------------------------\n";
    cout << "Number of " << R << "-permutation of "
         << N << " with repetition = " << NPR << endl;
    cout << "--------------------------------------------------\n";

    return 0;
}
import java.util.Scanner;

class NPR_Repetition
{
    public static void main(String args[])
    {
        int N, R;
        long NPR = 1;

        Scanner sc = new Scanner(System.in);
        System.out.print("Enter the values for N and R: ");
        N = sc.nextInt();
        R = sc.nextInt();

        for (int i = 0; i < R; i++)
        {
            NPR = NPR * N;
        }

        System.out.println("\n--------------------------------------------------");
        System.out.println("Number of " + R + "-permutation of "
                           + N + " with repetition = " + NPR);
        System.out.println("--------------------------------------------------");
    }
}
N = int(input("Enter the value for N: "))
R = int(input("Enter the value for R: "))

NPR = 1
for i in range(R):
    NPR *= N

print("\n--------------------------------------------------")
print(f"Number of {R}-permutation of {N} with repetition = {NPR}")
print("--------------------------------------------------")

Output 2

The output of the program for permutation with repetition allowed is given below.

Enter the values for N and R:5 4
--------------------------------------------------------------
Number of 4-permutation of 5 with Repetition = 625
--------------------------------------------------------------

Problem Definition: Permutation of N objects where N is not distinct and contains indistinguishable objects

Another type of permutation problem is when you have \Large N object, but they are not distinct and contains many objects of similar types.

\Large \begin{aligned}
&N \hspace{2px} objects =   x \hspace{2px}object \hspace{2px}of  \hspace{2px}n_1 \hspace{2px} type + \\\\
&y \hspace{2px} object \hspace{2px}of \hspace{2px}n_2 \hspace{2px}type + \\ \\
&z\hspace{2px} object \hspace{2px}of\hspace{2px} n_3 \hspace{2px}type + \\ \\
&\cdots + \\\\
&p \hspace{2px}objects \hspace{2px}of \hspace{2px}n_k \hspace{2px}type
\end{aligned}

The formula is given by following

\Large \begin{aligned} N = n_1 + n_2 + n_3 + \cdots + n_k\end{aligned}

To find the permutation of \Large N objects where some of them of indistinguishable, you use following.

\Large \begin{aligned}nPr = \frac{ n! }{ (n_1! + n_2! + n_3!)}\end{aligned}

Flowchart 3 – Permutation of Indistinguishable Objects

Flowchart - Permutation of Indistinguishable Objects
Flowchart – Permutation of Indistinguishable Objects

Program Code – Permutation of Indistinguishable Objects

The program for the permutation of numbers where some objects are indistinguishable.

#include <stdio.h>
#include <conio.h>
#include<math.h>
int fact(int);
main()
{
    int i,N,TOT,NPR,SUB;
    int OBJ[15];
    SUB = 1;TOT = 0;
    printf ("Enter the values for number of object N:");
    scanf("%d",&N);
for(i=1;i<=N;i++)
{
    printf("How many number of object OBJ[%d]?:",i);
    scanf ("%d", &OBJ[i]);
}
for(i=1;i<=N;i++)
{
    TOT = TOT + OBJ[i];
}
for(i=1;i<=N;i++) { 
    if(OBJ[i]>1)
    SUB = SUB * fact(OBJ[i]);
}
    NPR = fact(TOT)/SUB;
    for(i=0;i<50;i++)
    printf("_");
    printf("\n\n");
    printf("Permutation of %d distinguishable objects 
    = %d\n",N,NPR);
    for(i=0;i<50;i++)
    printf("_");printf("\n\n");
    system("PAUSE");
    return 0;
}
int fact(m)
{
    int i,fact=1;
    for(i=1;i<=m;i++)
    {
        fact=fact*i;
    }
    return(fact);
}
#include <iostream>
using namespace std;

long long fact(int m)
{
    long long f = 1;
    for (int i = 1; i <= m; i++)
        f *= i;
    return f;
}

int main()
{
    int N, TOT = 0;
    long long SUB = 1, NPR;
    int OBJ[20];

    cout << "Enter the number of object types: ";
    cin >> N;

    for (int i = 1; i <= N; i++)
    {
        cout << "How many objects of type " << i << "? ";
        cin >> OBJ[i];
        TOT += OBJ[i];
    }

    for (int i = 1; i <= N; i++)
    {
        if (OBJ[i] > 1)
            SUB *= fact(OBJ[i]);
    }

    NPR = fact(TOT) / SUB;

    cout << "\n--------------------------------------------------\n";
    cout << "Permutation of distinguishable objects = " << NPR << endl;
    cout << "--------------------------------------------------\n";

    return 0;
}
import java.util.Scanner;

class DistinguishablePermutation
{
    static long fact(int m)
    {
        long f = 1;
        for (int i = 1; i <= m; i++)
            f *= i;
        return f;
    }

    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);

        int N, TOT = 0;
        long SUB = 1, NPR;
        int OBJ[] = new int[20];

        System.out.print("Enter the number of object types: ");
        N = sc.nextInt();

        for (int i = 1; i <= N; i++)
        {
            System.out.print("How many objects of type " + i + "? ");
            OBJ[i] = sc.nextInt();
            TOT += OBJ[i];
        }

        for (int i = 1; i <= N; i++)
        {
            if (OBJ[i] > 1)
                SUB *= fact(OBJ[i]);
        }

        NPR = fact(TOT) / SUB;

        System.out.println("\n--------------------------------------------------");
        System.out.println("Permutation of distinguishable objects = " + NPR);
        System.out.println("--------------------------------------------------");
    }
}
def fact(m):
    f = 1
    for i in range(1, m + 1):
        f *= i
    return f

N = int(input("Enter the number of object types: "))

OBJ = []
TOT = 0
SUB = 1

for i in range(N):
    val = int(input(f"How many objects of type {i+1}? "))
    OBJ.append(val)
    TOT += val

for val in OBJ:
    if val > 1:
        SUB *= fact(val)

NPR = fact(TOT) // SUB

print("\n--------------------------------------------------")
print(f"Permutation of distinguishable objects = {NPR}")
print("--------------------------------------------------")

Output 3

The output of the program with permutation is given below.

Enter the values of number of object N:4
How many number of object OBJ[1]?:3
How many number of object OBJ[2]?:2
How many number of object OBJ[3]?:1
How many number of object OBJ[4]?:1
------------------------------------------------------
Permutation of 4 distinguishable objects = 420
------------------------------------------------------

Problem Definition: R-combination of a set of N distinct objects

A combination is a selection of \Large N distinct object taken \Large R at a time. The word “Selection” is very important because it indicates that only a particular order of \Large R objects is accepted.

For example, consider our example of permutation of \Large A, B and \Large C.

AB          AC          BC
BA          CA          CB

Here only one of the arrangement is “selected”, you can only select \Large AB or \Large BA, not both. This is called a Combination.

The formula for nCr is given below.

\begin{aligned}&Formula \hspace{2px} for \hspace{2px}  Combination = \frac{N \hspace{2px}  factorial }{ (R \hspace{2px} factorial \cdot (N-R) \hspace{2px} factorial)}\\ \\
&nCr = \frac{n!}{(r! \cdot (n-r)!)} 
\end{aligned}

Flowchart 4 – Combination No Repetition

Flowchart - Combination No Repetition
Flowchart – Combination No Repetition

Program Code – Combination No Repetition

Program for the combination of numbers is given below.

/* program to find nCr */
#include <stdio.h>
#include <conio.h>
long int fact(long int);
int main()
{
    long int i,N,R,M,NCR;
    printf ("Enter the values for N and R: ");
    scanf ("%d %d", &N, &R);
    M = N - R;
    NCR = fact(N)/(fact (R) * fact(M)); //ncr formula
    for(i=0;i<45;i++)
    printf("_");printf("\n\n");
    printf("Number of %d-combination of %d 
    = %dn",R,N,NCR);
    for(i=0;i<45;i++)
    printf("_");printf("\n\n");
    system("PAUSE");
    return 0;
}
long int fact(long int m)
{
    long int i,fact=1;
    for(i=1;i<=m;i++)
    {
        fact=fact*i;
    }
    return(fact);
}
#include <iostream>
using namespace std;

long long fact(long long m)
{
    long long f = 1;
    for (long long i = 1; i <= m; i++)
        f *= i;
    return f;
}

int main()
{
    long long N, R, NCR;

    cout << "Enter the values for N and R: ";
    cin >> N >> R;

    NCR = fact(N) / (fact(R) * fact(N - R));

    cout << "\n---------------------------------------------\n";
    cout << "Number of " << R << "-combination of "
         << N << " = " << NCR << endl;
    cout << "---------------------------------------------\n";

    return 0;
}
import java.util.Scanner;

class NCR
{
    static long fact(long m)
    {
        long f = 1;
        for (long i = 1; i <= m; i++)
            f *= i;
        return f;
    }

    public static void main(String args[])
    {
        long N, R, NCR;
        Scanner sc = new Scanner(System.in);

        System.out.print("Enter the values for N and R: ");
        N = sc.nextLong();
        R = sc.nextLong();

        NCR = fact(N) / (fact(R) * fact(N - R));

        System.out.println("\n---------------------------------------------");
        System.out.println("Number of " + R + "-combination of "
                           + N + " = " + NCR);
        System.out.println("---------------------------------------------");
    }
}
def fact(m):
    f = 1
    for i in range(1, m + 1):
        f *= i
    return f

N = int(input("Enter the value for N: "))
R = int(input("Enter the value for R: "))

NCR = fact(N) // (fact(R) * fact(N - R))

print("\n---------------------------------------------")
print(f"Number of {R}-combination of {N} = {NCR}")
print("---------------------------------------------")

Output 4

The output of the program is given below.

Enter the values for N and R: 10 5
---------------------------------------------
Number of 5-combination of 10 = 252
---------------------------------------------

Problem Definition: R-combinations of a set of N distinct object with repetition allowed

We know that \Large R -combination is a selection of \Large R objects at a time from given \Large N object set. The \Large R-combination of a set of \Large N distinct object with repetition means that we can now select each object in \Large N more than once.

For example, Let’s \Large N = 3, with \Large A, B and, \Large C and \Large R = 2.

You need to select \Large 2 object combination out of \Large 3 such that you can now choose any object more than once.

AA   AB    AC   BB    BC    CC

The formula for \Large R-combination with repetition is given below.

nCr formula with repetition

\Large \begin{aligned}{}^{\,n+r-1}C_{r}
= \frac{(n + r - 1)!}{ ( r! \cdot (n - 1)!)}\end{aligned}

The solution to the above problem is

\begin{aligned} &=\frac{(3 + 2 - 1)!}{2! (3 -1)!}\\
&=\frac{4 \times 3 \times \cancel{2 \times 1}}{2 \times 1\times \cancel{2 \times 1}}\\
&= 6
\end{aligned}

Flowchart 5 – Combination with Repetition Allowed

Flowchart - Combination Repetition Allowed
Flowchart – Combination Repetition Allowed

Program Code – Combination with Repetition Allowed

The program for the combination of numbers with repetition allowed is given below.

/* program to find nCr with repetition */
#include <stdio.h>
#include <conio.h>
int main()
{
    int N,R,P,M,fact(int);
    int i,NCR;
    printf ("Enter the value for N and R: ");
    scanf ("%d %d", &N, &R);
    P = N + R - 1;
    M = P - R;
    NCR = fact(P)/(fact(R)* fact(M));
    for(i=0;i<45;i++)
    printf("_");printf("\n\n");
    printf("Number of %d-Combination of %d with Repetition 
    = %d\n",R,N,NCR);
    for(i=0;i<45;i++)
    printf("_");printf("\n\n");
    system("PAUSE");
    return 0;
}
int fact(p)
{
    int i,fact=1;
    for(i=1;i<=p;i++)
    {
        fact=fact*i;
    }
    return(fact);
}
#include <iostream>
using namespace std;

long long fact(long long p)
{
    long long f = 1;
    for (long long i = 1; i <= p; i++)
        f *= i;
    return f;
}

int main()
{
    long long N, R, NCR;
    long long P, M;

    cout << "Enter the value for N and R: ";
    cin >> N >> R;

    P = N + R - 1;
    M = P - R;   // = N - 1

    NCR = fact(P) / (fact(R) * fact(M));

    cout << "\n---------------------------------------------\n";
    cout << "Number of " << R << "-combination of "
         << N << " with repetition = " << NCR << endl;
    cout << "---------------------------------------------\n";

    return 0;
}
import java.util.Scanner;

class NCR_Repetition
{
    static long fact(long p)
    {
        long f = 1;
        for (long i = 1; i <= p; i++)
            f *= i;
        return f;
    }

    public static void main(String args[])
    {
        long N, R, P, M, NCR;
        Scanner sc = new Scanner(System.in);

        System.out.print("Enter the value for N and R: ");
        N = sc.nextLong();
        R = sc.nextLong();

        P = N + R - 1;
        M = P - R;   // N - 1

        NCR = fact(P) / (fact(R) * fact(M));

        System.out.println("\n---------------------------------------------");
        System.out.println("Number of " + R + "-combination of "
                           + N + " with repetition = " + NCR);
        System.out.println("---------------------------------------------");
    }
}
def fact(p):
    f = 1
    for i in range(1, p + 1):
        f *= i
    return f

N = int(input("Enter the value for N: "))
R = int(input("Enter the value for R: "))

P = N + R - 1
M = P - R   # N - 1

NCR = fact(P) // (fact(R) * fact(M))

print("\n---------------------------------------------")
print(f"Number of {R}-combination of {N} with repetition = {NCR}")
print("---------------------------------------------")

Output 5

The output of the program is given below.

Enter the value for N and R: 4 6
---------------------------------------------------
Number of 6-Combination of 4 = 84
---------------------------------------------------
post

Program For GCD Of Two Numbers

This is a simple program to find the Greatest Common Divisor (GCD) of two given positive numbers.

Problem Definition

Suppose you want to find GCD of two numbers – \Large a and \Large b. The C program for GCD has a function called \Large hcf(a, b) which is called recursively until remainder is \Large 0. The function uses the following logic on the given input numbers where a is greater than or equal to \Large b.

\Large \begin{aligned}
&r = a - (a/b * b)
\end{aligned}

Suppose \Large a = 24 and \Large b = 6 than

\large \begin{aligned}
&r = 24 - (24/6 * 6)\\ 
&r = 24 - 24 = 0\\
&r = 0
\end{aligned}

Then the value of \Large b is the GCD which is \Large 6. Note: – number \Large amust be greater than or equal to \Large b.

Flowchart – Program for GCD of Two Numbers

Figure 1 - Flowchart for Program for GCD of Two Numbers
Figure 1 – Flowchart for Program for GCD of Two Numbers

Program Codes – GCD of Two Numbers

#include <stdio.h>
#include <conio.h>
main()
{
    int i,a,b,gcd;
    int hcf();
    /* Read the input numbers */
    printf("Enter Two Numbers To Find GCD:");
    scanf("%d%d",&a,&b);
    /* Compute the GCD for given numbers */
    gcd=hcf(a,b);
    /* Print the Result */
    for(i=0;i<40;i++)
    printf("_");printf("\n\n");
    printf("GCD of %d and %d is %d\n",a,b,gcd);
    for(i=0;i<40;i++)
    printf("_");printf("\n\n");
    system("PAUSE");
    return 0;
}

int hcf(p,q)
{
    int r;
    r=p-(p/q*q);
    if(r==0)
        return(q);
    else
        return hcf(q,r);
}
#include <iostream>
using namespace std;

int hcf(int p, int q)
{
    int r = p % q;
    if (r == 0)
        return q;
    else
        return hcf(q, r);
}

int main()
{
    int a, b, gcd;

    cout << "Enter Two Numbers To Find GCD: ";
    cin >> a >> b;

    gcd = hcf(a, b);

    cout << "\n----------------------------------------\n";
    cout << "GCD of " << a << " and " << b << " is " << gcd << endl;
    cout << "----------------------------------------\n";

    return 0;
}
import java.util.Scanner;

class GCD
{
    static int hcf(int p, int q)
    {
        int r = p % q;
        if (r == 0)
            return q;
        else
            return hcf(q, r);
    }

    public static void main(String[] args)
    {
        int a, b, gcd;
        Scanner sc = new Scanner(System.in);

        System.out.print("Enter Two Numbers To Find GCD: ");
        a = sc.nextInt();
        b = sc.nextInt();

        gcd = hcf(a, b);

        System.out.println("\n----------------------------------------");
        System.out.println("GCD of " + a + " and " + b + " is " + gcd);
        System.out.println("----------------------------------------");

        sc.close();
    }
}
def hcf(p, q):
    r = p % q
    if r == 0:
        return q
    else:
        return hcf(q, r)

a = int(input("Enter first number: "))
b = int(input("Enter second number: "))

gcd = hcf(a, b)

print("\n----------------------------------------")
print(f"GCD of {a} and {b} is {gcd}")
print("----------------------------------------")

The important piece of code in the above source code is the call to \Large hcf(a, b) function and the function \Large hcf(a, b) calling itself recursively.

gcd = hcf(a, b);

The function \Large hcf(a, b)evaluate the current value of \Large a and \Large b, and if the remainder is not equal to \Large 0, it call itself one more time until the remainder becomes \Large 0.

int hcf(p,q) 
{  
    int r; 
    r=p-(p/q*q);  
    if(r==0)  
        return(q);  
    else  
        return hcf(q,r); 
}

Output

The output of the program is given below. When the user enters \Large 24 and \Large 6, the result is \Large 6 which greatest common divisor (GCD) of \Large 24 and \Large 6

         Enter Two Numbers To Find GCD:24 6
          ------------------------------------------
          GCD of 24 and 6 is 6
          ------------------------------------------
post

Program To Compute Cosine Series

The program to compute cosine series is based on the mathematical concept of sequences and series – particularly power series.

Problem Definition

Cosine series is a power series known as the Maclaurin expansion of \Large cos \hspace{2px} (x) where \Large x is a real number. For any given value of \Large x, the series will converges and evaluates to a finite value; the radius of convergence for the series is infinite.

Cosine Series
Figure 1 – Cosine Series

We won’t be discussing, how terms of the series are generated because that would be topic for another post. The Maclaurin expansion for \Large cos \hspace{2px} (x) is for \Large x =0, however, it is true for all real values of \Large x.

In other words, it is same as finding the value of trigonometric ratio of \Large cos \hspace{2px} \theta, the cosine series will give you a better approximate value of \Large cos \hspace{2px} \theta.

Flowchart – Program for Cosine Series

Flowchart - C Program for Cosine Series
Flowchart – C Program for Cosine Series

Program Codes for Cosine Series

/* Program to compute cosine series */
/* cos(x) = 1-x^2/2!+x^4/4!+x^6/6!+...+x^n/n! */
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
main()
{
    float x, t, sum;
    int d;
    int i, n=20;
    /* Read the Input x value in degrees */
    printf ("Input X Value (in degrees) :");
    scanf ("%f", &x);
    d= x;
    /*converting x to radians */
    x=x*3.1412/180;
    t=1;
    sum=1;
    for (i=1; i<n+1; i++)
    {
        t=t*pow ((double) (-1), (double) (2*i-1))*x*x/ (2*i*(2*i-1));
        sum=sum+t;
    }
    /* Print the Results */
    for (i =0; i<35; i++)
    printf ("_"); printf ("\n\n");
    printf ("COS (%d) =%7.3f\n\n", (int) d, sum);
    for (i =0; i<35; i++)
    printf ("_"); printf ("\n\n");
    system ("PAUSE");
    return 0;
}
/* C++ Program to compute cosine series */
#include <iostream>
#include <cmath>
#include <cstdlib>
using namespace std;

int main() {
    float x, t, sum;
    int d;
    int i, n = 20;

    cout << "Input X Value (in degrees): ";
    cin >> x;
    d = static_cast<int>(x);

    // Convert degrees to radians
    x = x * 3.1412 / 180;
    t = 1;
    sum = 1;

    for (i = 1; i <= n; i++) {
        t = t * pow(-1.0, 2*i-1) * x * x / (2*i*(2*i-1));
        sum = sum + t;
    }

    for (i = 0; i < 35; i++) cout << "_";
    cout << "\n\n";
    cout << "COS (" << d << ") = " << fixed << sum << "\n\n";
    for (i = 0; i < 35; i++) cout << "_";
    cout << "\n\n";

    system("PAUSE");
    return 0;
}
/* Java Program to compute cosine series */
import java.util.Scanner;

public class CosineSeries {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        float x, t, sum;
        int d;
        int n = 20;

        System.out.print("Input X Value (in degrees): ");
        x = sc.nextFloat();
        d = (int) x;

        // Convert degrees to radians
        x = x * 3.1412f / 180;
        t = 1;
        sum = 1;

        for (int i = 1; i <= n; i++) {
            t = t * (float)Math.pow(-1.0, 2*i-1) * x * x / (2*i*(2*i-1));
            sum = sum + t;
        }

        for (int i = 0; i < 35; i++) System.out.print("_");
        System.out.println("\n\n");
        System.out.printf("COS (%d) = %.3f\n\n", d, sum);
        for (int i = 0; i < 35; i++) System.out.print("_");
        System.out.println();
    }
}
# Python Program to compute cosine series
import math

x = float(input("Input X Value (in degrees): "))
d = int(x)

# Convert degrees to radians
x = x * 3.1412 / 180
t = 1
sum_ = 1
n = 20

for i in range(1, n+1):
    t = t * (-1)**(2*i-1) * x*x / (2*i*(2*i-1))
    sum_ += t

print("_"*35 + "\n")
print(f"COS ({d}) = {sum_:.3f}\n")
print("_"*35 + "\n")

Output

           Input X Values(in degrees):34
           -------------------------------------
           COS(34)= 0.829
           -------------------------------------
post

Program To Compute Standard Deviation For Non-Grouped Data

In this example program, we compute the standard deviation for input non-grouped data and output the result.

The standard deviation is a measure to understand how much data deviates from the mean value. The data may be grouped or non-grouped where non-group data is a list of data.

In the next section, we will discuss the problem in detail.

Problem Definition

The standard deviation is a measure useful in comparing two sets of data when their mean value is the same. To calculate the standard deviation we use the following formula in this example program.

\Large SD =  \sqrt{\frac{(x - \overline{x})^2}{n}}

Where \Large \overline{x} is the mean value.

Given the formula, you can find standard deviation in the following steps.

  • Find the mean value.
  • Take the sum of each data element \Large x , subtracted from mean and then squared.
  • Take the square root of \frac{\Large sum}{\Large n}where \Large n <mark style="background-color:rgba(0, 0, 0, 0);color:#bb1717" class="has-inline-color"></mark>is the number of data elements.

The first step is to find the mean value of the given non-grouped data. The program takes the sum of all data elements and divides it with the total number of elements.

\Large Mean\hspace{1mm} value = \frac{Sum \hspace{1mm}of\hspace{1mm} all \hspace{1mm}elements}{Number\hspace{1mm} of \hspace{1mm}elements}

The second step in process of finding standard deviation is to take the sum of each data element (say x ) and subtract it from the mean and then square it.

\Large Sum = Sum + (x[i] - mean \hspace{1mm}value)^2

Where \Large x[i] represents a data element from the list of non-grouped data set. The last step is to compute the standard deviation using the following.

\Large Standard \hspace{1mm} deviation =  sqrt( Sum / n)

where \Large n is the total number of elements in data set and Sum is the value found in the previous step.

Program Codes – Standard Deviation for Non-grouped Data

#include <stdio.h>
#include <math.h>

/* Function Declaration */
float standard_deviation(float data[], int n);

int main()
{
    int n, i;
    float data[100];

    printf("Enter number of data elements (1 to 100): ");
    scanf("%d", &n);

    if (n <= 0 || n > 100)
    {
        printf("Invalid number of elements\n");
        return 0;
    }

    printf("Enter elements:\n");
    for (i = 0; i < n; i++)
        scanf("%f", &data[i]);

    printf("Standard Deviation = %.3f\n",
           standard_deviation(data, n));

    return 0;
}

float standard_deviation(float data[], int n)
{
    float mean = 0.0, sum = 0.0;
    int i;

    for (i = 0; i < n; i++)
        mean += data[i];

    mean /= n;

    for (i = 0; i < n; i++)
        sum += (data[i] - mean) * (data[i] - mean);

    return sqrt(sum / n);   /* Ungrouped data SD */
}
#include <iostream>
#include <cmath>
using namespace std;

float standardDeviation(float data[], int n)
{
    float mean = 0, sum = 0;

    for (int i = 0; i < n; i++)
        mean += data[i];
    mean /= n;

    for (int i = 0; i < n; i++)
        sum += (data[i] - mean) * (data[i] - mean);

    return sqrt(sum / n);
}

int main()
{
    int n;
    float data[100];

    cout << "Enter number of elements (1 to 100): ";
    cin >> n;

    if (n <= 0 || n > 100)
    {
        cout << "Invalid input\n";
        return 0;
    }

    cout << "Enter elements:\n";
    for (int i = 0; i < n; i++)
        cin >> data[i];

    cout << "Standard Deviation = "
         << standardDeviation(data, n) << endl;

    return 0;
}
import java.util.Scanner;

class StandardDeviation
{
    static double standardDeviation(double data[], int n)
    {
        double mean = 0, sum = 0;

        for (int i = 0; i < n; i++)
            mean += data[i];
        mean /= n;

        for (int i = 0; i < n; i++)
            sum += (data[i] - mean) * (data[i] - mean);

        return Math.sqrt(sum / n); // Population SD
    }

    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);
        int n;
        double[] data = new double[100];

        System.out.print("Enter number of elements (1 to 100): ");
        n = sc.nextInt();

        if (n <= 0 || n > 100)
        {
            System.out.println("Invalid input");
            return;
        }

        System.out.println("Enter elements:");
        for (int i = 0; i < n; i++)
            data[i] = sc.nextDouble();

        System.out.println("Standard Deviation = "
                + standardDeviation(data, n));

        sc.close();
    }
}
import math

n = int(input("Enter number of elements (1 to 100): "))

if n <= 0 or n > 100:
    print("Invalid input")
    exit()

data = []
print("Enter elements:")
for _ in range(n):
    data.append(float(input()))

mean = sum(data) / n
variance = sum((x - mean) ** 2 for x in data) / n
std_dev = math.sqrt(variance)

print("Standard Deviation =", round(std_dev, 3))

Output – Compute Standard Deviation for non-grouped data

When we execute the program whose code is given above. It asks for the number of data elements which should be less than \Large 100. For the purpose of example, you can enter any number (say \Large 7).

The program then asks for data elements, we entered following – \Large 56, 45, 89, 78, 12, 23, 35. The standard deviation value is \Large 26.031. To prove the correctness of the output, we leave it as an exercise for you. The output is shown below.

Enter Number of Data elements( Less than 100):7
Enter Elements:
56
45
78
89
23
12
35

Standard Deviation - 26.031
post

Program To Find Average Age

This program finds the average age of a person using an array. The array which stores a list of age is passed on to a function and the function computes the average age and returns a value.

Problem Definition

To find the average age of person the program does the following tasks.

  • Read all the values in an array.
  • Pass the entire array to function average( ).
  • Function average() computes and returns a value.

First, we store all the values of age in the array during array declaration. Do not mention the size during array declaration because it is automatically determined when array members are assigned.

For example

int arr[] = {20, 34, 45, 26, 58, 33};

The above declaration has 6 members; therefore, the size of the array is 6. Second, the array is passed on the function when you call the function in the main program.

main()
{
      avg = average(arr);
}

The value returned by function average will be assigned to variable avg. When the array is passed on to the function, only the reference to the first member of the array is passed. Other members are located using the reference to the first member.

Program Source Codes

#include <stdio.h>
#include <stdlib.h>
int average(int arr[]); /* Function declaration */
int main()
{
     int avg;
     int arr[] = {20, 34, 45, 26, 58, 33}; /* Array of ages */
     avg = average(arr); /* calling function average */
     printf("Average Age = %d\n",avg);
     system("PAUSE"); 
     return 0;
}

/* Function Definition - Average() */
int average(int a[])
{
     int i;
     int avg, sum=0; /* local variables */
     for(i=0;i<6;i++)
     {
       sum = sum + a[i];
     }
     avg = (sum/6);
     return avg;
}
#include <iostream>
using namespace std;

/* Function declaration */
int average(int arr[]);

int main() {
    int avg;
    int arr[] = {20, 34, 45, 26, 58, 33};   /* Array of ages */

    avg = average(arr);   /* calling function */
    cout << "Average Age = " << avg << endl;

    return 0;
}

/* Function Definition - average() */
int average(int a[]) {
    int sum = 0;

    for (int i = 0; i < 6; i++) {
        sum += a[i];
    }

    return sum / 6;
}
public class AverageAge {

    /* Function to calculate average */
    static int average(int[] a) {
        int sum = 0;

        for (int i = 0; i < 6; i++) {
            sum += a[i];
        }

        return sum / 6;
    }

    public static void main(String[] args) {
        int avg;
        int[] arr = {20, 34, 45, 26, 58, 33};   /* Array of ages */

        avg = average(arr);   /* calling function */
        System.out.println("Average Age = " + avg);
    }
}
# Function to calculate average
def average(a):
    sum = 0
    for i in range(6):
        sum += a[i]
    return sum // 6

# Main program
arr = [20, 34, 45, 26, 58, 33]   # Array of ages
avg = average(arr)

print("Average Age =", avg)

Output

The output of the above program is given below. The average age is 36 because:

\begin{aligned} &20 + 34 + 45 + 26 + 58 + 33 \\
&= \frac{216}{6}\\
&= 36
\end{aligned}

Therefore, the program works fine.

Average Age = 36
Press any key to continue . . . 
post

C Program To Output Current Date And Time

C programming language has several predefined macros. In this article we will demonstrate the usage of two important macros.

Before you begin with the example, learn C programming basics. If you know them already, skip and continue with the examples.

Problem Definition

As we mentioned earlier, there are two important macros related to Date and Time. This example program demonstrate the usage of these macros.

__DATE__

The data macro expands to a string constant that display date when the preprocessor was run. It display the date in following format – “ Jan 23 2012 “. If it cannot show the data then, display –  “??? ??  ????“.

__TIME__

The time macro expands to a string that shows the current time when the preprocessor ran on the system. It display the time in following format – “12:55:35“. If date cannot be displayed then it shows –  “??? ??  ????”

Program Source Code

#include <stdio.h>
#include <stdlib.h>
int main()
{
     printf("Current Date: %s\n\n",__DATE__);
     printf("Current Time: %s\n\n",__TIME__);
     system("PAUSE"); 
     return 0;
}

Output

Current Date: Jul 11 2018
Current Time: 22:41:38
Press any key to continue . . ._
post

C Program To Write A File

C programming allows to read or write files. In this program, a user will enter some text which will be stored in a file using file operations in C.

Learn C programming concepts, before you begin with this example.

Problem Definition

The program demonstrate the C language ability to write to file and it is achieved with the help of following C language features.

FILE – a file structure data type which is usually hidden from users.

fopen() – builtin function to open a file in buffer, so that you can read or write to file.

fprintf() – a print function to write to file from console.

fclose() – close the file and file pointer.

Program Source Code

Before you start executing the program, make sure you have created a file called demo.txt in the same directory where the program resides.

#include <stdio.h>
#include <stdlib.h>
int main()
{
    char c[1000];
    FILE *fptr;
    fptr = fopen("demo.txt","w");
    if(fptr == '\0')
    {
        printf("Error!!\n");
        exit(1);
    }
    printf("Enter a Sentence:\n\n");
    gets(c);
        fprintf(fptr,"%s", c);
        fclose(fptr);
    system("PAUSE"); 
    return 0;
}

Output

When run the program, it will ask for a sentence from user as input. See the diagram below, type the sentence you want to write to the file and press enter.

Enter a Sentence:

OMG ! This is a big red horse.
Press any key to continue . . . 

You must go to the directory where the C program resides and open the file – demo.txt. The content of the console is written to the file successfully.

Output - Program to Write to a File
Output – Program to Write to a File
post

Program To Compute Sum Of Geometric Progression

In this post, you will learn to write a program to compute sum of geometric progression.

A geometric progression is a sequence of numbers where each term is obtained by multiplying the previous term by a fixed number, called the common ratio.

The program receive two numbers and compute the sum of geometric progression.

How does the program works?

The program does the following:

  1. Implements the geometric progression ,
  2. Compute the input values when it receives it,
  3. Output the results.

Problem Definition

A geometric progression has two conditions.

  1. \Large a_1 = a where \Large a is the first term and not equal to \Large 0.
  2. \Large a_n = a_{n-1}r for \Large n \geq 1

\Large r is called the common ratio.

\Large \begin{aligned} &Suppose \hspace{2px} a = 1 \hspace{4px} and\hspace{4px}  r = 5, \hspace{2px} then\\ \\&a_1=1\\ &a_2= 5,\\&a_3=25\\& a_4= 125\end{aligned}

Basically, you can compute any term using the following formula.

\Large \begin{aligned}a_n \hspace{1ex} = \hspace{1ex} a \cdot \hspace{1ex} r_{n-1}\end{aligned}

The summation of a geometric progression is given below.

 \Large \begin{aligned} 1\hspace{1ex} + \hspace{1ex} x \hspace{1ex} + \hspace{1ex} x^2\hspace{1ex} + \hspace{1ex} x^3 \hspace{1ex} + \hspace{1ex} x^4 \hspace{1ex} + \hspace{1ex} \cdots \hspace{1ex} + \hspace{1ex} x^{n-1} \hspace{1ex} \cdots\end{aligned}

The summation can be translated into a program for any given \Large x value and \Large n value.

The program for geometric series is given below.

Program Source Codes

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
    int geo_sum, i, x,n;
    geo_sum = 1;
    printf("Enter the value for x:");
    scanf("%d",&x);
    printf("Enter the value for n:");
    scanf("%d",&n);
if(n <= 0 || x <= 0)
{
    printf("Incorrect Value!!\n\n");
}
else
{
    printf("The value is valid!!\n\n");
}
for(i = 1;i <= n; i++)
{
    geo_sum = geo_sum + pow(x,i);
}
printf("The Sum of Series = %d\n",geo_sum);
system("PAUSE"); 
return 0;
}
#include <iostream>
#include <cmath>
using namespace std;

int main()
{
    int x, n;
    long long geo_sum = 1;

    cout << "Enter the value for x: ";
    cin >> x;

    cout << "Enter the value for n: ";
    cin >> n;

    if (n <= 0 || x <= 0)
    {
        cout << "Incorrect Value!!" << endl;
        return 0;
    }
    else
    {
        cout << "The value is valid!!" << endl;
    }

    for (int i = 1; i <= n; i++)
    {
        geo_sum += pow(x, i);
    }

    cout << "The Sum of Series = " << geo_sum << endl;
    return 0;
}
import java.util.Scanner;

class GeometricSeries
{
    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);
        int x, n;
        long geo_sum = 1;

        System.out.print("Enter the value for x: ");
        x = sc.nextInt();

        System.out.print("Enter the value for n: ");
        n = sc.nextInt();

        if (n <= 0 || x <= 0)
        {
            System.out.println("Incorrect Value!!");
            return;
        }
        else
        {
            System.out.println("The value is valid!!");
        }

        for (int i = 1; i <= n; i++)
        {
            geo_sum += Math.pow(x, i);
        }

        System.out.println("The Sum of Series = " + geo_sum);
        sc.close();
    }
}
import math

geo_sum = 1

x = int(input("Enter the value for x: "))
n = int(input("Enter the value for n: "))

if n <= 0 or x <= 0:
    print("Incorrect Value!!")
else:
    print("The value is valid!!")
    for i in range(1, n + 1):
        geo_sum += math.pow(x, i)

    print("The Sum of Series =", int(geo_sum))

Output

The input values for the program is \Large r = x = 2 and \Large n = 10. If we use the values in the geometric expression as follows.

1 + 2 + 22 + 23 + 24 + 25 + 26 + 27 + 28 + 29
= 1  + 2 + 4 + 8 + 16 + 32 + 64 + 128 + 256 + 512 + 1024
= 2047

Therefore, the output is correct.

Enter the value for x:2
Enter the value for n:10
The value is valid!!
The Sum of Series = 2047
Press any key to continue . . . _
post