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

C Program to demonstrate usage of #error directive

The #error directive is one of the C preprocessor directives whose purpose is to stop the compilation process when a violation of constraint is found.

This program demonstrates the use of #error directive in Turbo C++ that is running on a DOS Box 0.74 system running on a Windows 7 64-bit PC.

Problem Definition

In this program, we are trying to write a program for finding q square-root of a number. To find square root we need a function called sqrt() which is part of Math.h header file.

The header file is not included in the programming which is an error. The #error directive will find this error and throw a user-defined message before terminating the compilation process.

Program Code – #error

#include <stdio.h>
#include <stdlib.h>
#ifndef _MATH_H
#error First include header file then compile
#else
main()
{

    float a,b = 25;
          a = sqrt(b);

          printf("%f\n",a);

          return 0;

}

#endif

Output – #error directive

The output from the program is a compilation error – #error directive in turbo C++ compiler.

First include header file then compile
post

C Program to Find Area of Square using Macro

This is a simple demonstration of a Macro in C language. This is program is written using Turbo C++ Compiler installed on a Windows XP 64-bit system. You can compile and run this program using an standard C compiler.

This program is intended for intermediate level learners who know how to write a complex C program.

Problem Definition

The program to compute the area of a square use a C macro called ” area (r) r * r “ where r is a parameter which can be replaced with any variable.

Macro code gets replaced directly where they appear within the program and then executed as regular C tokens.

The are declared and defined at the beginning of a C program using #define keyword.

The area(r) receives a variable value called “Length_of_Side” for a square and computes the area of a square.

Program Code

/* Program to find area of square using Macro in c */

#include <stdio.h>

#include <stdlib.h>

#define area(r) (r * r)

main()
{

    int length_of_side;
    int area_of_square;

/* Read the Length of Side of a Square */

    printf("Enter the length of side in 'cm' of a Square:");
    scanf("%d",&length_of_side);

/* Calling Macro area(r) where r is length_of_side */

    area_of_square = area(length_of_side);

    printf("Area of Square = %d",area_of_square);
    printf("cm(square)");

    getch();
    return 0;

}

The program receives the “length of side” in following code.

scanf("%d", &length_of_side);

The length of side is an integer data type.

The area of square is computed using following macro.

area of square = area(lenght_of_side);

It is quickly replaced with r * r and area of square is computed.

Output

Enter the length of side in 'cm' of a square:12
Area of Square = 144cm(square)
post

C Program to implement Insertion Sort Algorithm

Algorithms are the backbone of programs and they are studied deeply by computer science students. Each algorithm can perform a specific task. Sometimes we have to choose a specific and better performing algorithm out of many similar functioning algorithms.

In this article, I will demonstrate the implementation of a sorting algorithm called Insertion Sort. This program is written using Dev-C++ compiler version 4.9.9.2 installed on a windows 7 64-bit machine.

Since the nature of problem is advanced, the article is for intermediate to advanced C learners.

Problem Definition

Given an array of unsorted numbers, this algorithm sort them in ascending or descending order. To discuss the merit and demerit of this algorithm is not in the scope of this article.The program ask total number of elements and the elements from user and keep them in an array.To sort the array it uses a ‘temp’ variable to store each element of array temporarily.

 
Insertion Sort Algorithm
Insertion Sort Algorithm

From the above figure, you can see that all numbers before temp are sorted because whenever a temp is selected it is compared with all the numbers to its left and inserted in its proper place. All numbers in the right of temp are unsorted and need to be traversed one-by-one.

Flowchart

Flowchart - C Program to Implement Insertion Sort Algorithm
Flowchart – C Program to Implement Insertion Sort Algorithm

Program Code

/* C Program to Implement Insertion Sort Algorithm */

#include <stdio.h>

main()
{

    int n,array[20],temp,i,j;

    printf("Enter the number of elements to enter:");
    scanf("%d",&n);

/* enter elements into the array */

    for(i=0;i<n;i++) {

        printf("Enter the element in to the array:");
        scanf("%d",&array[i]);

    }

    for(i=1;i<n;i++) { 

        j = i; 

        while(j > 0 && array[j] < array[j-1]) 
        {

            temp = array[j];
            array[j]= array[j-1];
            array[j-1] = temp;
            j--;

        }

}

    for(i=0;i<n;i++) {

        printf("%d\t",array[i]);

        }

    system("PAUSE");

    return 0;

}

Output

Enter the number of elements to enter:8
Enter the element in to the array:4
Enter the element in to the array:35
Enter the element in to the array:66
Enter the element in to the array:55
Enter the element in to the array:3
Enter the element in to the array:55
Enter the element in to the array:23
Enter the element in to the array:12

3     4    12   23    35     55     55     66
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 Determinant of a 3 x 3 Matrix

The program receives a \Large 3 \times 3 matrix and computes the determinant and prints the results. The user provides the values for the matrix.

You must be familiar with the concept of the matrix and its determinant to understand this example. See the problem definition section for a brief introduction.

Visit our Linear algebra hub page to learn these concepts.

Problem Definition

The determinant of a \Large 3 \times 3 matrix is easy to calculate. Before we dive into the code, let’s understand the procedure to calculate the determinant of a \Large 3 \times 3 matrix.

Suppose you are given a \Large 3 \times 3 matrix like one given below.

3 x 3 Matrix

The next step is to find the co-factor of \Large A_{11}, A_{21} and \Large A_{31}.

\Large \begin{aligned}& A_{11} \hspace{1ex} = \hspace{1ex} a_1 (b_2 \hspace{1ex} \cdot \hspace{1ex} c_3 \hspace{1ex} - c_2 \hspace{1ex} \cdot b_3 )\\ \\
&A_{21} \hspace{1ex} = \hspace{1ex} -a_2(b_1 \hspace{1ex} \cdot \hspace{1ex} c_3 \hspace{1ex} - c_1 \hspace{1ex} \cdot b_3) \\ \\
&A_{31} \hspace{1ex} = \hspace{1ex} a_3(b_1 \hspace{1ex} \cdot \hspace{1ex} c_2 \hspace{1ex} - c_1 \hspace{1ex} \cdot \hspace{1ex} b_2)
\end{aligned}

Now the value of determinant for \Large 3 \times 3 matrix is

\Large \begin{aligned}&Determinant \hspace{1ex} = \hspace{1ex} a_1(b_2 \hspace{1ex} \cdot \hspace{1ex} c_3 \hspace{1ex} - \hspace{1ex} c_2 \hspace{1ex} \cdot \hspace{1ex}  b_3) \hspace{1ex} \\ \\ &\hspace{1ex}- a_2(b_1 \hspace{1ex} \cdot \hspace{1ex} c_3 \hspace{1ex} - \hspace{1ex} c_1 \hspace{1ex} \cdot \hspace{1ex} b_3) \\ \\ &\hspace{1ex} + \hspace{1ex} a_3( b_1 \hspace{1ex} \cdot \hspace{1ex} c_2 \hspace{1ex} -\hspace{1ex} c_1 \hspace{1ex} \cdot \hspace{1ex} b_2)\end{aligned}

Program Code – Determinant of 3 x 3 Matrix

/*Program to compute the determinant of a matrix */

#include <stdio.h>

#include <stdlib.h>

int main()
{

    int a[3][3],i,j,m,n,detval;

    int r1,r2,r3;

    r1 = 0;

    r2 = 0;

    r3 = 0;

    detval = 0;

    printf("Enter Elements of Matrix Row wise:\n");

    for(i=0;i<3;i++)
    {

        for(j=0;j<3;j++)
        {

            scanf("%d",&a[i][j]);

        }

    }

    r1 = a[0][0] * ((a[1][1] * a[2][2]) 
    - (a[2][1] * a[1][2]));

    r2 = a[0][1] * ((a[1][0] * a[2][2]) 
    - (a[2][0] * a[1][2]));

    r3 = a[0][2] * ((a[1][0] * a[2][1]) 
    - (a[2][0] * a[1][1]));

    detval= r1 - r2 + r3;

    printf("Determinant=%d\n",detval);

    system("PAUSE");

    return 0;

}
#include <iostream>
using namespace std;

int main() {
    int a[3][3], i, j;
    int r1, r2, r3, detval;

    cout << "Enter Elements of Matrix Row wise:\n";
    for (i = 0; i < 3; i++)
        for (j = 0; j < 3; j++)
            cin >> a[i][j];

    r1 = a[0][0] * ((a[1][1] * a[2][2]) - (a[2][1] * a[1][2]));
    r2 = a[0][1] * ((a[1][0] * a[2][2]) - (a[2][0] * a[1][2]));
    r3 = a[0][2] * ((a[1][0] * a[2][1]) - (a[2][0] * a[1][1]));

    detval = r1 - r2 + r3;

    cout << "Determinant = " << detval << endl;

    return 0;
}
import java.util.Scanner;

class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int[][] a = new int[3][3];
        int r1, r2, r3, detval;

        System.out.println("Enter Elements of Matrix Row wise:");
        for (int i = 0; i < 3; i++)
            for (int j = 0; j < 3; j++)
                a[i][j] = sc.nextInt();

        r1 = a[0][0] * ((a[1][1] * a[2][2]) - (a[2][1] * a[1][2]));
        r2 = a[0][1] * ((a[1][0] * a[2][2]) - (a[2][0] * a[1][2]));
        r3 = a[0][2] * ((a[1][0] * a[2][1]) - (a[2][0] * a[1][1]));

        detval = r1 - r2 + r3;

        System.out.println("Determinant = " + detval);
        sc.close();
    }
}
a = [[0]*3 for _ in range(3)]

print("Enter Elements of Matrix Row wise:")
for i in range(3):
    for j in range(3):
        a[i][j] = int(input())

r1 = a[0][0] * ((a[1][1] * a[2][2]) - (a[2][1] * a[1][2]))
r2 = a[0][1] * ((a[1][0] * a[2][2]) - (a[2][0] * a[1][2]))
r3 = a[0][2] * ((a[1][0] * a[2][1]) - (a[2][0] * a[1][1]))

detval = r1 - r2 + r3

print("Determinant =", detval)

Output

When the program executes, it ask for input values for the matrix. You must enter the values row-wise. Upon entering the values, it computes the determinant and prints the output to the console.

You can enter negative values too, the compiler will consider that as an negative integer value.The output value as you can see is a negative integer value of \Large -11.

You can verify the answer by doing the math on a paper and compare the results with program output. Try solving for different values for matrix.

Enter Elements of Matrix Row Wise:
1 4 5
1 3 1
2 3 1
Determinant=-11
Press any key to continue . . . _
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

C Program to Implement Student Database using Structure

This program is written using DEV C++ version 5. You can use any other standard C compiler to compile and run this program.

The best way to learn programming is to do lot of practice writing programs and understanding the logic behind achieving the solution to the problems. In this way you can easily master the programming skills.

AIM

 

To write a program in C that implement Student database using Structures.

PROGRAM

 

 

  1 
  2 
  3 
  4 
  5 
  6 
  7 
  8 
  9 
 10 
 11 
 12 
 13 
 14 
 15 
 16 
 17 
 18 
 19 
 20 
 21 
 22 
 23 
 24 
 25 
 26 
 27 
 28 
 29 
 30 
 31 
 32 
 33 
 34 
 35 
 36 
 37 
 38 
 39   
 40 
 41 
 42 
 43 
 44 
 45 
 46 
 47 
 48 
 49 
 50 
 51 
 52 
 53 
 54  
 55 
 56 
 57 
 58 
 59 
 60 
 61 
 62 
 63 
 64 
 65 
 66 
 67 
 68 
 69 
 70 
 71 
 72 
 73 
 74 
 75 
 76 
 77 
 78 
 79 
 80 
 81 
 82 
 83 
 84 
 85 
 86 
 87 
 88 
 89 
 90 
 91 
 92 
 93 
 94 
 95 
 96 
 97 
 98  
 99 
100 
101  
102 
103 
104  
105 
106 
107 
108 
109 
110 
111 
112  
113 
114 
115 
116 
117 
118 
119 
120 
121 
122 
123 
124 
125 
126  
127 
128 
129 
130 
131 
132 
133 
134 
135 
136 
137 
138 
139 
140 
141 
142 
143 
144 
145
/* Write a program for maintaining record of 'n' students using structure */

#include <stdio.h>

#include <stdlib.h>

#include <conio.h>

struct Student{

int rollno;

char name[15];

int marks;

char grade;

} ;

int main()

{

struct Student s1[10];

int i,n;

char search[15];

/* Read student information */

printf(“How many Student Records to Store:n);

scanf(“%d”,&n);

/* Enter student details */

printf(“Enter Student Details:n);

for(i=0;i<n;i++)

{

printf(“Rollno:”);

scanf(“%d”,&s1[i].rollno);

printf(n);

printf(“Name:”);

scanf(“%s”,&s1[i].name);

printf(n);

printf(“Marks(in %):”);

scanf(“%d”,&s1[i].marks);

printf(n);

printf(“Grade:”);

if(s1[i].marks <=50)

{

s1[i].grade = ‘F’;

}

else if(s1[i].marks > 50 && s1[i].marks <= 59)

{

s1[i].grade = ‘C’;

}

else if(s1[i].marks >=60 && s1[i].marks <= 75)

{

s1[i].grade = ‘B’;

}

else if(s1[i].marks > 75 && s1[i].marks <= 95)

{

s1[i].grade = ‘A’;

}

else

{

s1[i].grade = ‘S’;

}

printf(“%ct,s1[i].grade);

printf(n);

}

printf(“Enter Student Name to Search:”);

scanf(“%s”,&search);

/* print the data base */

printf(” Namett Markst Gradetn);

for(i=0;i<n;i++)

{

if(strcmp(search,s1[i].name)== 0 )

{

printf(“%stt %dt,search,s1[i].name);

}

else if(search == “all”)

{

printf(“%stt %dt,search,s1[i].name);

}

}

system(“PAUSE”);

return 0;

}

OUTPUT

OUTPUT FROM STUDENT MARK DATABASE
post

C Program To Draw Bar Diagram With Data

In this article, you will learn to write a C program to draw bar diagram with data input by user.

This program is written using Turbo C++ compiler installed on a Windows 7 64-bit PC. The compiler supports C language and the header Graphics.h is used to draw the chart.

Problem Definition

In this C example program, you will do following task:

  • Ask user to input data for the bar diagram.
  • Initialize the graph.
  • Choose correct position on the screen to draw the graph.
  • Write the labels for bars.
  • Draw the bars according to data input by user.
  • Close the graph.

For the purpose of this example:

In a university the number of application received in last five years is given below. Write a C program to display the data using bar chart.

YearNumber of Students
201320
2014100
201570
201650
2017120

Program Code – Bar Diagram With Data

/* C++ Program To Display following data:
 Year     No. Of Students
 2013           20
 2014           100
 2015           70
 2016           50
 2017           120
 ------------------------------ */
 include "graphics.h"
 include "stdlib.h"
 include "stdio.h"
 include "conio.h"
 include "dos.h"
 int main(void)
 {
    int gdriver=DETECT, gmode;
    int n,i,x1,x2,y1,y2, yr = 1950;
 /* Initialize the Graph */
 initgraph(&amp;gdriver,&amp;gmode,"D:\TurboC3\BGI");
 /* Initialize the variable */
 x1 = 50;
    x2 = 50;
    y1 = 350;
    y2 = 350;
 clrscr();
 /* Display the data label year */
 outtextxy(90,375,"1950");
    outtextxy(140,375,"1955");
    outtextxy(190,375,"1960");
    outtextxy(240,375,"1965");
    outtextxy(290,375,"1970");
    printf("\t\t\tBAR CHART\n");
 /* Set Color of the bar chart */
 setfillstyle(SOLID_FILL,RED);
 /* Display the data */
 for(i=1;i&lt;=5;i++)
    {
       printf("\nYear = %d Students:",yr);
       scanf("%d",&amp;n);
   y2=y2-n;   x2=x2+50;   x1=x2+10;   bar(x1,y1,x2,y2);   yr=yr+5;   y2 = 350;
 }
 /* Close the Graph */
 getch();
    closegraph();
    return 0;
    }

Output – Bar Diagram With Data

Bar Chart With Data
post