Google Add

Search

C Program to Check Whether a Number is Palindrome or Not

Write a C Program to check whether a number is palindrome or not. In this program, we take an input number from a user and check whether an input number is palindrome or not.

What is a Palindrome Number?


A palindrome number is a number that remains same when it's digits are reversed.

For example - 11, 22, 121, 12321, 16461 etc.

C program to check whether a number is Armstrong or not

How to check whether a number is palindrome or not?


i) Take an input number from a user.

ii) Reverse an input number.

iii) Compare input number and reverse of an input number. If both are equal then entered number is a palindrome number.

C program to check whether a string is palindrome or not

C Program to Check Whether a Number is Palindrome or Not



C Program to Check Whether a Number is Palindrome or Not


In this programming example, first step is to take an input from a user then find the reverse of an input number. If input number and reverse of an input number is same then it's a palindrome number.

#include<stdio.h>

  
int main(){

   int num, temp, rev, digit;

   //Input number
   printf("Enter a number \n");
   scanf("%d", &num);
    

   temp = num;
   
   //Reverse a number
   while( temp > 0) {
       
       digit = temp % 10;
       rev   = rev * 10 + digit;
       temp  = temp / 10;
   }

   /*
   If original number and reverse of a number
   is same, then it's palindrome
   */
   if( num == rev) {
       printf(" %d is a Palindrome number", num);
   } else {
       printf(" %d is not a Palindrome number", num);
   }

    return 0;
}


Output -

Enter a number:  121

121 is a palindrome number



C program to print fibonacci series using recursion

C program to reverse a number

C interview questions for practice

C program to calculate power of a number


C Program to Print Fibonacci Series Using Recursion

Write a c program to print Fibonacci Series using recursion. Given a positive integer n, we have to write a c code to print fibonacci series using recursion. This question is also very important in terms of technical interviews.

In my last post, I have already discussed C program to print fibonacci series using while, do while & for loop.  Let's first understand, what is Fibonacci series?

Fibonacci Series

In Fibonacci series, first two numbers are 0 and 1, and the remaining numbers are the sum of previous two numbers.

For example -

0  1  1  2  3  5  8 ......

You can clearly see first two numbers are 0 and 1 and the rest of the numbers are the sum of previous two numbers.

In this post, We will learn how to print Fibonacci series using recursion. So let's understand what is recursion.

C, C++ Interview Question

What is Recursion?


In simple words, Recursive function is a function that calls itself. Through recursion, We can write much cleaner and shorter code for complex problems.

In recursion program, Always specify the base condition(terminating condition) otherwise code will run infinitely until the program run out of memory.

Recursion vs iteration - Difference between recursion and iteration

C Program to Print Fibonacci Series Using Recursion


C Program to Print Fibonacci Series Using Recursion


In this program, we take a number of elements to print in a fibonacci series as an input from user. Then our recursive method print fibonacci series upto that number.


#include<stdio.h>


int fibonacci(int n){

  /**
   if number is less than 2,
   In case of 0 and 1
   */
  if(n < 2) {
      return n;
  }

  //Recursive call
  return fibonacci(n-1) + fibonacci(n-2);

}

  
int main(){

   int num;

   printf("Number of terms to print in a Fibonacci series");
   scanf("%d", &num);

   for(int i = 0; i < num; i++) {
       printf(" %d ", fibonacci(i));
   }

    return 0;
}



Output

Number of terms to print in a Fibonacci series 10

0  1  1  2  3  5  8  13  21  34


Another way to write this program using recursion.


#include<stdio.h>


void fibonacci(int n){

  static int first = 0, second = 1, third;

  //If n is greater than zero   
  if(n > 0){

    third = first + second;

    printf(" %d ",third);

    first  = second;
    second = third; 
 
   /* Function call itself. */

    fibonacci(n-1);

   }

}

  
int main(){

   int num;

   printf("Number of terms to print in a Fibonacci series");
   scanf("%d", &num);

   printf("%d %d",0,1);

  /* Frist two numbers (0,1) are printed, 
     so we passed n-2 to fibonacci function. */

   fibonacci(num-2);

    return 0;
}

 

C program to delete an element from an array

C program to check Armstrong number

C program to check whether a character is vowel or consonant

Questions on Recursion for Practice

C++ Program to Delete an Element from an Array

Write a C++ program to delete an element from an array at specified position.  Given an input array, Write a code to delete an element from a position input by a user.

To solve this problem, let's first understand what is the input parameter and what's our approach to solve this problem.


C++ Program to Delete an Element from an Array


In this program, we take an input array and position of an element to delete.


C program to delete an element from an array

Reverse an Array using Recursion


C++ Program to Delete an Element form an Array



In this program, we take an array and position of an element as an input. Then, we write a code to delete an element from an array. To delete an element at index i in array we have to shift all elements from index i+1(higher index) to i (previous index).


#include <iostream>
using namespace std;

int main() {
 
   
   int a[100], size, pos, i, count = 0;

   cout << "Enter the size of an array \n";
   cin  >> size;
   
   cout << "Enter the value in an array \n";
   
   // Take an input array
   for (i = 0; i < size; i++) {
    cin >> a[i];
   }
   
   //Input position where we delete an element 
   cout << "Enter the position \n";
   cin  >> pos;

   //Shift element from i+1 to i
   for(i = pos-1; i < size; i++) {

      arr[i] = arr[i+1];
   }

   // Reduce the size of an array
   size--;            

  // Print an array after deleting an element
  for(i = 0; i < size; i++) {
   
    cout<<"   "<<a[i];
    
  }

  return 0;
}


Output : 

Enter the size of an array  - 5

Enter the value in an array

2     4     6     1      2

Enter the position    -   2

 2    4   1    2



Programming questions on Strings

Programming questions on Recursion

Programming questions on Array

Programming questions on Linked List

Java Program to Find Largest Number in an Array

Write a java program to find largest number in an array. Given an unsorted array, we have to write a java code to find largest number in an array.

Algorithm to Find Largest Number in an Array


First Approach: Sort an array

First approach is to sort an array and pick the last element of an array. For sorting, we can use algorithm such as Bubble sortSelection sortInsertion sortQuick sort, Merge sort etc. to sort an array. After sorting, An array element at n-1 position is highest number of an array.

The time complexity of sorting an array is O(nlogn).

Bubble sort program in java

Sorting algorithms and their time complexity

Second Approach:

Traverse an array to find highest number of an array.

1. Take a variable and assign the minimum value.




2.  Traverse an array and compare each element of an array to the assigned variable. 

Java program to find second smallest number in an array


Java Program to Find Largest Number in an Array

Java Program to Find Largest Number in an Array


In this program, we take the size of an array and array element as input from a user. Then we declare a variable highest and assign a minimum integer value. After that, we traverse an array and compare each element of array to the value of a variable.


import java.util.Scanner;

public class Largest {

  public static void main(String[] args) {

     Scanner in = new Scanner(System.in);
     System.out.println("Enter the size of an array");

     // Size of an array
     int n = in.nextInt();

     // Array declaration
     int arr[] = new int[n];

     System.out.println("Enter an array elements");

     //Input array elements
     for (int i = 0; i < n; i++) {
 arr[i] = in.nextInt();
     }

     // Assign minimum value
     int highest = Integer.MIN_VALUE;

     for (int i = 0; i < n; i++) {
       // compare
       if (arr[i] > highest) {
          highest = arr[i];
       }
    }

     System.out.println("Highest number is " + highest);
   }

}


Output :

Output of largest number in an array

Java programs for practice

Java program to print factorial of a number

C Program to Find Highest Number in an Array

Write a c program to find highest number in an array. Given an input array, we have to write a code to find highest number in an array.

There are multiple approaches we can use to solve this problem.

i) Find highest number in an array using sorting algorithm.

We can use any sorting algorithm such as Bubble sort, Selection sort, Insertion sort, Quick sort, Merge sort etc. to sort an array. After sorting an array element at n-1 position is highest number in an array.

The time complexity of sorting an array is O(nlogn).

ii) Traverse an array to find highest number in array.

In this approach, first declare a variable highest and assign first element of an array. After that traverse an array, and compare each element of an array with the value of highest. If any element is greater than the highest then assign that value into highest variable.

The time complexity is O(n).

Let's implement the second approach.

C++ program to find largest number in an array

C Program to Find Highest Number in an Array


C Program to Find Highest Number in an Array


In this programming example, we first take an input array from user. Then we traverse an array to find highest number in an array.

#include <stdio.h>

int main() {
    
    int arr[100], n, i, highest;
    
    printf("Enter the size of an array( Max 100) \n");
    scanf("%d", &n);
    
    printf("Enter array elements \n");
    
    //Take input values
    
    for(i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
    }
    
    
    //Assign first value 
    
    highest = arr[0];
    
    //Traverse an array
    
    for(i = 0; i < n; i++) {
        
        //If any value is greater than highest
        
        if(arr[i] > highest) {
            highest = arr[i];
        }
    }
    
    //Print largest number
    
    printf("Largest number is %d ", highest);
    
    return 0;
}



Output :

Enter the size of an array( Max 100)  5

Enter array elements
3
8
2
7
1

 Largest number is 8


Programming questions on arrays

C program to check whether a character is vowel or consonant

C program to find second smallest number in an array without sorting

C++ Program to Find Largest Number in an Array

Write a C++ program to find largest number in an array. Given an unsorted array, we have to write a C++ code to find the largest number in an array.

Let's think for a moment, how do you solve this problem. You can solve this problem using sorting algorithm, first sort an array and then pick the element at n-1 position. But, let's solve this problem without using any sorting algorithm.

Also, The time complexity of sorting an array is O(nlogn) but we can solve this problem in O(n) in a single traversal.

Algorithm to Find Largest Number in an Array


i) Take an input array from a user.

ii) Take a variable highest and assign first element of an array. After that traverse an array and compare each element of an array with highest. If any element is greater than the highest then assign that value into highest.


Sample snippet.

 /* Assign array first element to highest variable. */

   int highest = arr[0];

  /* Iterate till the end of an array. */
 
   for(i=1;i< arrcount; i++){
 
        /* Check if array element is higher
           than value in highest.*/
       
 if(arr[i]>highest){
   
        highest = arr[i];
     }
 }

Reverse a number using recursion in C, C++

C program to find highest number in an array


C++ Program to Find Largest Number in an Array


C++ Program to Find Largest Number in an Array


#include <iostream>
using namespace std;

int main() {
    
    int arr[100], n, i, highest;
    
    cout << "Enter the size of an array( Max 100) \n";
    cin >> n;
    
    cout << "Enter array elements \n";
    
    //Take input values
    
    for(i = 0; i < n; i++) {
        cin >> arr[i];
    }
    
    
    //Assign first value 
    
    highest = arr[0];
    
    //Traverse an array
    
    for(i = 0; i < n; i++) {
        
        //If any value is greater than highest
        
        if(arr[i] > highest) {
            highest = arr[i];
        }
    }
    
    //Print largest number
    
    cout << "Largest number " << highest;
    
    return 0;
}

Output :

Enter the size of an array( Max 100)  5

Enter array elements
3
8
2
7
1

 Largest number 8


Programming questions on arrays

C program to check whether a character is vowel or consonant

C program to find second smallest number in an array without sorting

C Program to Calculate the Sum of Digits of a Number

Write a c program to calculate the sum of digits of a number. In this program, we take an input number from a user and then calculate the sum of digits of a number.

Algorithm to calculate the sum of digits of a number


i) Take an input number from a user.

ii) Assign a input number in a variable.

iii) Get the last digit by performing modular division i.e. digit = num % 10.

iv) Take another variable sum and assign the last digit into it i.e. sum = sum + digit.

v) Remove the last digit from number by dividing the number by 10 (num = num / 10).

vi) Repeat step (iii to v) till number becomes 0. After that we will get the sum of the digits of a number.

Find sum of digits of a number using recursion

C Program to Calculate the Sum of Digits of a Number



C Program to Calculate the Sum of Digits of a Number


In this example, we take an input number and calculate the sum of digits of a number.


#include <stdio.h>

int main() {
 
    int num, sum = 0, remainder;
    
    //Input number
    
    printf("Enter a number \n");
    scanf("%d", &num);
    
    
    //If num is greater than zero
    
    while(num > 0) {
    
       /* Find remainder of a a number */
       remainder = num % 10;
    
       /* Add to a sum */
        
       sum = sum + remainder;
       
       /* remove the last digit */
        
       num = num / 10;
    }
    
    
    printf("Sum of digits is %d", sum);
    
    return 0;
}

Output

Enter a number : 234

Sum of digits is 9

Programming questions for beginners

Programming questions on arrays

C Program to Check Whether a Number is Armstrong or Not

Write a c program to check whether a number is Armstrong or not. In this program, we take an input number from a user and check whether an input number is Armstrong or not.

Before we start solving this problem, let's understand what is Armstrong number?

What is Armstrong number?


An Armstrong number is an n-digit number that is equal to the sum of the nth powers of its digits.

For example - 153 , 371 is an Armstrong number.

Example 1 - 153 has 3 digits.

153 : 1 3 + 5 3 ;+ 3 3 = 153

Example 2 - Take an example of 6 which has 1 digit.

6 : 6 = 6  It's an Armstrong number

Example 3 -  Take another example let's say 15, it has 2 digits.

15 : 12 + 52 = 26

So 15 is not an Armstrong number.

Example 4 - This time let's take bigger number 1634, it has 4 digits.

1634 : 1 4 + 6 4 + 3 4 + 4 4 = 1634

It's an Armstrong number.

We have understood the concept, let's solve this problem.

Program to count number of digits in a number

C Program to Check Armstrong Number



Program to check whether entered number is Palindrome or not

C, C++ Program for Practice


C Program to Check Whether a Number is Armstrong or Not


In this example, we first take an input number. Then we find the length of a number and then calculate the sum of a number (Which i have explained in examples).  If entered number and the sum of a number is equal then it's an Armstrong number.

C program to calculate the sum of digits of a number


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

int main() {
 
  int num, remainder, temp, sum = 0, n = 0;
 
  //Take input number
  printf("Enter a number");
  scanf("%d", &num);
 
  temp = num;
 
  //Find the length of a number
  while(temp > 0) {
     n++;
     temp = temp/10;
  }
 
   
   //Again assign temp
   temp = num;
   
   while(temp > 0){
  
     remainder = temp % 10;
       
     sum  = sum + pow(remainder, n);
     temp = temp/10; 
   }
    
  
   if (num == sum){
      printf("\n %d is an Armstrong number ", num);
  
   } else {
     printf ("\n %d is not an Armstrong number ", num);
  
   }
    
   return 0;
}



Output -

Enter a number : 153

153 is an Armstrong number



Programming questions for beginners

Program to check whether a number is prime or not

C++ Program to Check whether a Character is Vowel or Consonant

Write a C++ program to check whether a character is vowel or consonant. Given an input character, we have to write a code to check whether an entered character is vowel or consonant.

An alphabet a, e, i, o, u is called as vowel and the rest of the alphabet is called as a consonant.

How to check whether a character is vowel or consonant


i) Take an input alphabet from user.

ii) Check whether an input alphabet is a, e, i, o, u, A, E, I, O, U then it's a vowel otherwise it's a consonant.

C program to check whether a character is vowel or consonant


C++ Program to Check whether a Character is Vowel or Consonant



C++ Program to Check whether a Character is Vowel or Consonant


In this programming example, we are going to write a C++ code which takes an input character and check whether a character is vowel or consonant.


#include <iostream>
using namespace std;

int main() {

   // Declare char
   char alpha;

   // Take a input character from a user
   cout<<" Enter an alphabet \n";
   cin >> alpha;

   if ( alpha == 'a' || alpha == 'A'  
       || alpha == 'e' || alpha == 'E' 
         || alpha == 'i' || alpha == 'I' 
       || alpha =='o' || alpha=='O' 
        || alpha == 'u' || alpha == 'U') {

         cout << alpha << " is a vowel";
      } else {
          cout << alpha << " is a consonant";
       }

       return 0;
}


Output:

Enter an alphabet :  a

a is a vowel.

C++ Program to Check whether a Character is Vowel or Consonant by using Function


In this example, we have created separate function to check whether a character is vowel or consonant. When a user input an alphabet, we called isVowel() method, which return true if the input character is vowel otherwise it returns false.


#include <iostream>
using namespace std;


bool isVowel(char alpha) {
    
    if ( alpha == 'a' || alpha == 'A'  
       || alpha == 'e' || alpha == 'E' 
         || alpha == 'i' || alpha == 'I' 
       || alpha =='o' || alpha=='O' 
         || alpha == 'u' || alpha == 'U') {

        return true;
       
    } else {
       
        return false;
    }
    
}

int main() {

   char alpha;

   // Take a input character from a user
   cout << "Enter an alphabet \n";
   cin >> alpha;

   
    if(isVowel(alpha)) {
        cout << alpha << " is vowel ";
    } else {
        cout << alpha << " is consonant ";
    }

    return 0;
}



Programming questions for beginners

C++ program to print even numbers between 1 to 100 using for and while loop

Programming questions on arrays

C Program to Check whether a Character is Vowel or Consonant

Write a c program to check whether a character is vowel or consonant. In this program, we take an input character from a user and our code will check whether an input character is vowel or consonant.

Before start writing code, let's first understand what is vowel and consonant?

What is vowel and consonant?

In english, Alphabet a, e, i, o, u is called vowel and rest of the alphabets is called consonant.

How to Check whether a Character is Vowel or Consonant 

 1. Take an input character from a user. 

 2. Compare input character with a, e, i, o, u, A, E, I, O, U. If it matches with any of them then it's a vowel otherwise it's a consonant.

C program to concatenate two strings

C Program to Check whether a Character is Vowel or Consonant


C Program to Check Whether a Character is Vowel or Consonant


In this example, we take an input alphabet from a user and then compare with a, e, i, o, u (upper and lower case both). If input character is matches then it's a vowel otherwise it's a consonant.

#include <stdio.h>

int main(void) {
 
  //Declar char
  char alpha;

  // Take a input character from a user

  printf(" Enter an alphabet\n");
  scanf("%c", &alpha);

  //Compare

  if ( alpha == 'a' || alpha == 'A' 
       || alpha == 'e' || alpha == 'E' 
          || alpha == 'i' || alpha == 'I' 
       || alpha =='o' || alpha=='O' 
           || alpha == 'u' || alpha == 'U') {

      printf("%c is a vowel", alpha);
  } else {
      printf("%c is a consonant", alpha);
  }
       
 return 0;

}



Output :

Enter an alphabet : a

a is a vowel

C Program to print 1 to 100 numbers without using loop

C program to reverse a number

C Program to Check Whether a Character is Vowel or Consonant using Switch Statement


In this example, we use switch statement to check whether an input alphabet is vowel or consonant. The logic is same. In this case, we solve this problem in another way using switch statement.


#include <stdio.h>

int main(void) {
 
    
      char alpha;

      // Take an input character from a user.

      printf(" Enter an alphabet \n");
      scanf("%c", &alpha);

      switch(alpha) {
              
          case 'a':
          case 'A':
          case 'e':
          case 'E':
          case 'i':
          case 'I':
          case 'o':
          case 'O':
          case 'u':
          case 'U':
             printf("%c  is a vowel", alpha);
             break;
          default:
             printf("%c  is not a vowel", alpha);
              
      }
      
     return 0;
}


Programming question on Arrays

Programming question on Linked List

Sorting algorithm and their time complexity

Stack implementation

Programming questions using Recursion

C, C++ interview questions

Programming Books

C Program to Concatenate Two Strings

Write a c program to concatenate two strings. Given two input strings, we have to write a C program to concatenate two strings. 

In this tutorial, we'll take an example of string concatenation using inbuilt string function strcat() as well as without using this inbuilt method.



C Program to Concatenate Two Strings



Logic of concatenating two strings.

i) Declare two character array and take input from user.


ii)  Traverse first string to reach at the end, now start concatenating second string into first.


Programming questions on strings

Let's first take an example of string concatenation using inbuilt function strcat().

C Program to Concatenate Two Strings using strcat


In this example, we take two input strings from user and then concatenate these two strings using strcat() method.


#include <stdio.h>
#include <string.h>

int main() {
    
    char str1[100], str2[100];
    
    printf("Enter first string \n");
    fgets(str1, 100, stdin);
    
    printf("Enter second string \n");
    fgets(str2, 100, stdin);
    
    
    //inbuilt library function1
    strcat(str1, str2);
    
    printf("After concatenation %s", str1);
    
    return 0;
}


C Program to Concatenate two Strings without using strcat



In this example, we first traverse a first string and reach at the end of a first string and then start concatenating second string into first string.

#include <stdio.h>

int main() {
    
    char str1[100], str2[100], i = 0, j = 0;
    
    printf("Enter first string \n");
    fgets(str1, 100, stdin);
    
    printf("Enter second string \n");
    fgets(str2, 100, stdin);
    
    
    /* Traverse and 
     *reach at the end of a string
     */
    
    while(str1[i] != '\0') {
        str1[i++];
    }
    
    /*
     * Traverse second string
     * and appends them into first string
     */
    while(str2[j] != '\0') {
        str1[i++] = str2[j++];
    }
    
    str1[i] = '\0';
    
    printf("After concatenation %s ", str1);
    
    return 0;
}

Output:

Enter a first string :  cprogrammingcode

Enter second string : .com

After concatenation : cprogrammingcode.com

C program to reverse a number

C program to check whether a character is vowel or consonant



Java Program to Check whether a Number is Palindrome or not

Write a java program to check whether a number is palindrome or not. Given an input number, we have to write a code to check whether a number is palindrome or not.

Before solving this problem, let's first understand what is palindrome number?

What is Palindrome Number? 


A palindrome number is a number that remains the same when its digits are reversed.

For example - 121, 454, 12521 etc.

If we reverse 121, it remains 121 so it's a palindrome number.

How do we check whether a number is palindrome or not


To check whether a number is palindrome or not, just reverse a number and compare with the input number. If it's equal then it's a palindrome number otherwise it's not.

C program to reverse a number

Reverse a number using recursion - C, C++ code

Java program to count number of digits in a number


Java Program to Check whether a Number is Palindrome or not


Java Program to Check whether a Number is Palindrome or not


To check whether a number is palindrome or not, we have to reverse a number and compare it with the input number. If both the numbers are equal then it's a palindrome number. Let's implement them programmatically.


public class Palindrome {

   public static void main(String[] args) {

      Scanner in = new Scanner(System.in);

      System.out.println("Enter an input number");
      int num = in.nextInt();

      // Assign number in temp
      int temp = num;
  
      int rev = 0, digit;
 
      // Logic to reverse a number
      while (temp > 0) {
 
        digit = temp % 10;
        rev = rev * 10 + digit;
        temp = temp / 10;
      }

      /*
       * If original and reverse of a number 
       * is equal then it's a palindrome number.
       */
       if (rev == num) {
         System.out.println(num + " is palindrome");
       } else {
         System.out.println(num + " is not a palindrome");
       }
   }

}


Output :


Palindrome program output

Palindrome program output











Program to reverse a string in java

Java program to print factorial of a number

Program to Check Whether a Number is Even or Odd - C, C++ Code

Write a Program to check whether a number is even or odd. Given an input number, we have to write a code to check whether an input number is even or odd.

Before solving this problem, let's first understand what is even or odd number?


Even number


Any integer that can be perfectly divisible by 2 is an even number. 

For example - 2, 4, 6, 8, 10 etc.


Odd Number


An odd number is a number that is not divisible by 2.

For example - 3, 5, 7 etc.



Program to print sum of first ten numbers

Program to count number of vowels in a string


Algorithm to check whether a number is even or odd number

1. Declare a variable num (You can declare any variable).


2. Take an input number from user and store this value in num variable.


3. Check whether a number is perfectly divisible by 2 .If it is divisible by 2 then it's a even number otherwise it is an odd number.


C program to print even numbers between 1 to 100 using for and while loop


C Program to Check whether a number is even or odd



C Program to Check whether a Number is Even or Odd


#include <stdio.h>

void main()
{
 
   int num; 
 
   printf("Enter an integer value");
   scanf("%d", &num);
 
   /* If a number is perfectly
      divisible by 2 then it's an even number*/

   if(num % 2 == 0){  
      printf(" \n %d is an even number ", num);
   } else {
      printf(" \n %d is an odd number ", num);
   }

}



Output :

Enter an integer value  : 10

10 is an even number

Find sum of first n odd numbers in C, C++


C++ Program to Check whether a Number is Even or Odd


#include <iostream>
using namespace std;

int main() {
 
   int num; 
 
   cout << "Enter an integer value\n";
   cin >> num;
 
   if(num % 2 == 0){  
      cout << " \n Entered number is an even number ";
   } else {
      cout << " \n Entered number is an odd number ";
   }
   
 return 0;
}




Programming question on Arrays

Programming question on Linked List

Sorting algorithm and their time complexity

Stack implementation

Programming questions using Recursion

C, C++ interview questions

Programming Books

C, C++ interview questions for practice

Java Program to Find Second Smallest Number in an Array

Write a java program to find second smallest number in an array without sorting. Given an unsorted array of integers, we have to write a code to find second smallest number without sorting an array.

If we use sorting then the time complexity of an algorithm is O(nlogn). You can read about various sorting algorithms and their time complexity.

We can solve this problem in a single traversal in O(n) time complexity.

C program to find second smallest number in an array without sorting


Java Program to Find Second Smallest Number in an Array


Let's write a java code to find second smallest number in an array in a single traversal. The time complexity of this approach is O(n).


import java.util.Scanner;

public class secondSmallest {

  public static void main(String[] args) {

    Scanner in = new Scanner(System.in);

    //Input size of an array
    System.out.println("Enter the size of an array");
    int n = in.nextInt();

    //Array declaration
    int arr[] = new int[n];

    System.out.println("Enter an array elements");

    //Taking an input value of an array
    for (int j = 0; j < arr.length; j++) {
       arr[j] = in.nextInt();
    }
    
    //Initialize with max value of integer
    int smallest = Integer.MAX_VALUE;
    int secondSmallest = Integer.MAX_VALUE;

    //Traverse an array
    for (int i = 0; i < arr.length; i++) {

      if (smallest > arr[i]) {
         secondSmallest = smallest;
         smallest = arr[i];

     }

     if (arr[i] > smallest && arr[i] < secondSmallest) {
        secondSmallest = arr[i];
     }
   }
   
   System.out.println("Second smallest number is " + secondSmallest);
 }

}



Output -

Java Program to Find Second Smallest Number in an Array



Java program to reverse a string using stack

Java program to find first non-repeating character in a string

Java program to print factorial of a number

Java program to find sum of n natural numbers using recursion

C Program to Find Second Smallest Number in an Array without Sorting

Write a C program to find second smallest number in an array without sorting. Given an unsorted array of integer, we have to write a code to find second smallest number without using sorting.

We can solve this problem easily using sorting. First we sort an array and then we pick the element at 2nd index which is the second smallest element. This sorting technique won't work if the element of an array is repeated.  Think for a moment how do we solve this problem without using sorting.

Program to Find Second Smallest Number in an Array without Sorting


Find second smallest number in an array using sorting

Sorting algorithm and their time complexity

Algorithm To Find Second Smallest Number in an Array without Sorting



1. Take two variables smallest and secondSmallest and intialized with INT_MAX (maximum integer value).

2. Run a loop,

     a) If value is smaller than smallest, then update smallest and secondSmallest.
     b) if the current element is smaller than secondSmallest then update  secondsmallest.

Program to Find Smallest Number Without Using Comparison Operator

Program to Find Smallest Number in An Array


C Program to Find Second Smallest Number in an Array without Sorting


We have discussed the logic to find second smallest number in an array. Let's write a c code to implement them programatically.

#include <stdio.h>
#include <limits.h>

int main() {
 
   int arr[50], n, i;

   //Enter the size of an array 
   printf("Enter the size of an array (Max 50) \n");
   scanf("%d", &n);
 
   printf("Enter an array elements\n");

   //Input array values 
   for(i = 0; i < n; i++) {
      scanf("%d", &arr[i]);
   }

   //Intialize variable with max int value 
   int smallest = INT_MAX;
   int secondSmallest = INT_MAX;

   //Traverse an array 
   for(i = 0; i < n; i++) {
  
     //If element is smaller
     if(arr[i] < smallest) {
         secondSmallest = smallest;
         smallest = arr[i];
     }
  
     if(arr[i] > smallest && arr[i] < secondSmallest) {
         secondSmallest = arr[i];
     }
  }
 
  printf("Second smallest %d", secondSmallest);
 
  return 0;
}



Output : 

Enter the size of an array (Max 50) : 5
Enter an array elements
-1
2
8
3
4
Second smallest 2