Adsense 728 * 15

Search

Custom Search

Program to Convert Decimal to Binary Number - C, C++ Code with Examples

Write a C, C++ program to convert a decimal number to binary number. In this program, Our code take a decimal number as an input from a user and convert them into a binary number.

Program to Convert Decimal to Binary Number


Basic Programs for Practice

Program to convert binary to decimal number

How to Convert Decimal to Binary Number


1. Take an input from a user.

2. Check whether a number is greater than zero.

3. Run a loop until the number is greater than zero.

a: Divide the original decimal number by 2 and store it's remainder.
b: Increment i and array subscript.


          while(num > 0){
             arr[i] = num%2;
             i++;
             num = num/2;
          } 


4. Print the array in a reverse order.

Program to Convert Binary to Decimal Number


Let's convert 3 into binary


Step 1:  3 / 2  Remainder : 1 , Quotient : 1
Step 2:  1 / 2  Remainder : 1 , Quotient : 0

So Binary Conversion of 2 is 11

Let's convert 12 into binary

Step 1:   12/ 2  Remainder : 0 , Quotient : 6
Step 2:   6 / 2  Remainder : 0 , Quotient : 3
Step 4:   3 / 2  Remainder : 1 , Quotient : 1
Step 5:   1 / 2  Remainder : 1 , Quotient : 0

So Binary Conversion of 12 is 1100



C Program to Convert Decimal to Binary Number


#include<stdio.h>

void main(){

    int arr[10],i=0,num,j;

    printf("Enter decimal number \n");
    scanf("%d",&num);
       
    /* If a number is greater than zero. */

     while(num > 0){
            
        /* store the remainder of a number in array. */

         arr[i] = num%2;
         i++;
         num = num/2;
     } 

    /* Print the array(arr) in reverse order.*/

    printf("Binary representation of an input number is\n");
 
    for(j=i-1; j>=0; j--){
         printf("%d",arr[j]);
    } 

}


C++ Program to Convert Decimal to Binary Number


#include <iostream>

using namespace std;

int main() {
    
    int num, i = 0, arr[20];
 
    cout << "Enter a number\n";
    cin  >> num;
    
    int temp = num;
    
    //While temp is greater than 0
    while (temp > 0) {

       //store remainder in an array
       arr[i++] = temp%2;

       //divide a number by 2 in each iteration
       temp  = temp / 2;
    }
 
    cout <<"Binary representation of " << num << " is \n"; 
 
    //Print an array in a reverse order
    for(int j = i-1; j >= 0; j--) {
        cout << arr[j] << " ";
    }
 
    return 0;
}



Output -

Enter a number
12

Binary representation of 12 is   1 1 0 0


C, C++ Program to Reverse an Array using Recursion

Write a C, C++ program to reverse an array using recursion. Given an input array, we have to write a code that reverse an array using recursion.

C, C++ Program to Reverse an Array using Recursion


I assume you are familiar with the concept of recursion and the difference between iteration and recursion.  Let's quickly go through the concept of recursion.

In recursion, A function call itself until the base condition is reached.

Reverse a number using recursion

Let's assume user has input following array values.

// Input array

int arr[] = {3,2,1,7,8}

// Reverse of an input array

arr[] = {8,7,1,2,3}

I already discussed how to reverse an array  using iterative approach in my previous post.  In this post, we'll write a code to reverse an array using recursion.

C Program to Reverse an Array using Recursion

#include <stdio.h>

int reverse(int arr[],int start,int end){
 
     int temp;

     // if start is less than end  

     if(start < end){
     
         /* Swap the position of an element. */
         
         temp       = arr[start];
         arr[start] = arr[end];
         arr[end]   = temp;
         
         /*calling itself
          *Incrementing start and decrementing end
          */ 
         reverse(arr, start+1, end-1);
         
     } 
     
     return 0;
}

int main(void) {
 
   // Decare an array
 
   int arr[] = {3,2,1,7,8};
 
   int n = 5;
 
   /* Call reverse method */

   reverse(arr, 0, n-1);
 
   printf("Reverse of an array \n");
 
   for(int i = 0; i < n; i++){
  
        printf("%d ",arr[i]);
   }

   return 0;
}



C++ Program to Reverse an Array using Recursion

#include <iostream>

using namespace std;

int reverse(int arr[], int start, int end) {
    
    int temp;
    
    if(start < end) {
        temp        = arr[start];
        arr[start]  = arr[end];
        arr[end]    = temp;
        
        // recursive function call
        reverse(arr, start+1, end-1);
    }
    
    return 0;
}

int main() {
    
    int n, arr[100], i;
    
    cout << "Enter the size of an array \n";
    cin  >> n;
    
    cout << "Enter an element of an array \n";
    
    for(i = 0; i < n; i++) {
        cin >> arr[i];
    }
    
    reverse(arr, 0, n-1);
    
    cout << "Reverse of an array is \n";
    
    for(i = 0; i < n; i++) {
        cout << arr[i] << " ";
    }
    
    return 0;
}


Output :

Enter the size of an array 5

Enter an element of an array
 2 3 5 6 7

Reverse of an array is
 7 6 5 3 2


Swap two numbers using third variable.

Swap two numbers using pointer(call by reference).

Swap two numbers without using third variable.


Program to Check Leap Year in C, C++ - Program to Check whether a given Year is Leap Year or Not

Write a C, C++ program to check whether a entered year is a leap year or not. In this program, A user will input a year and our program will check whether it's a leap year or not.

What is Leap Year

A Leap year is a year which has 366 days, it means it has one additional day. Each leap year has 366 days instead of the usual 365 days.

Leap Year Program in C, C++


How to Check Leap Year


i) If a year is divisible by 4 then it's a leap year.  For example - 2012, 2008 etc.

ii) If a century year(1200, 1600) is divisible by 400  then it's a leap year. For example - 1200, 1600 etc.

C, C++ Interview Questions

Leap Year Program in C


#include <stdio.h>

int main(void) {
 
      int year;
   
      printf("Enter a year\n");
      scanf("%d",&year);
      
      /* A year should be divisible by 4 or 400 
         but not divisible by 100 */
      
      if( ( (year%4 == 0) && (year%100!=0) ) 
             || (year%400==0) )
      {
           printf("%d is a leap year.", year );
      }
      else
      {
           printf("%d is not a leap year.", year);
      }

     return 0;     
}


Another way of writing above program is -

#include <stdio.h>

int main(void) {
 
      int year;
   
      printf("Enter a year :");
      scanf("%d",&year);
      
      /* Check whether a entered year 
         is divisible by 4 */
      
      if(year%4 == 0)
      {
         /* For century year such as 500,1200 etc */
         
          if( year%100 == 0) 
          {
             /* If it's divisible by 400 then it's a leap year */
             
              if ( year%400 == 0)
              {
                 printf("%d is a leap year.", year);
              }
              else
              {
                 printf("%d is not a leap year.", year);
              }
          }
          else
             printf("%d is a leap year.", year );
      }
      else
      {
         printf("%d is not a leap year.", year);
      }
      
      return 0;
      
}



Output:


Enter a year  :  2008

2008 is a leap year

Program to Count Number of Vowels and Consonants in a String

Write a C, C++ program to count number of vowels and consonants in a string. Given an input string, We have to write a code to count number of vowels and Consonants in a string.

Program to check whether a input character is vowel or not

Programming Interview Questions

C, C++ Program to Count Number of Vowels and Consonants in a String
C, C++ Program to Count Number of Vowels and Consonants in a String



Before solving this problem let's understand what is vowel and consonant.

What is Vowel and Consonants ?

In english alphabet, A, E, I, O, U is called a vowel and remaining alphabets which is not a vowel is known as consonant.

How to read string with spaces using scanf

Programming Questions on Strings

C Program to Count Number of Vowels and Consonants in a String


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


int main(){
   

    char str[200];
    
    int i,vowel=0,consonant=0;
   

    printf("Enter any string");
    fgets(str,200,stdin);
    

    /* Length of a string. */
    
    int len = strlen(str);
    
     /* Traverse a string */
     for(i = 0; i < len; i++){
          
         /* Check for vowel and increment the count. */

         if( str[i]=='a' || str[i]=='e' 
             || str[i]=='i' || str[i]=='o' 
             || str[i]=='u' || str[i]=='A' 
             ||str[i]=='E' ||str[i]=='I' 
             ||str[i]=='O' ||str[i]=='U' ) {
             
                vowel++;
                
             /* Check for consonant. */

            } else if((str[i]>='a' && str[i]<='z') 
                       || (str[i]>='A' && str[i]<='Z')) {
             
               consonant++;
            }
     }
 
    printf("The number of vowels and consonants in a 
            string is %d %d",vowel ,consonant);

    return 0;
}




C++ Program to Count Number of Vowels and Consonants in a String


#include <iostream>
#include <string.h>

using namespace std;

int main() {
 
     char str[300];
     int  vowel = 0, consonant = 0;
 
     cout << "Enter a string \n";
     cin.getline(str, sizeof(str));

      /* Length of a string. */
    
      int len = strlen(str);
    
     /* Traverse a string */
     for(int i = 0; i < len; i++){
          
       /* Check for vowel and increment the count. */

       if( str[i]=='a' || str[i]=='e' 
           || str[i]=='i' || str[i]=='o' 
           || str[i]=='u' || str[i]=='A' 
           ||str[i]=='E' ||str[i]=='I' 
           ||str[i]=='O' ||str[i]=='U' ) {
             
                vowel++;
                
             /* Check for consonant. */

       } else if((str[i] >= 'a' && str[i] <= 'z') 
                  || (str[i] >= 'A' && str[i] <= 'Z')) {
             
               consonant++;
       }
     }
     
     cout << "The number of vowels and consonants 
                    in a string is "
                   << vowel << "  " << consonant;
 
    return 0;
}



Output -

Enter a string  - I love cprogrammingcode.com

The number of vowels and consonants in a string is  9   15

Java Program to Count Number of Digits in a Number

Write a Java program to count number of digits in a number. In this program, We take a positive number as an input and our program will count number of digits in a number.

Java Program to Count Number of Digits in a Number
Java Program to Count Number of Digits in a Number


C, C++ Program to count number of digits in a number

Java program to print factorial of a number

Java program to reverse a string

Java programs

Java Program to Count Number of Digits in a Number



import java.util.*;

public class CountDigit {

    
    public static void main(String[] args) {
        
        int num, count = 0;
        
        System.out.println("Enter a number");
        Scanner in = new Scanner(System.in);
        
        num = in.nextInt();
        
        while( num > 0) {
            
            //Reduce number in each iteration
            num = num / 10;
            
            //count
            count++;
        }
        
        System.out.println("Number of digits in a number 
                            is "+ count);
    }
    
}



Output :

Enter a number  - 356

Number of digits in a number is - 3


Let's understand how this program works-

Iteration 1 - Our input number is 356

In first iteration, value of num variable is 356.

num = num / 10 = 35
count = 1

Iteration 2

After first iteration, value of num variable is 35.

num = num / 10 = 3
count = 2

Iteration 3

After second iteration, value of num variable is 3.

num = num / 10 = 0
count = 3


After third iteration our while loop terminate, As it not satisfy the condition (num is greater than zero). So our program will print number of digits in a number is 3.

C, C++ Program to Count Number of Digits in a Number

C, C++ Program to Count Number of Digits in a Number
C, C++ Program to Count Number of Digits in a Number
Write a C, C++ program to count number of digits in a number. Given a positive input number, Our program will count the number of digits present in a number. Suppose a user has entered a number 4567, So the total digits in a number is 4.



Logic to Count Number of Digits in a Number




C, C++ Interview Questions

Program to reverse a number

Program to Find the sum of first n odd numbers


C Program to Count Number of Digits of a Number

#include <stdio.h>

int main() {
 
   int num;
   int count=0;
 
   printf("Enter a number \n");
   scanf("%d", &num);

   /* If a number is greater than zero. */
       
   while(num > 0) {

      /* Reduce the number is every iteration. */

      num=num/10;

     /* Increment the count. */

     count++;
  }
 
  printf("Number of digits in a number is %d",count);
 
  return 0;
}



Output:

Enter a number - 4567

Number of digits in a number is - 4


C++ Program to Count Number of Digits in a Number



#include<iostream>
using namespace std;

int main() {
    
    int num, count = 0;
    
    // Input number
    cout << "Enter a number \n";
    cin  >> num;
    
    // If number is greater than zero
    while (num > 0) {
        
        //Reduce number in each iteration
        num = num / 10;
        
        //Count number of digits
        count++;
    }
    
    cout << "Number of digits in a number is " << count;
    
    return 0;
}






Time Complexity of Sorting Algorithms

Time Complexity of Sorting Algorithms
Time Complexity of Sorting Algorithms
The time complexity of sorting algorithms. In this tutorial, We'll compare the time complexity of various sorting algorithms.

We'll learn how various sorting algorithms performs when input size grows. An algorithm efficiency is measured by their time complexity. So let's compare the time complexity of various algorithms.

What is Time Complexity ?

In computer science, The time complexity of an algorithm signifies the total time taken by the program to complete it's execution. The time complexity of an algorithm is commonly expressed in big O notation.

Common Time Complexities

O(1)  - Constant Time

O(1) mean an algorithm will execute in constant time no matter how large input is. Hash functions are the perfect example of constant time.

Find first non-repeating character in a string using hashmap

O(log n) - Logarithmic Time.

O(log n) means the operations per instance required to complete decreases with each instance. For example - Binary Search, Binary Tree etc.

O(n) - Linear Time.

O(n) means algorithm performance is directly proportional to the input size (n). For example - when you traversing a string or an array. Linear search is a perfect example.


O(n2) - Quadratic Time.

O(n2)  means algorithm performance is directly proportional to the square of the size of input data. Nested for loops are the perfect example of this category.

Time Complexity of Sorting Algorithms


Let's check the time complexity of mostly used sorting algorithms.

Time Complexity of Bubble Sort

Bubble Sort is a simple sorting algorithm. It works by comparing each pair of elements and switching their positions if necessary. It repeats this process until all the elements are sorted.


Average case time complexity of bubble sort - O(n2)

Worst case time complexity of bubble sort - O(n2)

Best case time complexity of bubble sort - O(n)

Best case occurs when list is already sorted. Bubble sort is not good for sorting when n (input size) is large.


Time Complexity of Selection Sort


Selection sort is an in-place comparison sorting algorithm.  In this algorithm, we pick an element and move the element to it's correct position. This process is repeated until all the element is sorted.

Selection sort algorithm and it's implementation.

Average case time complexity of selection sort - O(n2)

Worst case time complexity of selection sort - O(n2)

Best case time complexity of selection sort - O(n2)

Like bubble sort, it is also inefficient for large data sets.  Selection sort is known for it's simplicity and it has performance advantages over more complicated algorithms in certain situations, particularly where auxiliary memory is limited.


Time Complexity of Insertion Sort

Insertion sort algorithm  works by taking one element in each iteration and put it at correct location. At each iteration, it insert the element at it's correct location. This process is repeated until no input element remains.

Insertion sort algorithm and it's implementation.

Best case time complexity of insertion sort - O(n)

Average and worst case time complexity of insertion sort - O(n2)


Time Complexity of QuickSort

QuickSort is a divide and conquer algorithm. In QuickSort, large arrays are divided into smaller sub-arrays and then we recursively sort the smaller sub-arrays.


Best and Average time complexity of quick sort - O(n log n)

Worst case time complexity of quick sort - O(n2)

Time Complexity Of Merge Sort


MergeSort is a Divide and Conquer algorithm. It divides an input array in two halves, calls itself for the two halves and then merges the two sorted halves.

Best and Average time complexity of merge sort - O(n log n)





Find Largest of three Numbers in C, C++

C, C++ Program to Find Largest of Three Numbers
C, C++ Program to Find Largest of Three Numbers
Write a C, C++ program to find largest of three numbers. In this program, We'll take three input numbers and our program will print largest among three numbers.

To solve this problem, first let's write an algorithm to find largest number among three numbers.


Algorithm to Find Largest of three Numbers

1. Declare three variable a ,b, c.

2.  Compare a with b and c. If a is greater than b and c than a is greatest among three numbers.

3. Compare b with a and c. if b is greater than a and c than b is greatest among three numbers.

4. Compare c with a and b. If c is greater than a and b than c is greatest among three numbers.

Program to find second largest element in an array

Find largest element in an array


C Program to Find Largest of  three Numbers


#include <stdio.h>
 
int main(){
 
      int a, b, c;
 
      printf("Enter three numbers: ");
      scanf("%d %d %d", &a, &b, &c);
 
      if(a >= b && a >= c){
         printf("Largest number is %d", a);
 
      }else if(b >= a && b >= c){
         printf("Largest number is %d", b);
 
      }else if(c >= a && c >= b){
         printf("Largest number is %d", c);
 
      } 
      return 0;
}

Output -

Enter three numbers :

14
34
23

Largest number is : 34


Find Largest of three Numbers using Ternary Operator


#include <stdio.h>

int main(void) {
 
    int a, b, c, larg;
 
    printf("Enter three numbers \n");
    scanf("%d %d %d", &a , &b , &c);
 
 
    larg =  (a > b && a > c) ? a : b > c ? b : c ;
 
    printf("Largest number is %d ", larg);

 
    return 0;
}


C++ Program Find Largest of three Numbers


#include <iostream>
using namespace std;

int main() {
 
    int a, b, c;
 
    cout << "Enter three numbers \n";

    /* Taking input */
    cin >> a >> b >> c;
 
    /* If a is greater than b and c. */

    if (a > b && a > c) {
       cout << "Largest number is " << a;

    /* If b is greater than a and c */
    } else if (b > a && b > c) {
       cout << "Largest number is " << b;

    } else {
       cout << "Largest number is "<< c;

    }
 
     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++ Program to Check whether a Character is Vowel or not

Write a C, C++ program to check whether a character is vowel or not.  In this program, We take a input character from user and our code will check whether a input character is vowel or not.


How to Check whether a Character is Vowel or not


1.  Take input character from 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.

Program to count number of vowels in a string

Programming questions on Strings


C++ Program to Check whether a Character is Vowel or not.

#include <iostream>
using namespace std;

int main() {

      /* Declare char. */
 
      char alpha;

      /* Take a input character from user. */

      cout<<" Enter a character\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<<"Entered character is a vowel";
      } else {
          cout<<"Entered character is not a vowel";
       }

       return 0;
}


Output:

Enter a character :  a

Entered character is a vowel.


C Program to Check Whether a Character is Vowel or Not


#include <stdio.h>

int main(void) {
 
      char alpha;

      /* Take a input character from user. */

      printf(" Enter a character\n");
      scanf("%c", &alpha);

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

         printf("Entered character is a vowel");
      } else {
         printf("Entered character is not a vowel");
       }
       
 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

Java Program to Find First Non-Repeating Character in a String

Write a Java program to Find first non-repeated character in a String. Suppose, a user has input AABCDEBFCH now the first non-repeated character in this string is D.

Input     - AABCDEBFCH
Output  - D

Java Programs for practice

C, C++ Program to print first non-repeating character of a string

How to Print First Non-repeated Character of a String

i) Method 1 - Naive Approach

Use two for loops and compare a character with each character of a string. The time complexity for this approach is O(n2).

 for(int i = 0; i < len; i++) {
  
     flag = 0; 
  
     for(int j = 0; j < len; j++) {
   
        /* If it's equal and indexes
           is not same */
        if((str[i] == str[j]) && (i != j)) {
             flag = 1;
             break;
        }
     }

ii) Method 2 - Use hash map to create a key and value pair of character and it's count. This approach is much better as compared to first one.

Traverse a string and create a hash table for character and it's count. If there  is no value stored for a character then set it to 1. Else we increment the character value by 1.

Explanation -



Let's implement a hash map to solve this problem.

Java Program to Find First Non-repeating Character in a String


import java.util.*;

public class FirstNonRepeatedCharacter {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        
        System.out.println("Please enter an input string ");
        
        // Take a input

        Scanner in = new Scanner(System.in);
        
        //Assign value into str

        String str = in.nextLine();
        
        // Length of a string

        int len = str.length();
        
        // Using HashMap

        HashMap<Character, Integer> charcount 
                  = new HashMap<Character, Integer>();
        
        Character ch;
        
        /*Traverse a string and create a hash table for 
          character and it's count. 
          If there  is no value stored for a character then set it to 1. 
          Else we increment the character value by 1 */

        for(int i = 0; i < len; i++) {
            
            ch = str.charAt(i);
            
            /* If character is already exists 
               then increment it's count by 1 */

            if(charcount.containsKey(ch)) {
                
                charcount.put(ch, charcount.get(ch)+1);
                
            } else {
                
                // If character is not exist

                charcount.put(ch, 1);
            }
        }
        
        for (int j = 0; j < len; j++) {
            
            ch = str.charAt(j);
            
            if(charcount.get(ch) == 1){
                
                System.out.println("First non-repeated character 
                                    is " + ch);
                break;
                
            }
        }
    }
    
}



Output -

Please enter an input string AABCDEBFCH

First non-repeated character is D

Java Programming Books