Program to Reverse a Number using Recursion

The program uses recursion to reverse an input number. A function is recursively called to extract each digit from the number and place it in reverse order. The final output is a reversed number.

Problem Definition

The program receives an input number and reverse each by extracting the digits one at a time from original number n. It starts with two initial conditions. The remainder r = 0 and if n=0 then return 0.

The procedure to reverse the number 567 is shown below. The program does the following tasks to reverse the input number.

  1. Extract a digit from the unit position.
  2. Each iteration multiply the number with 10 to reverse it.
  3. Next extracted digit is added to previously obtained result.
  4. After final extraction the number is completely reversed.

Go through each step below to understand the working of the reverse() function.

Step 1: Extract the number 7

\begin{aligned}&r = r + n \hspace{2mm}\% \hspace{2mm}10\\ \\
&r = 0 + 567 \hspace{2mm}\% \hspace{2mm}10\\ \\ 
&t = 7
\end{aligned}

Step 2: Change the position of a number from unit place to tenth place.

\begin{aligned}
&r = r * 10\\ \\
& r = 7 * 10\\ \\
 &r = 70
\end{aligned}

Step 3: Get ready for the next extraction.

\begin{aligned}
&= reverse (n/10)\\ \\
&= reverse (567/10)\\ \\
&= reverse (56)
\end{aligned}

Step 4: Extraction the second digit when value of r = 70 from Step 2.

\begin{aligned}
&r = 70 + n \% 10\\ \\
&r = 70 + 56 \% 10\\ \\
&r = 70 + 6\\ \\
&r = 76
\end{aligned}

Step 5: Change position of r to tenth place to hundredth place.

\begin{aligned} &r = r * 10\\ \\
&r = 76 * 10\\ \\
&r = 760
\end{aligned}

Step 6: Get ready for a new n value.

\begin{aligned}
&= reverse (n/10)\\ \\
& = reverse ( 56/1)\\ \\
& = reverse (5)
\end{aligned}

Step 7: Extract last digit from original number, when r = 760

\begin{aligned}
&r = r + n \% 10\\ \\ 
& r = 760 + 5\\ \\
&r = 765
\end{aligned}

The number is successfully reversed.

Note:- The above steps are demonstration of reversing a 3 digit number, hence, the number of steps are limited. If you take a larger number there will be more steps.

Flowchart – reverse a number using recursion

Figure 1 - Flowchart for Reverse Number using recursion
Figure 1 – Flowchart for Reverse Number using recursion

Program Codes – reverse a number using recursion

#include 
#include 
int reverse(int);
int main()
{
        int n, r, i;
        printf("Enter a Number to Reverse:");
        scanf("%d", & n);
        r = reverse(n);
        for (i = 0; i < 30; i++)
            printf("_"); printf("\n\n");
            printf("%d\n\n", r);
        for (i = 0; i < 30; i++)
            printf("_"); printf("\n\n");
        system("PAUSE");
        return (0);
}
/* The Reverse Function */
int reverse(int n)
{
        static long r = 0;
        if (n == 0)
        {
            return 0;
        }
        r = r * 10;
        r = r + n % 10;
        reverse(n / 10);
        return r;
}
#include <iostream>
using namespace std;

long reverse(int n)
{
    static long r = 0;   // static variable to retain value
    if (n == 0)
        return 0;

    r = r * 10 + (n % 10);
    reverse(n / 10);
    return r;
}

int main()
{
    int n;
    long r;

    cout << "Enter a Number to Reverse: ";
    cin >> n;

    r = reverse(n);

    for (int i = 0; i < 30; i++)
        cout << "_";
    cout << "\n\n";

    cout << r << "\n\n";

    for (int i = 0; i < 30; i++)
        cout << "_";
    cout << "\n";

    return 0;
}
import java.util.Scanner;

class ReverseNumber {

    static long r = 0;   // static variable

    static long reverse(int n) {
        if (n == 0) {
            return 0;
        }
        r = r * 10 + (n % 10);
        reverse(n / 10);
        return r;
    }

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

        System.out.print("Enter a Number to Reverse: ");
        int n = sc.nextInt();

        long result = reverse(n);

        for (int i = 0; i < 30; i++)
            System.out.print("_");
        System.out.println("\n");

        System.out.println(result + "\n");

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

        sc.close();
    }
}
def reverse(n, r=0):
    if n == 0:
        return r
    return reverse(n // 10, r * 10 + n % 10)


n = int(input("Enter a Number to Reverse: "))
result = reverse(n)

print("_" * 30)
print("\n", result, "\n")
print("_" * 30)

Output

The program ask for an input number, when you enter a number – for example, 244. The program reverses the digits of the number and prints on the console. The solution is 442.

Enter a Number to Reverse: 244
_______________________________
442
_______________________________
post

Program To Identify A Quadrilateral

The program to identify a quadrilateral read inputs – length of sides and angles made by the quadrilateral shape and prints the shape name as output.

Before you practice this program, you must go through the concepts of quadrilateral shapes and their differences. See the next section.

Problem Definition

A quadrilateral is a polygon shape that has \Large 4 sides and corners that make \Large 4 angles. The sum of those angles must be equal to \Large 360 \hspace{4px} degrees. There are many types of quadrilateral shapes, you will find a brief description of each shape below.

Square

A square has \Large 4 equal sides and \Large 4 right angles at each corner.

A Square
A Square

Rectangle

A rectangle has \Large 4 sides with parallel sides are of the same length and \Large 4 corners are right angles. The rectangle has a longer side and a shorter side.

A Rectangle
A Rectangle

Rhombus

A rhombus is like a square or diamond with \Large 4 equal sides, but none of the corners is a right angle.

A Rhombus
A Rhombus

Parallelogram

Any quadrilateral that has two pair of parallel sides is a parallelogram. There are shapes which demonstrate properties of parallelogram – square, rectangle, and a rhombus are special case of a parallelogram.

In general, parallelogram has:

  • Opposite sides are parallel
  • Opposite sides are equal
  • Opposite angles are equal
A Paralleogram
A Parallelogram

Trapezoid

If a quadrilateral contains at least one pair of parallel lines then it is called a trapezoid.

A Trapezoid
A Trapezoid

Kite

A kite is a quadrilateral that has a pair of adjacent sides of equal length and the angle where these two pair meet are equal.

A Kite Diagram
A Kite Diagram

Flowchart

Figure 1 - Flowchart for program to Identify a Quadrilateral
Figure 1 – Flowchart for program to Identify a Quadrilateral

Program Codes – Program to Identify Quadrilateral

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

int main()
{
    float side[4], angle[4];
    float sum = 0;
    int i, right = 0, equal = 0;

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

    printf("Enter 4 angles:\n");
    for (i = 0; i < 4; i++)
    {
        scanf("%f", &angle[i]);
        sum += angle[i];
        if (fabs(angle[i] - 90) < 0.001)
            right++;
    }

    if (fabs(sum - 360) > 0.001)
    {
        printf("Invalid quadrilateral\n");
        return 0;
    }

    for (i = 1; i < 4; i++)
        if (fabs(side[i] - side[0]) < 0.001)
            equal++;

    if (equal == 3 && right == 4)
        printf("Square\n");
    else if (right == 4 && side[0] == side[2] && side[1] == side[3])
        printf("Rectangle\n");
    else if (equal == 3)
        printf("Rhombus\n");
    else if (side[0] == side[2] || side[1] == side[3])
        printf("Parallelogram\n");
    else
        printf("Trapezoid\n");

    return 0;
}
#include <iostream>
#include <cmath>
using namespace std;

int main()
{
    float side[4], angle[4], sum = 0;
    int right = 0, equal = 0;

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

    cout << "Enter 4 angles:\n";
    for (int i = 0; i < 4; i++)
    {
        cin >> angle[i];
        sum += angle[i];
        if (fabs(angle[i] - 90) < 0.001)
            right++;
    }

    if (fabs(sum - 360) > 0.001)
    {
        cout << "Invalid quadrilateral\n";
        return 0;
    }

    for (int i = 1; i < 4; i++)
        if (fabs(side[i] - side[0]) < 0.001)
            equal++;

    if (equal == 3 && right == 4)
        cout << "Square\n";
    else if (right == 4 && side[0] == side[2] && side[1] == side[3])
        cout << "Rectangle\n";
    else if (equal == 3)
        cout << "Rhombus\n";
    else if (side[0] == side[2] || side[1] == side[3])
        cout << "Parallelogram\n";
    else
        cout << "Trapezoid\n";

    return 0;
}
import java.util.Scanner;

class Quadrilateral {
    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        float[] side = new float[4];
        float[] angle = new float[4];
        float sum = 0;
        int right = 0, equal = 0;

        System.out.println("Enter 4 sides:");
        for (int i = 0; i < 4; i++)
            side[i] = sc.nextFloat();

        System.out.println("Enter 4 angles:");
        for (int i = 0; i < 4; i++) {
            angle[i] = sc.nextFloat();
            sum += angle[i];
            if (Math.abs(angle[i] - 90) < 0.001)
                right++;
        }

        if (Math.abs(sum - 360) > 0.001) {
            System.out.println("Invalid quadrilateral");
            return;
        }

        for (int i = 1; i < 4; i++)
            if (Math.abs(side[i] - side[0]) < 0.001)
                equal++;

        if (equal == 3 && right == 4)
            System.out.println("Square");
        else if (right == 4 && side[0] == side[2] && side[1] == side[3])
            System.out.println("Rectangle");
        else if (equal == 3)
            System.out.println("Rhombus");
        else if (side[0] == side[2] || side[1] == side[3])
            System.out.println("Parallelogram");
        else
            System.out.println("Trapezoid");

        sc.close();
    }
}
side = []
angle = []
sum_angle = 0
right = equal = 0

print("Enter 4 sides:")
for _ in range(4):
    side.append(float(input()))

print("Enter 4 angles:")
for _ in range(4):
    a = float(input())
    angle.append(a)
    sum_angle += a
    if abs(a - 90) < 0.001:
        right += 1

if abs(sum_angle - 360) > 0.001:
    print("Invalid quadrilateral")
    exit()

for i in range(1, 4):
    if abs(side[i] - side[0]) < 0.001:
        equal += 1

if equal == 3 and right == 4:
    print("Square")
elif right == 4 and side[0] == side[2] and side[1] == side[3]:
    print("Rectangle")
elif equal == 3:
    print("Rhombus")
elif side[0] == side[2] or side[1] == side[3]:
    print("Parallelogram")
else:
    print("Trapezoid")

Output

Enter 4 sides:
20
20
20
20
Enter 4 angles:
90
90
90
90

Square
Enter 4 sides:
12
24
12
24
Enter 4 angles:
60
120
60
120

Parallelogram
post

Program For Law Of Sine Problems

With the law of sine, you can find any unknown angle of a given triangle or the length of a particular side of a triangle or the length of a particular side of a triangle.

We will see two cases while using law of sine.

  1. When length of 2 sides and 1 angle is given.
  2. When 2 angles and 1 side is given.

Problem Definition

The law of sine is given below. The triangle has three sides \Large a, \hspace{1ex} b and \Large c ; It also has three angles – \Large \angle A, \hspace{1ex} \angle B and \Large \angle C.

Figure1: Law of Sine for a Triangle
Figure1: Law of Sine for a Triangle

In general, there are two cases for problems involving the law of sine.

Case 1: When the length of two sides is given and the angle opposite to one of the sides with length is given.

Figure2: Law of sine for two sides and 1 angle
Figure2: Law of sine for two sides and 1 angle

When the length of two side – \Large A and \Large B are given and the angle opposite to side \Large A is given. Then using law of sine

\Large \begin{aligned}&X \hspace{1ex} = \hspace{1ex} sin \hspace{1ex} \frac{A}{a}\\ \\
&sin  \hspace{1ex}\frac{B}{b} \hspace{1ex} = \hspace{1ex} X\\ \\
&sin \hspace{1ex} B \hspace{1ex} =\hspace{1ex}  X \hspace{1ex}\ast \hspace{1ex}b\\ \\
&\angle {B }\hspace{1ex} = \hspace{1ex} arcsin ( X \ast b)
\end{aligned}

This the way to find the value of sin \Large B and then using arcsin to find the \Large \angle B.

Case 2: When 2 angles – angle A and angle B are given with length of the side opposite to angle A or angle B.

When two angles and length of at least one side opposite to \Large \angle A or \Large \angle B is given. Find the \Large sin \hspace{3px} A and \Large sin \hspace{3px} B values first.

Find \Large X \hspace{1ex} = \frac{\Large sin \hspace{3px} A}{\Large a} or \frac{\Large sin \hspace{3px} B}{\Large b}, whichever is given in the problem.

The length of side

\Large \begin{aligned}b \hspace{1ex} = \hspace{1ex} sin\hspace{2px} B \cdot X\end{aligned}

This is how you will find the value of the length of side \Large b when \Large \angle A and \Large\angle B is given along with the length of side \Large a.

Figure 3: Two Angles and 1 Side for Law of Sine Problems
Figure 3: Two Angles and 1 Side for Law of Sine Problems

In next section, you will find the flowchart of the program for the law of sine and the above two cases to understand the logic of the program.

Flowchart – Program for Law of Sine Problems

Flowchart Sine Law
Flowchart Sine Law

The next flowchart is of function \Large s1() which covers the case 1 of the law of sine problems.

Flowchart Sine Law 2 Sides and 1 Angle
Flowchart Sine Law 2 Sides and 1 Angle

The flowchart for function \Large s2 () that covers the case 2 of the law of sine problems is given below.

Flowchart Sine Law 2 Angle and 1 Side
Flowchart Sine Law 2 Angle and 1 Side

Program Codes – Program for Law of Sine Problems

/* C Program for solving law of sine problems */
#include <stdio.h>
#include <math.h>
#include<stdlib.h>
/* Variable declarations */
        int ch,i;
        float a, b, q, p, deg;
        float angle,angle2, res;
/* Function declaration */
        void s1();
        void s2();
int main()
{
        for(i=0;i < 30;i++)
        printf("*");printf("\n\n");
        printf("\tMenu\n\n");
        for(i=0;i < 30;i++)
        printf("*");printf("\n\n");
                printf("1.Sine Problem with 2 Sides and 1 Angle:\n");
                printf("2.Sine Problem with 2 Angles and 1 Side:\n");
                printf("3.Quit using any other number:\n\n");
        for(i=0;i < 30;i++)
        printf("*");printf("\n\n");
        while(1)
        {
                 printf("Enter your Choice:");
                 scanf("%d",& ch);
                 if(ch == 1)
                {
                     s1();
                }
                else if(ch == 2)
                {
                     s2();
                }
                else if(ch == 3)
                {
                     exit(0);
                }
               else
               {
                     printf("Wrong choice ! Try again:\n");
               }
        }
               system("PAUSE");
               return 0;
}
/* Main function ends */
/* Function definition - s1() */
void s1()
{
        float pi = 3.141;
        for(i=0;i < 30;i++)
        printf("_");printf("\n\n");
                printf("Enter value for side with angle:");
                scanf("%f",&a);
                printf("Enter value for side without angle:");
                scanf("%f",&b);
                printf("Enter the angle(degrees):");
                scanf("%f",&angle);
        for(i=0;i < 30;i++)
        printf("_");printf("\n\n");
                angle = angle * (pi/180);
                q = sin(angle);
                p = b * (q/a);
                deg = asin(p);
                res = deg * (180/pi);
        for(i=0;i < 30;i++)
        printf("_");printf("\n\n");
                printf("Angle B = %f\n",res);
        for(i=0;i < 30;i++)
        printf("_");printf("\n\n");
}
/* Function definition - s2() */
void s2()
{
        float pi = 3.141;
        for(i=0;i < 30;i++)
        printf("_");printf("\n\n");
                printf("Enter value of side a with angle:");
                scanf("%f",&a);
                printf("Enter angle A for side a:");
                scanf("%f",&angle);
                printf("Enter value angle B of side b:");
                scanf("%f",&angle2);
        for(i=0;i < 30;i++)
                printf("_");printf("\n\n");
                angle = angle * (pi/180);
                angle2 = angle2 * (pi/180);
                q = sin(angle);
                p = sin(angle2);
                deg = q/a;
                b = p/deg;
        for(i=0;i < 30;i++)
        printf("_");printf("\n\n");
                printf("Side b = %f\n",b);
       for(i=0;i<30;i++)
       printf("_");printf("\n\n");
}
/* C++ Program for solving law of sine problems */
#include <iostream>
#include <cmath>
#include <cstdlib>

using namespace std;

/* Global variables */
int ch, i;
float a, b, q, p, deg;
float angle, angle2, res;

/* Function declarations */
void s1();
void s2();

int main()
{
    for (i = 0; i < 30; i++) cout << "*";
    cout << "\n\n\tMenu\n\n";
    for (i = 0; i < 30; i++) cout << "*";
    cout << "\n\n";

    cout << "1. Sine Problem with 2 Sides and 1 Angle\n";
    cout << "2. Sine Problem with 2 Angles and 1 Side\n";
    cout << "3. Quit using any other number\n\n";

    for (i = 0; i < 30; i++) cout << "*";
    cout << "\n\n";

    while (1)
    {
        cout << "Enter your Choice: ";
        cin >> ch;

        if (ch == 1)
            s1();
        else if (ch == 2)
            s2();
        else
            exit(0);
    }
    return 0;
}

void s1()
{
    float pi = 3.141f;

    cout << "\n------------------------------\n";
    cout << "Enter value for side with angle: ";
    cin >> a;
    cout << "Enter value for side without angle: ";
    cin >> b;
    cout << "Enter the angle (degrees): ";
    cin >> angle;

    angle = angle * (pi / 180);
    q = sin(angle);
    p = b * (q / a);
    deg = asin(p);
    res = deg * (180 / pi);

    cout << "Angle B = " << res << "\n";
}

void s2()
{
    float pi = 3.141f;

    cout << "\n------------------------------\n";
    cout << "Enter value of side a with angle: ";
    cin >> a;
    cout << "Enter angle A for side a: ";
    cin >> angle;
    cout << "Enter angle B of side b: ";
    cin >> angle2;

    angle = angle * (pi / 180);
    angle2 = angle2 * (pi / 180);

    q = sin(angle);
    p = sin(angle2);
    deg = q / a;
    b = p / deg;

    cout << "Side b = " << b << "\n";
}
/* Java Program for solving law of sine problems */
import java.util.Scanner;

public class LawOfSine {

    static int ch;
    static float a, b, q, p, deg;
    static float angle, angle2, res;

    static Scanner sc = new Scanner(System.in);

    public static void main(String[] args) {

        for (int i = 0; i < 30; i++) System.out.print("*");
        System.out.println("\n\n\tMenu\n");
        for (int i = 0; i < 30; i++) System.out.print("*");

        System.out.println("\n\n1. Sine Problem with 2 Sides and 1 Angle");
        System.out.println("2. Sine Problem with 2 Angles and 1 Side");
        System.out.println("3. Quit using any other number\n");

        while (true) {
            System.out.print("Enter your Choice: ");
            ch = sc.nextInt();

            if (ch == 1)
                s1();
            else if (ch == 2)
                s2();
            else
                System.exit(0);
        }
    }

    static void s1() {
        float pi = 3.141f;

        System.out.print("Enter value for side with angle: ");
        a = sc.nextFloat();
        System.out.print("Enter value for side without angle: ");
        b = sc.nextFloat();
        System.out.print("Enter the angle (degrees): ");
        angle = sc.nextFloat();

        angle = angle * (pi / 180);
        q = (float) Math.sin(angle);
        p = b * (q / a);
        deg = (float) Math.asin(p);
        res = deg * (180 / pi);

        System.out.println("Angle B = " + res);
    }

    static void s2() {
        float pi = 3.141f;

        System.out.print("Enter value of side a with angle: ");
        a = sc.nextFloat();
        System.out.print("Enter angle A for side a: ");
        angle = sc.nextFloat();
        System.out.print("Enter angle B of side b: ");
        angle2 = sc.nextFloat();

        angle = angle * (pi / 180);
        angle2 = angle2 * (pi / 180);

        q = (float) Math.sin(angle);
        p = (float) Math.sin(angle2);
        deg = q / a;
        b = p / deg;

        System.out.println("Side b = " + b);
    }
}
# Python Program for solving law of sine problems
import math
import sys

def s1():
    pi = 3.141
    a = float(input("Enter value for side with angle: "))
    b = float(input("Enter value for side without angle: "))
    angle = float(input("Enter the angle (degrees): "))

    angle = angle * (pi / 180)
    q = math.sin(angle)
    p = b * (q / a)
    deg = math.asin(p)
    res = deg * (180 / pi)

    print("Angle B =", res)

def s2():
    pi = 3.141
    a = float(input("Enter value of side a with angle: "))
    angle = float(input("Enter angle A for side a: "))
    angle2 = float(input("Enter angle B of side b: "))

    angle = angle * (pi / 180)
    angle2 = angle2 * (pi / 180)

    q = math.sin(angle)
    p = math.sin(angle2)
    deg = q / a
    b = p / deg

    print("Side b =", b)

while True:
    print("\n************** Menu **************")
    print("1. Sine Problem with 2 Sides and 1 Angle")
    print("2. Sine Problem with 2 Angles and 1 Side")
    print("3. Quit")

    ch = int(input("Enter your Choice: "))

    if ch == 1:
        s1()
    elif ch == 2:
        s2()
    else:
        sys.exit()

Outputs from the Program

The program gives three choices during run time

  1. Apply the law of sine when the length of 2 sides and 1 angle opposite to a given side is available.
  2. Apply the law of sine when 2 angles are given and length of 1 side opposite to an angle is given.
  3. Quit the program

The output from both the cases are given below, you should run the program and verify the output for yourself.

                                Menu
***********************************************************************
1.Sine Problem with 2 Sides and 1 Angle:
2.Sine Problem with 2 Angles and 1 Side:
3.Quit using any other number:
***********************************************************************
Enter your Choice:1
_______________________________________________________________________
Enter value for side with angle:5
Enter value for side without angle:4
Enter the angle(degrees):60
_______________________________________________________________________
_______________________________________________________________________
Angle B = 43.855770
_______________________________________________________________________
Enter your Choice:_

Now, we will test option 2 from the menu.

                                Menu
***********************************************************************
1.Sine Problem with 2 Sides and 1 Angle:
2.Sine Problem with 2 Angles and 1 Side:
3.Quit using any other number:
***********************************************************************
Enter your Choice:2
_______________________________________________________________________
Enter value of side a with angle:30
Enter angle A for side a:14
Enter value angle B of side b:55
_______________________________________________________________________
_______________________________________________________________________
Side b = 101.586449
_______________________________________________________________________
Enter your Choice:_
post

C Program to Implement Stack using Linked-List

A stack is an abstract data structure where elements are pushed and deleted from only one end. We call this top of a stack.

This program implement stack using a linked-list structure. The linked-list is a linear list in which you can enter data only from one end. You must always insert from the front of the linked list so that it works like a stack.

The basic stack operations are given below.

  1. Push()
  2. Pop()

The Push () function insert an item into the stack and Pop () deletes the item from top of the stack. In the figure below, items are added to top and deleted from top. This is called Last In, First Out mechanism.

Stack Operations
Stack Operations

Problem Definition

A stack can be implemented using array data structure or a dynamically growing linked-list data structures. The linked-list implementation of stack does not need to check for “stack being full” because the list grows dynamically.

A linked-list has nodes that are linked together using pointers. A linked-list node has a data and a link pointer of type node that points to the next node element in the list.

An example of a node

struct node {
 int data;
 node* next;
};

Steps to build a linked-list based stack is as follows

Step 1: Declare pointers to build initial stack.

 struct node *head, *temp;

The *head pointer of type struct points to the first node of the linked-list and the *temp pointer of type struct points to any new node you create. The pointers are created but does not point to anything. You must point to some variable or allocate memory to initialize them.

Step 2: Initialize the head node.

In C programming language, you must initialize any pointer by dynamically allocating memory using function malloc (). You initialize pointer head as follows

head =(struct node* )malloc( ( struct node))

Now that have assigned memory to the head node, give values to its variables.

head->data=10;
head->next =NULL;

See the following diagram to understand what initializing a node means.

Single Node in Linked-list
Single Node in Linked-list

The head pointer points to a location which has address 0x3000 and data value is 10. The node->next is also a pointer that maintain the linked-list and currently points to NULL.

Step 3: Create a new node and *temp points to it

We now create a new node by allocating memory dynamically for *temp.

temp = (struct node*) malloc ((struct node));

assign values to the variable and point the next pointer to NULL.

temp->data = 20;
temp->next = NULL;

See the memory drawing below to understand the process.

Two Independent Node of Linked List
Two Independent Node of Linked List

Right now, we have two independent nodes, not a linked-list. To start building a list and making sure that the linked-list work like a stack.

Step 4: Now temp nodes must point to head node so that it becomes the first node or head node.

temp->next = head;
Pointer in Action
Pointer in Action
A Linked-List
A Linked-List

Step 5: Write a pop () function that removes the top element.

In the stack, pop () function directly removes the top element automatically. You need to skip the top element and make the second element as the head of the linked-list based stack.

To make a new head use following code

head = head->next;

Flowchart

Flowchart - Stack using Linked List
Flowchart – Stack using Linked List

Program Code – Stack using Linked-List

#include < stdio.h >
#include < stdlib.h >
#include < malloc.h >
struct node
{
    int data;
    struct node * next;
} * head, * temp, * p;
    void push();
    void pop();
int main()
{
    int n, i;
    char ch;
    printf("how many nodes ?:");
    scanf("%d", & n);
    head = (struct node * ) malloc(sizeof(struct node));
 
    printf("Enter a value for node->data:");
    scanf("%d", & head - > data);
    head - > next = NULL;
    for (i = 0; i < n - 1; i++) 
    { 
        push(); 
    } 
        printf("\n\n"); 
        printf("Top = %d \n\n ", head - > data);
        printf("Do you wish to Pop:y/n:");
        scanf("%s", & ch);
    if (ch == 'y')
    {
        pop();
        printf("\n\n");
        printf("new top = %d\n", head - > data);
        printf("\n\n");
    }
    system("PAUSE");
    return 0;
}
void push()
{
    temp = (struct node * ) malloc(sizeof(struct node));
    printf("Enter a value for node->data:");
    scanf("%d", & temp - > data);
    temp - > next =
    head = temp;
}
void pop()
{
    head = head - > next;
}

Output

When you run the program, enter the number of nodes required for linked-list based stack. Then start entering value to the top of the stack. In the following figure, 434 is the last in entry, so it is the top of the stack, also head of the linked-list.

Output- stack using linked-list
Output- stack using linked-list

If you decide to pop() the top element – 434, then the second last entry becomes the top element. In this case, 125 is the new top element.


    post

    C Program to Implement a Stack

    A stack is a common data structure used in many applications. It is an abstract data type defined not by its data type, but by its operations.

    Stack operations are critical to its implementation. We will create a C++ stack using linked-list in this article.

    This program demonstrates the implementation of a stack and its operations using simple functions and the program is compiled using Dev-C++ compiler 4.9.9.2 installed on windows 7 64-bit computer.

    In this article, you will find the following sections – problem definition, flowchart, program source code and verified output to help you learn to programme effectively. Since the level of the program is difficult, it is for intermediate level learners of C programming language.

    Problem Definition

    A stack is a linear data structure with a predefined size. It is possible to increase or decrease the stack size, but that depends on the application using the stack data structure.

    To build a stack data structure, you can use two methods – an array or a linked -list. A fixed size array can work as an array for a simple data type, however, for a stack that uses dynamic memory allocation, we need a linked-list.

    A stack works in a specific way called the LIFO principle –Last in, First out. The last item inserted onto the stack is processed first because items are inserted from the top of the stack and removed from the top first. The stack operations implemented in this program are

    push()

    Whenever you insert on to stack use push () function and the item cannot be inserted if the stack is full. So this check is performed first.

    pop()

    It removes the top item of the stack immediately.

    display()

    This displays the top item of a stack.

    Flowchart – Program to Implement a Stack

    Flowchart - C Program to implement a Stack
    Flowchart – C Program to implement a Stack

    Program Code – Program to Implement a Stack

    /* program to implement stack */
    
    
    #include <stdio.h>
    
        int stack[100],top,size,choice,i,num;
    
    main()
    {
        void push();
        void pop();
        void traverse();
    
        top =0;
    
    /* get the size of stack */
    
    
        printf("ENTER THE SIZE OF STACK:");
        scanf("%d",&size);
    
    
    /* menu for stack */
    
    
        i=0;
    
        while(choice != 4)
        {
    
            printf("n***MENU***\n");
            printf("1.PUSH:\n");
            printf("2.POP:\n");
            printf("3.DISPLAY:\n");
            printf("4.QUIT:\n");
            printf("ENTER YOUR CHOICE:");
    
            scanf("%d",&choice);
            i++ ;
    
        switch(choice)
        {
    
            case 1:
    
                push(stack,top,size);
                break;
    
            case 2:
    
                pop(stack,top);
                break;
    
            case 3:
    
                traverse();
                break;
    
            case 4:
    
                exit(0);
    
            default:
    
        for(i=0;i<35;i++)
        printf("_");printf("\n\\n");
    
        printf("WRONG CHOICE:\n");
    
        for(i=0;i<35;i++)
        printf("_");printf("\n\\n");
    
        }
    
        }
        getch();
        return 0;
    }
    
    /* PUSH OPERATION */
    
    void push()
    {
    
        int i,num;
        printf("ENTER THE NUMBER TO PUSH:");
        scanf("%d",&num);
    
        if(top == size)
        {
    
            for(i=0;i<35;i++)
            printf("_");printf("\n\n");
    
            printf("STACK IS FULL!\n");
    
            for(i=0;i<35;i++)
            printf("_");printf("\n\n");
        }
        else
        {
    
            top++; stack[top] = num;
    
        }
    }
    
    /* POP OPERATION */
    
    void pop()
    {
    
        int i,num;
        printf("ENTER THE NUMBER TO POP:");
        scanf("%d",&num);
    
        if(top == 0)
        {
    
            for(i=0;i<35;i++)
            printf("_");printf("\n\n");
    
            printf("STACK IS EMPTY:\n");
    
            for(i=0;i<35;i++)
            printf("_");printf("\n\n");
    
        }
        else
        {
    
            num= stack[top];
            top--;
    
        }
    }
    
    /* Traverse The Stack */
    void traverse()
    {
    
        int i;
    
        if (top==0)
        {
    
            for(i=0;i<35;i++)
            printf("_");printf("\n\n");
    
            printf("STACK IS EMPTY:\n");
    
            for(i=0;i<35;i++)
            printf("_");printf("\n\n");
    
        }
        else
        {
    
            for(i=0;i<35;i++)
            printf("_");printf("\n\n");
    
            printf("Stack Display\n");
    
            for(i=1;i<=top;i++) 
    
            if(i==top) 
            { 
    
                printf("%d at %d -> top\n",stack[i],i);
    
                for(i=0;i<35;i++)
                printf("_");printf("\n\n");
            }
            else
            {
    
                printf("%d at %d\n",stack[i],i);
    
                for(i=0;i<35;i++)
                printf("_");printf("\n\n");
            }
        }
    }

    Output

    The output of the above program is given in the following figure.

    Output-Stack-Implementation
    Output-Stack-Implementation

    post

    Program to find Area of a Triangle

    The program computes the area of triangle once he user enters input values for the triangle. The inputs for the triangle are the length of base and height of the triangle.

    Problem Definition

    This program needs two critical information about a triangle -length of base and the height of the triangle. The base of the triangle is the longer side and one endpoint of the height divides the base. See the figure below.

    Triangle
    Triangle

    Now, the formula to find the area is as follows.

    \Large \begin{aligned} & Area = 1/2  \cdot (Base) \cdot (Height) \\\\
    &Area = 1/2 \cdot b \cdot h\end{aligned}

    Flowchart- Area of a Triangle

    Flowchart-Area of Triangle
    Flowchart – Area of Triangle

    Program Codes – Area of Triangle

    /* Area of Triangle */
    
    #include < stdio.h >
    
    #include < stdlib.h >
    
    main() 
    {
    
        float base, height, area, i;
    
        printf("Enter Base of the Triangle:");
    
        scanf("%f", & base);
    
        printf("Enter Height of the Triangle:");
    
        scanf("%f",& height);
    
        area = (base / 2) * height;
    
        for (i = 0; i < 35; i++)
    
        printf("_"); printf("\n\n");
    
        printf("Area of Triangle: %f\n", area);
    
        for (i = 0; i < 35; i++)
    
        printf("_"); printf("\n\n");
    
        system("PAUSE");
    
        return 0;
    
    }
    #include <iostream>
    using namespace std;
    
    int main()
    {
        float base, height, area;
    
        cout << "Enter Base of the Triangle: ";
        cin >> base;
    
        cout << "Enter Height of the Triangle: ";
        cin >> height;
    
        area = (base * height) / 2;
    
        cout << "\n-----------------------------------\n";
        cout << "Area of Triangle = " << area << endl;
        cout << "-----------------------------------\n";
    
        return 0;
    }
    import java.util.Scanner;
    
    class AreaOfTriangle
    {
        public static void main(String args[])
        {
            float base, height, area;
            Scanner sc = new Scanner(System.in);
    
            System.out.print("Enter Base of the Triangle: ");
            base = sc.nextFloat();
    
            System.out.print("Enter Height of the Triangle: ");
            height = sc.nextFloat();
    
            area = (base * height) / 2;
    
            System.out.println("\n-----------------------------------");
            System.out.println("Area of Triangle = " + area);
            System.out.println("-----------------------------------");
        }
    }
    base = float(input("Enter Base of the Triangle: "))
    height = float(input("Enter Height of the Triangle: "))
    
    area = (base * height) / 2
    
    print("\n-----------------------------------")
    print(f"Area of Triangle = {area}")
    print("-----------------------------------")

    Output

    The output of the above program is given below. When you enter the required input values – Base and Height of the triangle. The program computes the area and display it on the console.

        Enter Base of the Triangle:20
        Enter Height of the Triangle:12
        _____________________________________
        Area of Triangle: 120.000000
        _____________________________________
    post

    Program To Count Frequency Of Vowels

    The program to count the frequency of vowels, consonants and white spaces for a given word or a sentence is a string manipulation program. A loop with conditions check the given input string and count the number of vowels, consonants, and white spaces.

    Problem Definition

    In programming languages, every string is like an array with each character of the string hold a position in this array. The last character is null character by default in C/C++.

    Programming languages like Java, Python, and JavaScript do not add a null at the end of a string, but they treat a string as sequence of individual characters as an array.

    Using this array logic, the program read a word or a sentence during execution and check each and every character of input string. It counts the number of vowels, consonants and white spaces.

    For example, the array representation of word – SPIDERMAN as follows.

    \begin{aligned} &0 \hspace{5px}1  \hspace{5px}2\hspace{5px} 3 \hspace{5px}4 \hspace{5px}5 \hspace{5px}6\hspace{5px} 7\hspace{5px} 8 \hspace{5px}9 \\ 
    &S \hspace{3px} P\hspace{3px} I \hspace{3px}D \hspace{3px}E \hspace{3px}R \hspace{3px}M\hspace{3px} A \hspace{3px}N \hspace{3px}\backslash\empty\end{aligned}

    Note:- The Null character is added to all the strings in C by default.

    Flowchart – Program to Count Frequency of Vowels

    Figure 1 - Flowchart for Program to count the frequency of Vowels.
    Figure 1 – Flowchart for Program to count the frequency of Vowels.

    Program Codes – Program to Count Frequency of Vowels

    #include <iostream>
    #include <string>
    using namespace std;
    
    int main()
    {
        string str;
        int a=0, e=0, i=0, o=0, u=0;
        int consonant=0, whitespace=0;
    
        cout << "Enter a sentence: ";
        getline(cin, str);
    
        for (char ch : str)
        {
            if (ch=='a'||ch=='A') a++;
            else if (ch=='e'||ch=='E') e++;
            else if (ch=='i'||ch=='I') i++;
            else if (ch=='o'||ch=='O') o++;
            else if (ch=='u'||ch=='U') u++;
            else if (isalpha(ch)) consonant++;
            else if (ch == ' ') whitespace++;
        }
    
        cout << "a : " << a << endl;
        cout << "e : " << e << endl;
        cout << "i : " << i << endl;
        cout << "o : " << o << endl;
        cout << "u : " << u << endl;
        cout << "Consonants : " << consonant << endl;
        cout << "Whitespaces : " << whitespace << endl;
    
        return 0;
    }
    import java.util.Scanner;
    
    public class VowelCount {
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
    
            int a=0, e=0, i=0, o=0, u=0;
            int consonant=0, whitespace=0;
    
            System.out.print("Enter a sentence: ");
            String str = sc.nextLine();
    
            for (char ch : str.toCharArray()) {
                if (ch=='a'||ch=='A') a++;
                else if (ch=='e'||ch=='E') e++;
                else if (ch=='i'||ch=='I') i++;
                else if (ch=='o'||ch=='O') o++;
                else if (ch=='u'||ch=='U') u++;
                else if (Character.isLetter(ch)) consonant++;
                else if (ch == ' ') whitespace++;
            }
    
            System.out.println("a : " + a);
            System.out.println("e : " + e);
            System.out.println("i : " + i);
            System.out.println("o : " + o);
            System.out.println("u : " + u);
            System.out.println("Consonants : " + consonant);
            System.out.println("Whitespaces : " + whitespace);
    
            sc.close();
        }
    }
    s = input("Enter a sentence: ")
    
    a = e = i = o = u = consonant = whitespace = 0
    
    for ch in s:
        if ch in 'aA': a += 1
        elif ch in 'eE': e += 1
        elif ch in 'iI': i += 1
        elif ch in 'oO': o += 1
        elif ch in 'uU': u += 1
        elif ch.isalpha(): consonant += 1
        elif ch == ' ': whitespace += 1
    
    print("a :", a)
    print("e :", e)
    print("i :", i)
    print("o :", o)
    print("u :", u)
    print("Consonants :", consonant)
    print("Whitespaces :", whitespace)

    Apart from being a string program, we used built-in functions from C standard library to get string input (fgets) and compute the length of the given input string (strlen).

    The C++ code uses getline() command to read the sentence.

    Similarly, the scanner object sc is used to read the input text in Java program. It uses nextline() method which can read an entire line.

    The input() function in Python is capable of reading a line of text from user.

    After input, the operations on string to extract vowels, consonants, and spaces is similar in all four programming languages for the program.

    Output

    The output of the program is given below. When the sentence ” A large reptile” is entered, the program reads all the vowels, consonants and white spaces and print the results.

    ENTER A WORD OR A SENTENCE:
    A large reptile
    _____________________________________________
    a :1
    e :3
    i :1
    o :0
    u :0
    
    CONSONANTS :8
    WHITESPACES :2
    post

    C Program To Display Student Results

    The C program to display student results demonstrates the working of conditional statement in the C language. The program takes student’s marks in percentage (%) as input , process the input value and displays the results (pass or fail) as output.

    The output depends on the conditional statement in the example program.

    Learn C programming basics before you begin with this example program.

    Problem Definition

    The program decides whether a student has passed or failed an exam. If the input is in percentage mark ( say 70%), a simple conditional statement checks if given percentage mark is below 40%.

    ( mark < 40)

    The student result is a pass when mark is above 40% , else the student has failed. The result is displayed at the console.Here we list the steps involved in processing input values.

    1. Receive input in percentage mark (%)
    2. Check if the given mark is above below 40%
    3. If below 40%, then the student has failed
    4. Else the student passed.
    5. Display the result.

    Flowchart – Display Student Results

    The program start at the top (Start) and terminates where it says, (End) in the flowchart.

    Flowchart - C Program to Display Student Results
    Flowchart – C Program to Display Student Results

    Program Code – Display Student Results

    /*Show result of student using Marks */
    #include <stdio.h>
    #include <conio.h>
    int main()
    {
        int marks,i;
        /* Read student marks */
        printf("Enter the marks (in percentage ) of Student:");
        scanf("%d",&marks);
        /* display result */
        if(marks < 40)
        {
            for(i=0;i<40;i++)
            printf("_");printf("\n\n");
            printf("Result = Failed\n");
            for(i=0;i<40;i++)
            printf("_");printf("\n\n");
        }
        else
        {
            for(i=0;i<40;i++)
            printf("_");printf("\n\n");
            printf("Result = Passed\n");
            for(i=0;i<40;i++)
            printf("_");printf("\n\n");
        }
        system("pause");
        return 0;
    }

    Output

    The student entered his or her mark which is 60%. The given mark are above 40%, required condition to pass the exam. Hence, the student result is passed.

    Enter the marks ( in percentage ) of Student:60
    ___________________________________________________
    Result = Passed
    ___________________________________________________
    post

    C Function that Implements Call-By-Reference

    The main() function in a C program calls other functions. Some functions need arguments and some do not need any arguments. The efficiency of the program sometimes depends on what and how the arguments passed into the function.

    This program is written in Dev-C++ version 4 installed on a Windows 7 64-bit system, but you can use any other standard C compiler to compile and run this program.

    The program “C function that implements call-by-reference” is intended for beginner and intermediate level learner of C programming. You may need prior knowledge of pointers to understand this program.

    Problem Definition

    There are two methods of calling a function in the main() function of a C program.

    1. Call-by-Value
    2. Call-by-Reference

    In this post, we will only discuss the call-by-reference method. To learn about call-by-value method, read the article below.

    C Function that Implements Call-By-Value Method

    In call-by-reference method, when the main() function calls another function the actual arguments are not sent, but a reference to the original values of the variable is sent to the function.

    The function will use the memory address (the reference) of the original value of the variable and perform operations on it. You must carefully use this method because the original value can be changed during the execution of the program.

    For example, we will declare two variable a and b

    int a = 3;                          /* Original Values */
    int b = 4;                          /* Original Values */

    int *p, *q;                        /* Declare two pointers */

    p = &a;                             /* Pointer p refers to the memory address of the variable a */
    q = &b;                             /* Pointer q refers to the memory address of the variable b */

    swap ( p, q );                    /* Pass the memory address of the original value in the function */

    Now, in the function swap (), we use the reference to the original value and do the necessary operations.

    void swap ( int &a, int &b )
    {

             ……………………………..
            ……………………………..
            ……………………………..
    }

    Flowchart

    Flowchart: C Function that Implements Call-By-Reference Method

    Flowchart: C Function that Implements Call-By-Reference Method

    Program Code

    /*PROGRAM TO DEMO CALL-BY-REFERENCE */ 
    
    #include <stdio.h> 
    #include <conio.h> 
    main() { 
    int a,b,i; 
    void swap(int *p,int *q); 
    int *p, *q; p = &a; q = &b; 
    
    /* Read two Integers */ 
    
    printf("Enter two number A and B:"); 
    scanf("%d%d",&a,&b); 
    
    for(i=0;i<35;i++) 
    printf("_");printf("\n\n"); 
    
    printf("Before Swap : %d\tB = %d\n",a,b); 
    
    for(i=0;i<35;i++) printf("_");
    printf("\n\n"); 
    
    /* Swap the number using function swap() that uses original values of variable A and B */ 
    
    for(i=0;i<35;i++) 
    printf("_");printf("\n\n"); 
    
    swap(p,q); for(i=0;i<35;i++) 
    
    printf("_");printf("\n\n"); 
    
    getch(); 
    return 0; } 
    
    /* Swap Operations */ 
    
    
    void swap(int *p, int *q) { 
    
    int temp = 0; temp = *p; 
    *p = *q; 
    *q = temp; 
    
    printf("After Swap : A = %dtB = %dn",*p,*q); 
    
    }

     

    Output

    The output of the program is given below.

    Output : C Function that Implements Call-By-Reference Method

    Output : C Function that Implements Call-By-Reference Method

    post

    Program To Compute Nth Fibonacci Number

    The program computes Nth Fibonacci number using a technique called recursion and prints the results. A recursion is the ability of a procedure or function to call itself several times.

    You can write the program without recursion, but computer science students learn Fibonacci series as an introduction to recursion or recurrence relations. It is a topic of higher importance in both mathematics and computer science.

    Problem Definition

    In mathematics, the whole number means all positive numbers starting with 0. Any term in Fibonacci series takes a sum of previous two terms. The formula for the nth term of Fibonacci series is given below.

    \Large \begin{aligned}
    & f_{n} = f_{n-1} + f_{n-2}
    \end{aligned}

    The first few terms of the series are as follows

    \Large \begin{aligned}
    &0, 1, 1, 2, 3, 5, 8, 13, 21, 34, \cdots
    \end{aligned}

    Flowchart – Program for Fibonacci Series

    Figure 1 is a Flowchart for Computing Nth Fibonacci number
    Figure 1 – Flowchart for Computing Nth Fibonacci number

    Program Codes – Fibonacci Series

    /* Program to calculate Fibonacci Series */
    #include < stdio.h >
    #include < stdlib.h >
    main ()
    {
        int n;
        void fib ();
        printf ("Number of terms to be generated?");
        scanf ("%d", & n);
        printf ("%d", n);
        printf ("\n\n Fibonacci sequence up to %d terms :\n\n");
        fib(n);
        printf("\n");
        system("PAUSE");
        return 0;
    }
    
    void fib(int n)
    {
        static long int f1 = 0, f2 = 1, sum;
        if (n > 0)
        {
            sum = f1 + f2;
            f1 = f2;
            printf("%5d", sum);
            f2 = sum;
            fib(n - 1);
        }
    }
    #include <iostream>
    using namespace std;
    
    void fib(int n) {
        static long f1 = 0, f2 = 1;
        long sum;
    
        if (n > 0) {
            sum = f1 + f2;
            f1 = f2;
            f2 = sum;
            cout << sum << " ";
            fib(n - 1);
        }
    }
    
    int main() {
        int n;
        cout << "Number of terms to be generated?";
        cin >> n;
    
        cout << "\nFibonacci sequence up to " << n << " terms:\n\n";
        fib(n);
        cout << endl;
    
        return 0;
    }
    import java.util.Scanner;
    
    class Fibonacci {
        static long f1 = 0, f2 = 1;
    
        static void fib(int n) {
            if (n > 0) {
                long sum = f1 + f2;
                f1 = f2;
                f2 = sum;
                System.out.print(sum + " ");
                fib(n - 1);
            }
        }
    
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
    
            System.out.print("Number of terms to be generated?");
            int n = sc.nextInt();
    
            System.out.println("\nFibonacci sequence up to " + n + " terms:\n");
            fib(n);
            System.out.println();
    
            sc.close();
        }
    }
    f1, f2 = 0, 1
    
    def fib(n):
        global f1, f2
        if n > 0:
            s = f1 + f2
            f1, f2 = f2, s
            print(s, end=" ")
            fib(n - 1)
    
    n = int(input("Number of terms to be generated?"))
    
    print(f"\nFibonacci sequence up to {n} terms:\n")
    fib(n)
    print()

    Output

    Number of terms to be generated?:8
    Fibnacci sequence upto 8 terms :
    -------------------------------------------------------
         1     2     3     5     8     13    21     34
    -------------------------------------------------------
    post