Java finally block after return statement

  • finally block will be executed always even exception occurs.
  • If we explicitly call System.exit() method then only finally block will not be executed if exit() call is before finally block.
  • There are few more rare scenarios where finally block will not be executed.
  1. When JVM crashes
  2. When there is an infinite loop
  3. When we kill the process ex:kill -9 (on unix)
  4. Power failure, hardware error or system crash.
  5. And as we discussed System.exit().
  •  Other than these conditions finally block will be executed always.
  • finally block is meant to keep cleaning of resources. Placing code other than cleaning is a bad practice
  • What happens if we place finally block after return statement? or
  • Does finally block will execute after return statement??
  •  As per the above rules Yes finally will always execute except any interruption like System.exit()  or all above mentioned conditions

 Program #1 : Java example program which explains how finally block will be executed even after a return statement in a method.

  1. package com.instanceofjava.finallyblockreturn;
  2. /**
  3.  * By: www.instanceofjava.com
  4.  * program: does finally gets executed after return statement??
  5.  *
  6.  */
  7. public class FinallyBlockAfterReturn {
  8.  
  9.     public static int Calc(){
  10.         try {
  11.             
  12.             return 0;
  13.         } catch (Exception e) {
  14.             return 1;
  15.         }
  16.  
  17. finally{
  18.             
  19.  System.out.println("finally block will be executed even when we
  20. place after return statement");
  21.         }
  22.  }
  23.     
  24. public static void main(String[] args) {
  25.         
  26.         System.out.println(Calc());         
  27. }
  28.  
  29. }



  
Output:


  1. finally block will be executed even when we place after return statement
  2. 0


 Can we place return statement in finally??
  • Yes we can place return statement in finally and finally block return statement will be executed.
  • But it is a very bad practice to place return statement in finally block.
Program #2 : Java example program which explains finally block with return statement in a method.



finally block after return statement

How to subtract minutes from current time in java



Program #1 : Java Example Program to subtract minutes from given string formatted date time using java 8.


  1. package java8;
  2. /**
  3.  * By: www.instanceofjava.com
  4.  * program: how to subtract minutes from date time using java 8  
  5. *
  6.  */
  7. import java.time.LocalDateTime;
  8. import java.time.format.DateTimeFormatter;
  9.  
  10. public class SubtractMinutesJava{

  11. public static void main(String[] args) {
  12.  
  13.   DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
  14.  
  15.         String currentTime= "2017-10-19 22:00:00";

  16.  
  17.         System.out.println("Before subtraction of minutes from date: "+currentTime);
  18.  
  19.         LocalDateTime datetime = LocalDateTime.parse(currentTime,formatter);
  20.  
  21.         datetime=datetime.minusMinutes(30);
  22.  
  23.         String aftersubtraction=datetime.format(formatter);
  24.         System.out.println("After 30 minutes subtraction from date: "+aftersubtraction);

  25.  
  26.     }
  27.  
  28. }

Output:

  1. Before subtraction of minutes from date: 2017-10-19 22:00:00
  2. After 30 minutes subtraction from date: 2017-10-19 21:30:00

Program #2 : Java Example Program to subtract seconds from given string formatted date time using java 8.
  1. package java8;
  2. /**
  3.  * By: www.instanceofjava.com
  4.  * program: how to subtract seconds from date time using java 8  
  5. *
  6.  */
  7. import java.time.LocalDateTime;
  8. import java.time.format.DateTimeFormatter;
  9.  
  10. public class SubtractSecondsJava{

  11. public static void main(String[] args) {
  12.  
  13.   DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
  14.  
  15.         String currentTime= "2017-10-19 22:00:00";

  16.  
  17.         System.out.println("Before subtraction of seconds from date time: "+currentTime);
  18.  
  19.         LocalDateTime datetime = LocalDateTime.parse(currentTime,formatter);
  20.  
  21.         datetime=datetime.minusSeconds(30);
  22.  
  23.         String aftersubtraction=datetime.format(formatter);
  24.         System.out.println("After 30 seconds subtraction from date time: "+aftersubtraction);

  25.  
  26.     }
  27.  
  28. }

Output:

  1. Before subtraction of seconds from date time: 2017-10-19 22:00:00
  2. After 30 seconds subtraction from date time: 2017-10-19 21:59:30

Program #3 : Java Example Program to subtract seconds from current date time using java 8.


how to subtract minutes from java date time

How to subtract N hours from current date time using java 8

  • We have already seen how to subtract number of days from java using calendar and using java 8.
  • How to subtract X days from a date using Java calendar and with java 8 
  • Now we will discuss here how to subtract hours from java 8 localdatetime.
  • Some times we will get out date time in string format so we will convert our string format date to java 8 LocaDateTime object.
  • We can user DateTimeFormatter to tell the format of date time to LocalDateTime class.
  • LocalDateTime datetime = LocalDateTime.parse(currentTime,formatter);
  • LocalDateTime has minusHours(numberOfHours) method to subtract hours from date time.
  • Lets see an example java program to subtract hours from java date time using java 8 LocalDateTime class.
  • How to subtract hours from java 8 date time.



Program #1 : Java Example Program to subtract hours from given string formatted date time using java 8.



  1. package java8;
  2. /**
  3.  * By: www.instanceofjava.com
  4.  * program: how to subtract hours from date time using java 8  
  5. *
  6.  */
  7. import java.time.LocalDateTime;
  8. import java.time.format.DateTimeFormatter;
  9.  
  10. public class SubstractHoursJava{
  11. public static void main(String[] args) {
  12.  
  13.   DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
  14.  
  15.         String currentTime= "2017-10-19 22:00:00";
  16.  
  17.         System.out.println("Before subtraction of hours from date: "+currentTime);
  18.  
  19.         LocalDateTime datetime = LocalDateTime.parse(currentTime,formatter);
  20.  
  21.         datetime=datetime.minusHours(4);
  22.  
  23.         String aftersubtraction=datetime.format(formatter);
  24.         System.out.println("After 4 hours subtraction from date: "+aftersubtraction);
  25.  
  26.     }
  27.  
  28. }

Output:

  1. Before subtraction of hours from date: 2017-10-19 22:00:00
  2. After 4 hours subtraction from date: 2017-10-19 18:00:00

  • Now we will see how to subtract one hour from current date time in java using java 8 

Program #2 : Java Example Program to subtract one hour from given current date time using java 8.

  1. package java8;
  2. /**
  3.  * By: www.instanceofjava.com
  4.  * program: how to subtract hours from date time using java 8  
  5. *
  6.  */
  7. import java.time.LocalDateTime;
  8. import java.time.format.DateTimeFormatter;
  9.  
  10. public class SubtractOneHour {
  11.  
  12. public static void main(String[] args) {
  13.  
  14.   DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd H:mm:ss");
  15.  
  16.         LocalDateTime datetime = LocalDateTime.now();
  17.         System.out.println("Before subtraction of hours from date: "+datetime.format(formatter));
  18.  
  19.        datetime=datetime.minusHours(1);
  20.        String aftersubtraction=datetime.format(formatter);
  21.        System.out.println("After 1 hour subtraction from date: "+aftersubtraction);
  22.  
  23.     }
  24.  
  25. }
Output:


  1. Before subtraction of hours from date: 2017-10-19 23:14:12
  2. After 1 hour subtraction from date: 2017-10-19 22:14:12

subtract hours from java date time

C program to insert an element in an array

  • Program to insert an element in an array at a given position
  • C program to insert an element in an array without using function



Program #1: Write a c program to insert an element in array without using function


  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. int main(int argc, char *argv[])
  5. {
  6.   int insarray[100], pos, c, n, value;
  7.  
  8.   printf("Enter number of elements of array\n");
  9.    scanf("%d", &n);
  10.  
  11.    printf("Enter all %d elements\n", n);
  12.  
  13.    for (c = 0; c < n; c++)
  14.       scanf("%d", &insarray[c]);
  15.  
  16.    printf("Enter the specific position where you wish to insert an element in array\n");
  17.    scanf("%d", &pos);
  18.  
  19.    printf("Enter the value to insert\n");
  20.    scanf("%d", &value);
  21.  
  22.    for (c = n - 1; c >= pos - 1; c--)
  23.       insarray[c+1] = insarray[c];
  24.  
  25.    insarray[pos-1] = value;
  26.  
  27.    printf("Resultant array is\n");
  28.  
  29.    for (c = 0; c <= n; c++)
  30.       printf("%d\n", insarray[c]);
  31.  
  32. getch();
  33. }
Output:

insert element in array c

C program to delete an element in an array

  • Write a c program to insert and delete an element in array
  • Write a c program to delete an element in an array
  • C Program to Delete the Specified Integer from an Array without using function



Program #1: Write a c program to insert and delete an element in array


  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. int main(int argc, char *argv[])
  5. {
  6.   
  7.      int array[10];
  8.  
  9.     int i, n, position, element, exist = 0;
  10.  
  11.  
  12.     printf("Enter number of elements \n");
  13.  
  14.     scanf("%d", &n);
  15.  
  16.     printf("Enter the elements\n");
  17.  
  18.     for (i = 0; i < n; i++)
  19.  
  20.     {
  21.  
  22.         scanf("%d", &array[i]);
  23.  
  24.     }
  25.  
  26.     printf("Input array elements are\n");
  27.  
  28.     for (i = 0; i < n; i++)
  29.  
  30.     {
  31.  
  32.         printf("%d\n", array[i]);
  33.  
  34.     }
  35.  
  36.     printf("Enter the element to be deleted from array\n");
  37.  
  38.     scanf("%d", &element);
  39.  
  40.     for (i = 0; i < n; i++)
  41.  
  42.     {
  43.  
  44.         if (array[i] == element)
  45.  
  46.         {
  47.             exist = 1;
  48.  
  49.             position = i;
  50.  
  51.             break;
  52.  
  53.         }
  54.  
  55.     }
  56.  
  57.     if (exist == 1)
  58.  
  59.     {
  60.  
  61.         for (i = position; i <  n - 1; i++)
  62.  
  63.         {
  64.  
  65.             array[i] = array[i + 1];
  66.  
  67.         }
  68.  
  69.         printf("array after deletion  \n");
  70.  
  71.         for (i = 0; i < n - 1; i++)
  72.  
  73.         {
  74.  
  75.             printf("%d\n", array[i]);
  76.  
  77.         }
  78.  
  79.     }
  80.  
  81.     else
  82.  
  83.         printf("Given element %d is not exist in the array \n", element);
  84. getch();
  85. }
Output:


delete array element c

Apache Spark create rdd from an array java | convert an array in to RDD

  • RDD is the spark's core abstraction.
  • Full form of RDD is resilient distributed dataset.
  • Each RDD will split into multiple partitions which may be computed in different machines of cluster
  • We can create Apache spark RDD in two ways
    1. Parallelizing a collection
    2. Loading an external dataset.
     
  • So Creating RDD from an array comes in under Parallelizing a collection.
  • Let us see Apache spark an example program to convert an array into RDD.



Program #1: Write a Apache spark java example program to create simple RDD using parallelize method of JavaSparkContext. convert an array in to RDD


  1.  package com.instanceofjava.sparkInterview;
  2.  
  3. import java.util.Arrays;
  4.  
  5. import org.apache.spark.SparkConf;
  6. import org.apache.spark.api.java.JavaRDD;
  7. import org.apache.spark.api.java.JavaSparkContext;
  8.  
  9. /**
  10.  *  Apache spark examples:RDD in spark example program  
  11. *  converting an array to RDD
  12.  * @author www.instanceofjava.com
  13.  */
  14. public class SparkTest {
  15.     
  16.     public static void main(String[] args) {
  17.         
  18.         SparkConf conf = new
  19. SparkConf().setMaster("local[2]").setAppName("InstanceofjavaAPP");
  20.         JavaSparkContext sc = new JavaSparkContext(conf);
  21.         
  22.         String[] arrayStr={"convert array to rdd","convert array into rdd"};
  23.         
  24.         JavaRDD<String> strRdd=sc.parallelize(Arrays.asList(arrayStr));
  25.         System.out.println("apache spark rdd created: "+strRdd);
  26.         
  27.         /**
  28.          * Return the first element in this RDD.
  29.          */
  30.         System.out.println(strRdd.first());
  31.         
  32.     }
  33.  
  34. }
  35. }

Output:

  1. apache spark rdd created: ParallelCollectionRDD[0] at parallelize at SparkTest.java:24
  2. convert array to rdd



convert an array to rdd

How to create rdd in apache spark using java

  • RDD is the spark's core abstraction.
  • Full form of RDD is resilient distributed dataset.
  • That means it is immutable collection of objects.
  • Each RDD will split into multiple partitions which may be computed in different machines of cluster
  • We can create Apache spark RDD in two ways
    1. Parallelizing a collection
    2. Loading an external dataset.
  • Now we sill see an example program on creating RDD by parallelizing a collection.
  • In Apache spark JavaSparkContext  class providing parallelize() method.
  • Let us see the simple example program to create Apache spark RDD in java



Program #1: Write a Apache spark java example program to create simple RDD using parallelize method of JavaSparkContext.

  1. package com.instanceofjava.sparkInterview;
  2. import java.util.Arrays;
  3.  
  4. import org.apache.spark.SparkConf;
  5. import org.apache.spark.api.java.JavaRDD;
  6. import org.apache.spark.api.java.JavaSparkContext;
  7.  
  8. /**
  9.  *  Apache spark examples:RDD in spark example program
  10.  * @author www.instanceofjava.com
  11.  */
  12. public class SparkTest {
  13.     
  14.  public static void main(String[] args) {
  15.         
  16.  SparkConf conf = new SparkConf().setMaster("local[2]").setAppName("InstanceofjavaAPP");
  17.  JavaSparkContext sc = new JavaSparkContext(conf);
  18.         
  19.  JavaRDD<String> strRdd=sc.parallelize(Arrays.asList("apache spark element1","apache
  20. spark element2"));
  21.  System.out.println("apache spark rdd created: "+strRdd);
  22.         
  23. /**
  24.  * Return the first element in this RDD.
  25.  */
  26. System.out.println(strRdd.first());
  27.  }
  28.  
  29. }
  30.  
  31. }

Output:

  1. apache spark rdd created: ParallelCollectionRDD[0] at parallelize at SparkTest.java:21
  2. spark element1


create apache spark rdd java

Remove whitespace from string javascript

  • To remove white space in a string in JavaScript at the starting and ending. i.e both sides of a string we have trim() method in JavaScript.
  •  By Using .trim() method we can remove white spaces at both sides of a string.
  • var str = "       instanceofjava.com        ";
    alert(str.trim());
  • Will alert a popup with instanceofjava.com.
Javascript remove last character if comma 
  • If  we want to remove last character of a string then we need to use replace method in JavaScript.
  • str = str.replace(/,\s*$/, "");
  • We can also use slice method to remove last character.
remove white spaces in javascript

Remove specific characters from a string in Javascript


  • To remove specific character from string in java script we can use

  1. var string = 'www.Instanceofjava.com'; 
  2. string.replace(/^www.+/i, ''); 'Instanceofjava.com'

C program for addition subtraction multiplication and division using switch case

  • Write a C program to simulate a simple calculator to perform arithmetic operations like a and division only on integers. Error message should be reported if any attempt is made to divide by zero    
  • C program for addition subtraction multiplication and division using switch case
  • Write a c program to perform arithmetic operations using switch case
  • C program to add subtract multiply and divide two numbers using functions
Program #1: Write a c program to perform arithmetic operations using switch case



  1. #include <stdio.h>
  2. #include <conio.h>
  3.  
  4. int main()
  5. {
  6.     char oper;            /* oper is an operator to be selected */
  7.     float n1, n2, result;
  8.  
  9.     printf ("Simulation of a Simple Calculator\n\n");
  10.  
  11.     printf("Enter two numbers\n");
  12.     scanf ("%f %f", &n1, &n2);
  13.  
  14.     fflush (stdin);
  15.  
  16.     printf("Enter the operator [+,-,*,/]\n");
  17.     scanf ("%c", &oper);
  18.  
  19.     switch (oper)
  20.        {
  21.         case '+': result = n1 + n2;
  22.               break;
  23.         case '-': result = n1 - n2;
  24.               break;
  25.         case '*': result = n1 * n2;
  26.               break;
  27.         case '/': result = n1 / n2;
  28.               break;
  29.         default : printf ("Error in operation\n");
  30.               break;
  31.     }
  32.  
  33.     printf ("\n%5.2f %c %5.2f= %5.2f\n", n1,oper, n2, result);
  34. getch();
  35. }


Output:

algorithm for switch case in c


  • Output
    Simulation of Simple Calculator

    Enter two numbers
    3 5
    Enter the operator [+,-,*,/]
    +

     3.00 +  5.00=  8.00
     
  • RUN2
    Simulation of Simple Calculator

    Enter two numbers
    12.75
    8.45
    Enter the operator [+,-,*,/]
    -

    12.75 -  8.45=  4.30
  • RUN3
    Simulation of Simple Calculator

    Enter two numbers
    12 12
    Enter the operator [+,-,*,/]
    *

    12.00 * 12.00= 144.00
     
  • RUN4
    Simulation of Simple Calculator

    Enter two numbers
    5
    9
    Enter the operator [+,-,*,/]
    /

     5.00 /  9.00=  0.56

Print semicolon without using semicolon in java

  • Write a program to print a semicolon without using a semicolon anywhere in the code in java.
  • Write a program to print"hello world"without using semicolon anywhere in the code.\
  • Yes we can print ";" without using semicolon in java by using printf in java.
  • Format text using printf in java here we have provided information about how to format text using printf in java.
  • In the same way we can print ";" using printf .
  • ASCII value for ";" is 59. So if we print 59 in character format it will print ;
  • System.out.printf("%C",59).
  • But in java program end of every statement we need to keep ";". To eliminate this we can use if condition.
  • Keep print statement inside if condition and it will print the ";" now.
  • Now let us see an example java program to print a semicolon without using a semicolon anywhere in the code in java.


Program #1: Write a program to print a semicolon without using a semicolon anywhere in the code in java 


  1. package instanceofjava;
  2. /**
  3.  * Print semicolon without using semicolon in java
  4.  * Print hello world without using semicolon java program code
  5.  * @author www.instanceofjava.com
  6.  */
  7. public class PrintSemiColon {
  8.     
  9. public static void main(String[] args) {
  10.     
  11.     if(System.out.printf("%C",59) != null){
  12.         
  13.     } 
  14.     
  15. }
  16. }

Output:

  1. ;


Program #1: Write a program to print hello world without using a semicolon anywhere in the code in java

  1. package instanceofjava;
  2. /**
  3.  * Print semicolon without using semicolon in java
  4.  * Print hello world without using semicolon java program code
  5.  * @author www.instanceofjava.com
  6.  */
  7. public class PrintSemiColon {
  8.     
  9. public static void main(String[] args) {
  10.     
  11.     if(System.out.printf("Hello World")!=null){
  12.         
  13.     }
  14.     
  15.     
  16. }
  17. }

Output:

  1. Hello World


print semilolon without semicolon

C programming power function example program

  • C program to find power of a number using function.
  • Write a c program to find power of a number using function recursion



 Program #1 : Write a c program to find power of a number without using function recursion

  1.  #include<stdio.h>
  2. int main(){
  3.   int power,num,i=1;
  4.   long int sum=1;
  5.   printf("Enter a number:\n ");
  6.   scanf("%d",&num);
  7.   printf("\nEnter power:\n ");
  8.   scanf("%d",&power);
  9.   while(i<=power){
  10.             sum=sum*num;
  11.             i++;
  12.   }
  13.   printf("\n%d to the power %d is: %ld",num,power,sum);
  14.   getch();
  15. }

  Output:


power of number in c



  Program #2 : Write a c program to find power of a number using function recursion


  1.  #include<stdio.h>
     
  2. void powerofnumber(int power, int num);
  3. int main(){
  4.   int power,num,i=1;
  5.   long int sum=1;
  6.   printf("Enter a number:\n ");
  7.   scanf("%d",&num);
  8.   printf("\nEnter power:\n ");
  9.   scanf("%d",&power);
  10.   powerofnumber(power,num);
  11.   return 0;
  12. }
  13.  
  14. void powerofnumber(int power, int num){
  15.      int i=1,sum=1;
  16.      while(i<=power){
  17.             sum=sum*num;
  18.             i++;
  19.   }
  20.   printf("\n%d to the power %d is: %ld",num,power,sum);
  21.  
  22. }
 

Output:


  1. Enter a number:
  2.  23
  3.  
  4. Enter power:
  5.  3
  6.  
  7. 23 to the power 3 is: 12167

C program to display characters from a to z using loop

  • C program to display characters from a to z using loop.
  • We can print all alphabets starting from A to Z using for loop.
  • Take a char variable and using for loop iterate it from A to Z.
  • Let us see an Example C program to print A to Z using for loop.



Program #1: Write a C program to print or display characters from A to Z using for loop.

  1. #include <stdio.h>
  2. int main()
  3. {
  4.     char c;
  5.  
  6.     for(c = 'A'; c <= 'Z'; ++c)
  7.       printf("%c ", c);
  8.     
  9.     return 0;
  10. }

   Output:

  1. A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

Program #2: Write a C Program to Display English Alphabets in Uppercase and Lowercase

  1. #include <stdio.h>
  2. int main()
  3. {
  4.      char c;
  5.  
  6.     printf("Enter u to display alphabets in uppercase. And enter l to display alphabets in
  7. lowercase: ");
  8.     scanf("%c", &c);
  9.  
  10.     if(c== 'U' || c== 'u')
  11.     {
  12.        for(c = 'A'; c <= 'Z'; ++c)
  13.          printf("%c ", c);
  14.     }
  15.     else if (c == 'L' || c == 'l')
  16.     {
  17.         for(c = 'a'; c <= 'z'; ++c)
  18.          printf("%c ", c);
  19.     }
  20.     else
  21.        printf("Error! You entered invalid character.");
  22.     getch();
  23. }
     

  Output:

print a to z c program

Convert string to integer c programming

  • We can convert string to integer in c Programming by using atoi() function.
  • atoi() is a library function from C. 
  • int atoi(const char *str) ;
  • Now we will write a C program to convert String format number to integer.
  • Read input from user as string.
  • Convert string to integer using atoi() function.

Program #1: Write a C program to convert String to integer in c Programming.

  1. #include<stdio.h>
  2. #include<stdlib.h>
  3.  
  4. int main() {
  5.    int number;
  6.    char number_string[3];
  7.  
  8.    printf("Please Enter a number : ");
  9.    scanf("%s", number_string);
  10.  
  11.    number = atoi(number_string);
  12.    printf("\n number_string : %d", number);
  13.  
  14.    getch();
  15. }


 Output:


convert String to int in c program

Bubble sort algorithm in c with explanation

  • Bubble sort is one of the example of sorting algorithm.
  • Bubble sort in data structure
  • Bubble sort is a procedure of sorting elements in ascending or descending order.
  • If we want to sort an array of numbers [4,2,3,1]  using bubble sort it will return [1,2,3,4] after sorting in ascending order.


 Bubble sort in c with explanation

  • Bubble sort algorithm of ascending order will move higher valued elements to right and lower value elements to left.
  • For this we need to compare each adjacent elements in an array and check they are in order or not if not swap those two elements.
  • After completion of first iteration highest value in the array will be moved to last or final position.
  • In the worst case all the highest elements in array like [9 8 7 5 4] completely in reverse order so we need to iterate all of the elements in N times.
  • Repeat this process N- 1 time in worst case to sort set of elements.
  • Worse case complexity : O(n2
  • In the best case scenario all the elements are already in sorted order so one iteration with no swaps required.
  • Best case complexity: O(n)
  • Let us see the graphical representation of explanation of bubble sort algorithm in c programming language.

Bubble sort algorithm with example diagram

bubble sort algorithm in c

Bubble sort algorithm pseudocode:

Program #1 : Write a C program to sort list of elements using bubble sort algorithm.

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. //Bubble sort algorithm in c
  4. //www.instanceofjava.com
  5. int main(int argc, char *argv[])
  6. {
  7.    int array[100], n,i,j,k, swap;
  8.  
  9.   printf("Enter number of elements to sort\n");
  10.   scanf("%d", &n);
  11.  
  12.   printf("Enter %d elements \n", n);
  13.   for (i = 0; i< n; i++)
  14.     scanf("%d", &array[i]);
  15.  
  16.   printf("\nBefore sorting \n ");
  17.    for (k = 0; k < n; k++) {
  18.       printf("%5d", array[k]);
  19.    }
  20.  
  21.    for (i = 1; i < n; i++) {
  22.       for (j = 0; j < n - 1; j++) {
  23.          if (array[j] > array[j + 1]) {
  24.             swap = array[j];
  25.             array[j] = array[j + 1];
  26.             array[j + 1] = swap;
  27.          }
  28.       }
  29.       
  30.       }
  31.  
  32.  printf("\nAfter Bubble sort elements are:\n");
  33.    for (k = 0; k < n; k++) {
  34.       printf("%5d", array[k]);
  35.    }
  36.  
  37.   return 0;
  38. }

 Output:


bubble sort algorithm in c program recursive

  • Now we will see program on recursive bubble sort algorithm in c
  • Bubble sort using recursive function in c

Program #2: Write a c program for bubble sort using recursion


  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. //Bubble sort algorithm in c
  4. //www.instanceofjava.com
  5. void bubblesort(int array[], int n);
  6. int main(int argc, char *argv[])
  7. {
  8.    int array[10], n,i,k;
  9.  
  10.   printf("Enter number of elements to sort\n");
  11.   scanf("%d", &n);
  12.  
  13.   printf("Enter %d elements \n", n);
  14.   for (i = 0; i< n; i++)
  15.     scanf("%d", &array[i]);
  16.  
  17.   printf("\nBefore sorting \n ");
  18.    for (k = 0; k < n; k++) {
  19.       printf("%5d", array[k]);
  20.    }
  21.  bubblesort(array,n);
  22.    
  23.   getch();
  24. }
  25.  
  26. void bubblesort(int array[], int n){
  27.       int  i,j,k, swap;
  28.   for (i = 1; i < n; i++) {
  29.       for (j = 0; j < n - 1; j++) {
  30.          if (array[j] > array[j + 1]) {
  31.             swap = array[j];
  32.             array[j] = array[j + 1];
  33.             array[j + 1] = swap;
  34.          }
  35.       }
  36.       
  37.       }
  38.  
  39.  printf("\nAfter Bubble sort elements are:\n");
  40.    for (k = 0; k < n; k++) {
  41.       printf("%5d", array[k]);
  42.    }    
  43. }

Output:

  1. Enter number of elements to sort
  2. 6
  3. Enter 6 elements
  4. 9 8 2 3 5 1
  5.  
  6. Before sorting
  7.      9    8    2    3    5    1
  8. After Bubble sort elements are:
  9.     1    2    3    5    8    9

C program to find ASCII value of a string or character

  • Convert string to ascii c programming.
  • C program to find ascii value of a string or character.
  • C program to print ascii value of alphabets.
  • Now we will write a C program to print ASCII value of each character of a String.



Program #1: Write a C programming code to print ASCII value of String.


  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. int main(int argc, char *argv[])
  5. {
  6.     char str[100];
  7.     int i=0;
  8.     printf("Enter any string to get ASCII Value of each Character \n");
  9.     scanf("%s",str);
  10.  
  11.     printf("ASCII values of each characters of given string:\n ");
  12.     while(str[i])
  13.          printf("%d \n",str[i++]);
  14.         
  15.     getch();
  16. }


Output:


Print Ascii value of string character c program

C program to print 1 to 100 without using loop

  • Print 1 to 100 without using loop in c
  • We print 1 to n numbers without using any loop.
  • By using recursive function in C Programming we can print 1 to 100 or 1 to n numbers.
  • Now We will write a C program to print one to 100 without using any loops.
  • Print 1 to 100 without loop and recursion



 Program #1: Write a C program to print 1 to 100 without loop and using recursive function.


  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. int print(int num);
  4. int main(int argc, char *argv[])
  5. {
  6.     int number = 1;
  7.  
  8.     print(number);
  9.  
  10.    return 0;
  11. }
  12. int print(int number){
  13.     if(number<=100){
  14.          printf("%d ",number);
  15.          print(number+1);
  16.     }
  17. }
   
Output:


print 1 to 100 in c

C program to print given number in words

  • Write a program to input a digit and print it in words
  • C program to print number in words using switch cas.
  • Now we will see how to convert number /digits in to words in C programming.
  • Get the input from the user using Scanf() function.
  • Using while loop and % operator and get the each number and use switch case to print corresponding word for the current number.



Program #1: write a program in c that reads the digits and then converts them into words

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. int main(int argc, char *argv[])
  4. {
  5.  int number,i=0,j,digit;
  6.     char * word[1000];
  7.  
  8.     printf("Enter any integer to print that in words: ");
  9.     scanf("%d",&number);
  10.  
  11.     while(number){
  12.  
  13.     digit = number %10;
  14.     number = number /10;
  15.  
  16.          switch(digit){
  17.              case 0: word[i++] = "zero"; break;
  18.              case 1: word[i++] = "one"; break;
  19.              case 2: word[i++] = "two"; break;
  20.              case 3: word[i++] = "three"; break;
  21.              case 4: word[i++] = "four"; break;
  22.              case 5: word[i++] = "five"; break;
  23.              case 6: word[i++] = "six"; break;
  24.              case 7: word[i++] = "seven"; break;
  25.              case 8: word[i++] = "eight"; break;
  26.              case 9: word[i++] = "nine"; break;
  27.  
  28.         }
  29.     }
  30.    
  31.     for(j=i-1;j>=0;j--){
  32.          printf("%s ",word[j]);
  33.     }
  34.  return 0;
  35. }
  
Output:


print numbers in words c program

C program for swapping of two strings

  • C program for swapping of two strings.
  • C program to swap two strings without using library functions.
  • Now we will swap two strings without using library functions and by using arrays in java.
  • Now we will write a C program on how to swap two strings.



Program #1 Write a C program to swap two strings


  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. int main(int argc, char *argv[])
  4. {
  5.  int i=0,j=0,k=0;
  6.   char str1[20],str2[20],temp[20];
  7.   puts("Enter first string");
  8.   gets(str1);
  9.   puts("Enter second string");
  10.   gets(str2);
  11.   printf("Before swapping the strings \n");
  12.   puts(str1);
  13.   puts(str2);
  14.   while(str1[i]!='\0'){
  15.              temp[j++]=str1[i++];
  16.   }
  17.   temp[j]='\0';
  18.   i=0,j=0;
  19.   while(str2[i]!='\0'){
  20.               str1[j++]=str2[i++];
  21.   }
  22.   str1[j]='\0';
  23.   i=0,j=0;
  24.   while(temp[i]!='\0'){
  25.               str2[j++]=temp[i++];
  26.   }
  27.   str2[j]='\0';
  28.   printf("After swapping the strings are\n");
  29.   puts(str1);
  30.   puts(str2);
  31.   getch();
  32. }

  
Output:


swap strings in c program

Select Menu