Blog

  • Java Variables

    What is Variable in Java?

    The variable is the basic unit of storage which holds the value while the program is executed. We can also say that it is a name given to the memory location. A variable is defined by data-types provided by Java.

    It may be string, int, float, char, and boolean.

    Declaring a Variable in Java:

    Certain rules are needed to be followed before declaring the variables:

    • The first character must be a letter.
    • A variable name can consist of letters A-Z, a-z, digits 0-9, and two special characters such as underscore(_) and dollar Sign($).
    • Blank spaces cannot be used in variable names.
    • Java keywords cannot be used as variable names.
    • Variable names are case-sensitive.

    Syntax to declare Variables:

    data_type variable_name = value;

    Here, data_type means one of the Java data-types mentioned above. variable_name is the name that must be assigned to it, you can give any name suitable for it. The equal sign(=) is an assignment Operator used to assign the value of R.H.S. to L.H.S.

    Example: Demonstration of assigning value to different data-types

     int num = 20;
     String name = "Daniel";
     float floatNum = 7.98f;
     char alphabet = 'D';
     boolean bool = true;

    Types of Variables in Java:

    • local variable
    • instance variable
    • static variable

    Following declaration help us to understand the position of each of these three variables:

     class Example
     {  
      int Num1 = 30;//instance variable  
    
      static int Num2 = 40;//static variable 
      
      void method_Name()
      {  
      int num3 = 60;//local variable  
      }  
     }

    1. Local Variable:

    A variable that is declared within the body of the method or constructor is called a local variable. This variable is used only within that block or method where it was created other classes cannot access it. And is destroyed after exiting the method or block. Initialization of Local Variables is necessary.

    Example of Local variable in Java:

      public class Employees
      { 
        public void EmployeeInfo() 
        { 
          // local variable age 
          int age = 0;
          String name = "Prashant";
            
          age = age + 30; 
          System.out.println("Employee age is : " + age); 
          System.out.println("Employee name is : " + name ); 
        } 
      
        public static void main(String args[]) 
        { 
          Employees emp = new Employees(); 
          emp.EmployeeInfo(); 
        } 
      }

    Output of local variable in Java:

     Employee age is : 30
     Employee name is : Prashant

    2. Instance Variable:

    These are the non-static variable that is declared within the class but outside the method or constructor. With the creation of Objects, Instance Variable is created and destruction of an object destroys the variables. And can be accessed only by creating objects. Initialization of Instance Variable is not necessary as it is 0 by default.

    Example of Instance variable in Java:

     public class Employees
     {
        // this instance variable  
        String name;
        int age;
    
        public Employees (String EmployeeName)
        {
          name = EmployeeName;
        }
    
        public void EmpAge(int EmployeeAge)
        {
          age = EmployeeAge;
        }
    
        public void Display()
        {
          System.out.println("Employee name: " + name ); 
          System.out.println("Employee  age :" + age); 
        }
    
        public static void main(String args[])
        {
          Employees r = new Employees("Prashant");
          r.EmpAge(20);
          r.Display();
        }
     }

    Output of Instance variable in Java:

    Employee name: Prashant
    Employee  age :20

    3. Static variable:

    These variables are also known as class Variables. These are declared just like Instance Variable that within the class but outside the constructor or method but the difference is that static variable is declared using static keyword. Unlike Instance variable, only one static variable is created its value remains the same for all objects no matter how many objects user creates. Here initialization is not mandatory, it is 0 by default.

    Example of Static variable in Java:

     public class Employees
     {
        //static variable
        static int id = 1101;
    
      public static void main(String[] args)
      {
        
        Employees emp = new Employees();
    
       // Call static variable using object reference variable
        int a = emp.id;
    
        
        System.out.println("Employee ID: ");
        System.out.println(Employees.id);
      }
     }

    Output of Static variable in Java:

    Employee ID: 
    1101

  • Comparison between JDK, JRE and JVM

    This post contains the difference between JDK, JRE, and JVM. Let’s understand the difference between them first.
    JVM: Java Virtual Machine
    JDK: Java Development Kit
    JRE: Java Runtime Environment

    Comparison between JDK, JRE, and JVM

    JDK

    It stands for Java Development Kit. It is the tool necessary to compile, document and package Java programs. It contains JRE + development tools and is an implementation of any one of the following Java Platforms released by Oracle:

    1. Standard Edition Java Platform
    2. Enterprise Edition Java Platform
    3. Micro Edition Java Platform

    JRE

    It stands for Java Runtime Environment. JRE refers to a runtime environment in which Java bytecode can be executed and used for developing java applications with set of libraries.

    It’s an implementation of the JVM and is physically exists.

    JVM

    JVM stands for Java Virtual Machine, which is an abstract machine that provides a runtime environment to run Java programs. JVM is the specification that must be implemented in the computer system.

    There are three notations in JVM:

    • Specification
    • Implementation
    • Runtime Instance.

  • Java – Basic Syntax

    The syntax of the Java programming language is the set of rules for writing the java programs and defining its interpretation. Java program is the collection of classes and objects that communicate with each other via. method. It is the program structure.

    There are certain features that are omitted such as operator overloading or unsigned integer types, also there are no global functions or variables, but there are data members which are regarded as global variables.

    Before starting programs, it is very important to remember the following points.

    1. Case Sensitivity:

    Java is case sensitive, which means identifier Hello, heLlO and hello, all have a different meaning in Java.

    2. Class Names:

    Class names should always begin with Upper Case. If more than one word is used to form the name of the class, then each inner word’s first letter should be in Upper Case.

    Example: class MyFirstJavaLesson, class StudentsDetails, etc.

    3. Method Names:

    All method names should begin with a Lower Case letter. If more than one word is used to form the name of the method, then each inner word’s first letter should be in Upper Case.

    Example: public void myFirstMethod(), public void myStudentDetails() etc.

    Note: public static void main(String args[]):
    All Java program processing begins from the main() method which is a mandatory part of every Java program.

    4. Program File Name:

    The name of the program file should always match the class name. While saving the file, it should be saved with the class name and append ‘.java’ to the end of the name. Note that if it doesn’t match with the class name then the program will not work.

    Example: consider that ‘MyFirstJavaCode’ is the class name. Then the file should be saved with the name ‘MyFirstJavaProgram.java’.

    JAVA Basic Example to print “Hello World”:

    This the very basic way to write a program. The program below print “Hello World”.

    public class JavaBasic //JavaProgram is the class name
     {
      public static void main(String args[]) //main() method
      {
        System.out.println("Hello World"); //Prints hello world
      }
     }

    This shows the format for writing java code in code editor. This is the basic one. To learn more on how to write java with function and multiple classes, navigate through our website and learn more.


  • Java Introduction

    Java is a popular general-purpose, high level, modern programming language, and computing platform. It is fast, reliable, secure, and dynamic, with the ability to fit the needs of virtually any type of application.

    It is Platform Independent, which means the user only needs to write a program once and it can be run on a number of different platforms such as Windows, Mac OS, and the various versions of UNIX

    It was created by James Gosling from Sun Micro-systems (Sun) in 1991. It was first publicly released in 1995 with the version of Java (Java 1.0). According to Oracle, Java runs on 3 billion devices worldwide

    Nowadays, Java is used almost in every field that is desktop to web applications, mobile applications, in gaming consoles, cell phones to the Internet, data connection, servers, and many more.

     Main Features of Java:

    • Object-Oriented
    • Platform Independent
    • Simple and secure
    • Portable
    • Robust
    • Dynamic
    • Multi-threaded
    • High Performance
    • Compiled and Interpreted
    • Distributed.

    JAVA Basic Example to print “Hello World”:

    public class JavaBasic //JavaProgram is the class name
        {
         public static void main(String args[]) //main() method
         {
            System.out.println("Hello World"); //Prints hello world
         }
        } 

    Let’s understand briefly on each of the features.

    1. Object-Oriented:

    Java is an object-oriented programming language. OOP divides the program into a number of objects and makes it simpler. This Object has some data and behavior which is used inflow of data from one function to another. Users can easily extend java as it is based on Object Model. Therefore understanding OOP is an important step to learn Java Programming.

    Basic concepts of OOPs are:

    • Object
    • Class
    • Inheritance
    • Polymorphism
    • Abstraction
    • Encapsulation

    2. Platform Independent:

    Unlike other programming languages such as C, C++, etc, which require a specific platform to be compiled whereas Java is compiled into byte-code and this byte-code is Platform Independent.

    This means Java is only required to write-once and can be run on any platform such as Windows, Linux, Mac OS, etc. This byte-code is interpreted by the Java Virtual Machine (JVM).

    3. Simple and secure:

    Java is very easy to learn, clean, and easy to understand. Java language is a simple programming language because of its C++ syntax.

    Java is also best known for the security that it provides and enables us to develop virus-free systems. it is secured because java programs run inside the virtual machine sandbox.

    4. Portable:

    As mentioned above, the byte-code is Platform Independent and can be carried to any other platform for execution of Java program that makes Java code portable.

    5. Robust:

    Robust means strong. Java is strong and reliable because of its ability for early checking for errors, mainly on a compilation error and run-time checking.

    6. Dynamic:

    Since Java is designed to adapt to a transformed environment, it makes java dynamic. it is considered to be more dynamic than C or C++. Java supports the dynamic loading of classes and compilation and garbage collection.

    7. Multi-threaded:

    This feature in Java allows Java to perform more than one task at once by defining multiple threads for maximum utilization of CPU. The advantage of the use of Multi-threaded is that it does not require to occupy space in memory for each thread instead it shares the common memory space.

    8. High Performance:

    Java-enabled High performance by introducing JIT- Just In Time compiler, that is the compiler only compiles the code or method that is called, making the compilation process faster and consume less-time.

    9. Compiled and Interpreted:

    Java has both Compiled and Interpreted feature where the compilation feature allows to create byte code after compilation. And after, the byte codes are converted into Machine Language with the help of the Interpreter. Hence both the features are required for the execution of Java Code.

    10. Distributed:

    Java is distributed because it allows users/developers to create distributed applications that are designed to run on computer networks. RMI(Remote Method Invocation) and EJB(Enterprise Java Beans) are used for creating distributed applications.

    In other words, this feature allows the user to access the files from any machine that is connected to each other on the internet.

    These are some of the features of java.


  • Dining Philosophers problem in C

    In this article, you will learn about the C program to solve Dining Philosophers problem.

    The Dining Philosophers Problem:

    Let there be 5 philosophers (for example) sitting around a round table for dinner. Each philosopher needs two forks to eat but there are only 5 forks (equal to the number of philosophers around the table).

    A philosopher may eat if he/she can pick up two adjacent forks. But the 5 philosophers cannot eat at the same time because they can have only 1 fork on one hand and empty on the other and not able to eat. After that, each of them waits for the adjacent philosopher to finish which leads to a deadlock situation and each of the philosophers starve.

    The problem is to create a behaviour (algorithm) for the philosophers such that each philosopher would not starve and able to alternate between eating and thinking.

    Program for Dining Philosophers Problem in C

    #include <stdio.h>
    #define n 5	//Number of philosophers around the table
    
    int completedPhilosophers = 0, i;
    
    struct fork
    {
      int taken;
    }
    
    ForkAvail[n];
    
    struct philosp
    {
      int left;
      int right;
    }
    
    Philostatus[n];
    
    void goForDinner(int philID)
    {
     	//same like threads concept here cases implemented
      if (Philostatus[philID].left == 10 && Philostatus[philID].right == 10)
        printf("Philosopher %d completed his dinner\n", philID + 1);
     	//if already completed dinner
      else if (Philostatus[philID].left == 1 && Philostatus[philID].right == 1)
      {
       	//if just taken two forks
        printf("Philosopher %d completed his dinner\n", philID + 1);
    
        Philostatus[philID].left = Philostatus[philID].right = 10;	//remembering that he completed dinner by assigning value 10
        int otherFork = philID - 1;
    
        if (otherFork == -1)
          otherFork = (n - 1);
    
        ForkAvail[philID].taken = ForkAvail[otherFork].taken = 0;	//releasing forks
        printf("Philosopher %d released fork %d and fork %d\n", philID + 1, philID + 1, otherFork + 1);
        completedPhilosophers++;
      }
      else if (Philostatus[philID].left == 1 && Philostatus[philID].right == 0)
      {
       	//left already taken, trying for right fork
        if (philID == (n - 1))
        {
          if (ForkAvail[philID].taken == 0)
          {
           	//KEY POINT OF THIS PROBLEM, THAT LAST PHILOSOPHER TRYING IN reverse DIRECTION
            ForkAvail[philID].taken = Philostatus[philID].right = 1;
            printf("Fork %d taken by philosopher %d\n", philID + 1, philID + 1);
          }
          else
          {
            printf("Philosopher %d is waiting for fork %d\n", philID + 1, philID + 1);
          }
        }
        else
        {
         	//except last philosopher case
          int dupphilID = philID;
          philID -= 1;
    
          if (philID == -1)
            philID = (n - 1);
    
          if (ForkAvail[philID].taken == 0)
          {
            ForkAvail[philID].taken = Philostatus[dupphilID].right = 1;
            printf("Fork %d taken by Philosopher %d\n", philID + 1, dupphilID + 1);
          }
          else
          {
            printf("Philosopher %d is waiting for Fork %d\n", dupphilID + 1, philID + 1);
          }
        }
      }
      else if (Philostatus[philID].left == 0)
      {
       	//nothing taken yet
        if (philID == (n - 1))
        {
          if (ForkAvail[philID - 1].taken == 0)
          {
           	//KEY POINT OF THIS PROBLEM, THAT LAST PHILOSOPHER TRYING IN reverse DIRECTION
            ForkAvail[philID - 1].taken = Philostatus[philID].left = 1;
            printf("Fork %d taken by philosopher %d\n", philID, philID + 1);
          }
          else
          {
            printf("Philosopher %d is waiting for fork %d\n", philID + 1, philID);
          }
        }
        else
        {
         	//except last philosopher case
          if (ForkAvail[philID].taken == 0)
          {
            ForkAvail[philID].taken = Philostatus[philID].left = 1;
            printf("Fork %d taken by Philosopher %d\n", philID + 1, philID + 1);
          }
          else
          {
            printf("Philosopher %d is waiting for Fork %d\n", philID + 1, philID + 1);
          }
        }
      }
      else {}
    }
    
    int main()
    {
      for (i = 0; i < n; i++)
        ForkAvail[i].taken = Philostatus[i].left = Philostatus[i].right = 0;
    
      while (completedPhilosophers < n)
      {
        /*
        Actually problem of deadlock occur only they try to take at same time
        This for loop will say that they are trying at same time. 
        And remaining status will print by go for dinner function
        */
        for (i = 0; i < n; i++)
          goForDinner(i);
        printf("\nTill now number of philosophers who completed dinner are: %d", completedPhilosophers);
      }
    
      return 0;
    }

    The output of the Dining philosopher problem in c programming:

  • Round Robin Scheduling in C

    This article contains the implementation of the Round Robin Scheduling in C Programming with the explanation, an example, it’s advantages and disadvantages.

    If we consider large management or organization with multi-users and with a time-sharing system, in such cases response time plays a vital role in the achievements of various objectives. So, Process Scheduling is a key component for such management.

    Let us understand the Round Robin Scheduling program in C

    What is Round Robin Scheduling?

    The Round robin algorithm is a pre-emptive process scheduling algorithm used by the machine for scheduling the CPU utilization. Here, each process is allotted to a fixed time called time slice or time quantum in a cyclic way. A process enables the job scheduler that saves the current progress of the job moves to the next job present in the queue. Each process must complete the job within the given time-quantum else an interrupt may occur. The context-switching saves the current state of the process.


    What is Round Robin Scheduling Algorithm?

    • Here, every job is arranged in a FIFO(First Come First Server) order.
    • When the first process arrives, it is sent for execution. But if it couldn’t complete the execution in a given amount of time quantum that is allotted to it, then an automated timer generates an interrupt.
    • After that, the process is stopped and then send back to the end of the queue. Although the state is saved and stored so that it can be resumed where it was interrupted.
    • The process is resumed and the schedulers select the next process from the queue sent it to the processor for execution.
    • Each process is executed in a similar way and checked for the time quantum.
    • The steps are repeated for every process until the processes are over.

    Compute Times involved in Round Robin Scheduling:

    • Completion Time: Time at which process completes its execution.
    • Turn Around Time: Time Difference between completion time and arrival time.
      Turn Around Time = Completion Time – Arrival Time
    • Waiting Time(W.T): Time Difference between turn around time and burst time.
      Waiting Time = Turn Around Time – Burst Time

    Advantages:

    • It is simple, easy to use and the overhead in decision-making is low.
    • Due to the fair share of CPU, Starvation issues or convoy effect do not occur.
    • Due to the queue system, equal priority is given to all the jobs which cannot be seen in other algorithms.
    • Each process can be rescheduled after a given fixed time slot or quantum period.

    Disadvantages:

    • Due to its dependency on quantum value, the efficiency of the system is decreased.
    • An increase in the quantum value might make the system unresponsive.
    • There is no special priority for the most important process, every process is scheduled.

    Example: Round Robin Scheduling in C Programming

    #include <stdio.h>
    
    int main()
    {
       int i, total = 0, x, limit, counter = 0, t_quantum;
       int wait_time = 0, turnaround_time = 0, arrival_time[10], burst_time[10], temp[10];
    
       float average_wait_time, average_turnaround_time;
    
       printf("\nEnter Total Number of Processes: ");
       scanf("%d", &limit);
       x = limit;
    
       for (i = 0; i < limit; i++)
       {
          printf("\nProvide the details for Process[%d]\n", i + 1);
          printf("Arrival Time:\t");
          scanf("%d", &arrival_time[i]);
          printf("Burst Time:\t");
          scanf("%d", &burst_time[i]);
          temp[i] = burst_time[i];
       }
    
       printf("\nEnter Time Quantum:\t");
       scanf("%d", &t_quantum);
    
       printf("\nProcess ID\t\tBurst Time\t Turnaround Time\t Waiting Time\n");
       for (total = 0, i = 0; x != 0;)
       {
          if (temp[i] <= t_quantum && temp[i] > 0)
          {
             total = total + temp[i];
             temp[i] = 0;
             counter = 1;
          }
          else if (temp[i] > 0)
          {
             temp[i] = temp[i] - t_quantum;
             total = total + t_quantum;
          }
    
          if (temp[i] == 0 && counter == 1)
          {
             x--;
             printf("\nProcess[%d]\t\t%d\t\t %d\t\t\t %d", i + 1, burst_time[i], total - arrival_time[i], total - arrival_time[i] - burst_time[i]);
    
             wait_time = wait_time + total - arrival_time[i] - burst_time[i];
    
             turnaround_time = turnaround_time + total - arrival_time[i];
             counter = 0;
          }
    
          if (i == limit - 1)
          {
             i = 0;
          }
          else if (arrival_time[i + 1] <= total)
          {
             i++;
          }
          else
          {
             i = 0;
          }
       }
    
       average_wait_time = wait_time *1.0 / limit;
       average_turnaround_time = turnaround_time *1.0 / limit;
    
       printf("\n\nAverage Waiting Time:\t%f", average_wait_time);
       printf("\nAvg Turnaround Time:\t%f\n", average_turnaround_time);
    
       return 0;
    }

    Output of above Round Robin Algorithm in C:


  • Bit Stuffing Program in C

    This post contains the implementation of Bit Stuffing in C programming. Learn about bit-stuffing and with source code for Bit Stuffing in c.

    What is Bit Stuffing?

    Bit Stuffing is the technique of insertion of one or more extra bits (0) into data. These are the noninformation bits as a way to provide signaling information to a receiver.

    On the receiver end, the stuffed 0 bit is removed and the original value is retrieved.

    This bit (0) is added after every 5 consecutive 1’s bit frame sequence as shown in a program below.


    C Program for Bit Stuffing

    In the following source code of C programming in bit stuffing, while loop is used.

    Firstly, the user needs to input the number of frame sizes than the bit string and the 0 is stuffed after every 5 consecutive 1’s execution.

    Implementation of Bit stuffing Using C.

    #include <stdio.h>
    #include <conio.h>
    #include <string.h>
    
    void main()
    {
      int x[50], y[50], n;
      int i, j, k, count = 1;
    
      printf("Enter size of a bit string:");
      scanf("%d", &n);
    
      printf("Enter the bit string(0's &1's):");
      for (i = 0; i < n; i++)
      {
        scanf("%d", &x[i]);
      }
    
      i = 0;
      j = 0;
    
      while (i < n)
      {
        if (x[i] == 1)
        {
          y[j] = x[i];
    
         	//count is less than 5 as 0 is inserted after every 
         	//5 consecutive 1's
          for (k = i + 1; x[k] == 1 && k < n && count < 5; k++)
          {
            j++;
            y[j] = x[k];
            count++;
    
            if (count == 5)
            {
              j++;
              y[j] = 0;
            }
    
            i = k;
          }
        }
        else
        {
          y[j] = x[i];
        }
    
        i++;
        j++;
      }
    
     	//Displaying final result
      printf("Result of Bit Stuffing:");
      for (i = 0; i < j; i++)
      {
        printf("%d", y[i]);
      }
    
      getch();
    }

    The output of Bit Stuffing Program in C:

    bit stuffing in c program

  • C – Frequently Asked Question/Interview Questions

    This is an article prepared for you to answer all the frequently asked questions (short or long) in C and more. This listed FAQ is also prepared for interview questions that you may prepare through it. Not only about C but also about the compilers and headers used, etc.

    Although right now only a few questions with solutions are presented but will be extended or more questions will be added in upcoming months. So stay connected to simple2code.com.
    Let us begin.

    1. What is Acronym for ANSI and ASCII?

    ANSI:-American National Standards Institute
    ASCII:-American Standard Code for Information Interchange

    2. What is an Automatic storage Class?

    A variable defined within a function or block with an auto specifier belongs to the automatic storage class. Auto variables can only be accessed within the block/function they have been declared and not outside them (which defines their scope).

    3. C is derived from which language?

    Language B.

    4. Who invented C ?

    Developed at AT&T’s Bell Laboratories(USA,1972) Designed by Dennis Ritchie. Its features were derived from an earlier language class “B“, which according to Ken Thompson was a stripped-down version of the BCPL programming language.

    5. What is low, middle and High level language? Which one is C?

    There are three types of language: High Level, Middle Level & Low Level.

    • High-level languages are user-oriented, giving faster development of programs, an example is BASIC.
    • Low-level languages are machine-oriented; they provide faster execution of programs.

    C is a middle-level language because it combines the best part of high-level language with low-level language. It is both user and machine-oriented and provides infinite possibilities.

    6. State the Difference between Compiler and Interpreter?

    CompilerInterpreter
    The compiler translates the entire program to machine code at once.The interpreter translates line by line process.
    It generates intermediate code, called the object code or machine code.It does not generate object code or machine code.
    More difficult to debug compared to Interpreter as all errors are shown at a time.Easier to debug since execution will stop if the error is found in a particular line.
    It takes a large amount of time to analyze the source code but the overall execution time is comparatively faster.It takes less amount of time to analyze the source code but the overall execution time is slower.
    Takes more memory compared to Interpreter as Intermediate code is generatedTakes Less Memory(Memory Efficient) as Intermediate code is not generated
    Example: C, C++, COBOL, etc.Example: BASIC, Ruby, Python, etc.

    7. What character is the end of a string?

    The character used for ending a string is “\0”.

    Example:
    char str[10]="Simple2Code"

    Then Even though the string length is 11 it is ended with ‘\0’ i.e Hello\0. It indicates the end of a string.

    8. What is conio.h and getch() and clrscr()?

    • conio” means console input and output.
    • getch() is defined in “conio.h”. getch() is used to freeze the console screen for user input. It will read a character as input.
    • Clrscr() is used to clear the screen while displaying the output.

    At present we are using compilers that will show output after running a program without closing the console so no need to use getch(). Even though, the clrscr() is not present at beginning of the program and getch() at the end of the program, the program automatically clears the previous output so there is no need for clrscr().

    9. What is Dangling Pointer?

    A dangling pointer is a pointer that has an invalid memory location. Usually, this happens in such situations where we free memory allocated to pointer from memory location then it is pointing to an invalid memory location.
    Example:

    int *i=NULL;
     {
      int j=2;
      i=&j;
     }

    10. What are the modes in files?

    ModeDescription
    “r”Opens the file in reading mode. If the file is found then the file is loaded into memory and the pointer is set to the first character of the file. If the file doesn’t exist or cannot be opened it returns NULL.
    “w”If the file exists then its content is overwritten. If the file doesn’t exist then it will create a new file and write the data into it. If the file can’t be opened in any case it will return NULL.
    “a”Used to add new content at the end of the file. If the file exists then the new data/content is appended at the end of the file. In this case, the file is loaded into memory, and the pointer is set to the last character of the file.
    If the file does not exist then a new file is created.
    If in case of file can’t be opened then it returns NULL.
    “r+”Opens the existing files in reading and writing mode. If the file can’t be opened then it returns NULL.
    “w+”Opens a new file in reading and writing mode if the file does not exist.
    If the file exists the content is overwritten.
    If the file can’t be opened then it returns NULL.
    “a+”Opens file in reading and appending mode if the file exists.
    If the file can’t be opened returns NULL.Cannot modify existing data, but can append the data at the end of the file.

    11. List the files that are generated after running C program?

    • When you save source code “.c” file is generated.
    • When you compile the C program then the “.o” file is generated which means object file.
    • On running the program “.exe” file is generated which means an executable file.

    12. When to use for loop, while loop, and do-while loop?

    • for loop: is a preferred statement that is to be executed for a fixed or known number of times.
    • while loop: While loop is used to repeat a section of code an unknown number of times until a specific condition is met
    • do-while loop: When the loop has to be executed at least one time.

    13. What are header files?

    Header files contains predefined keywords like printf, scanf, main() etc in stdio.h. So including them with #include <stdio.h> makes us to use them in our program. Their functionality(i.e printf, scanf, main()) is defined in stdio.h header file. Similarly math.h, conio.h etc.

    14. What are actual parameters(arguments) and formal parameters?

    Parameters in calling function are called actual parameters or Arguments Parameters in Called functions are called formal parameters.

    15. What are comments and why we use them and In what way they will affect the program

    The comment starts with’ /*’ and ends with ‘*/’. Comments are not mandatory but still, it’s a good practice if you use them, it improves the readability of the code. A program can have any number of comments.

    16. what is d in %d and i in %i, x in %x, o in %obtain

    • %d represents decimal(base 10)
    • i represents integer
    • x represents hexadecimal(base 16)
    • o represents Octal(base 8)

    17. What is External Storage Class?

    Extern stands for external storage class. The principal use of extern is to specify that a variable is declared with external linkage elsewhere in the program. In general, it is used to declare a variable to be used in a module that is not the one in which the corresponding variable is defined

    18. What is ‘f’ in printf or scanf?

    ‘f’ in printf or scanf indicates a Formatted Specifier.

    19. What is Far Pointer?

    A pointer that can access all 16 segments of RAM

    20. Why i++ execution is faster than i+1?

    Since i++ requires only one instruction in assembly language while compiling but i+1 requires more than one instruction

    21. Is FILE s built-in datatype?

    No File is not a built-in datatype but it is a structure defined in stdio.h

    More will be added soon.


  • C – Storage Class

    Every variable has a storage class that defines the characteristics of the variable. It tells the compiler where to allocate memory for a variable, it also determines the scope of the variable, visibility, and lifetime of a variable.

    There are four types of storage classes:

    • Automatic
    • External
    • Static
    • Register

    Automatic(auto) Storage class:

    A variable defined within a function or block with an auto specifier belongs to the automatic storage class. Auto variables can only be accessed within the block/function they have been declared and not outside them (which defines their scope).

    We can also say that these are the local variables. By default, the variable declared in a program is auto storage variables. By default, they are assigned the garbage value whenever they are declared.

    auto keyword is used to define an auto storage class in a program.
    Example:

    auto int number;

    Program for auto storage class in C

    Example: The following program demonstrates the use of the auto storage class. The program shows how the same variable name can be used at variable blocks in a program with different values.

    #include <stdio.h>
    
    void autoStorageClass()
    {
      // declaring an auto variable
      auto int x = 6;
    
      // printing the auto variable
      printf("Variable x 1st: %d\n", x);
    
      {
        auto int x = 12;
        //Displaying the variable
        printf("Variable x 2nd: %d\n", x);
      }
    }
    
    int main()
    {
    
      // calling auto storage class
      autoStorageClass();
    
      return 0;
    }

    Output:

    Variable x 1st: 6
    Variable x 2nd: 12


    External(extern) Storage Class:

    Extern stands for external storage class. The principal use of extern is to specify that a variable is declared with external linkage elsewhere in the program. In general, it is used to declare a variable to be used in a module that is not the one in which the corresponding variable is defined.

    extern keyword is used to define the global variable whose scope is within the whole program, which means these variables are accessible throughout the program. That means this variable can be used anywhere in the program and its value can be manipulated from anywhere necessary.

    The main purpose of using extern variables is that they can be accessed between two different files which are located apart in a large program providing the reference of the variable.

    extern int variable_name;

    Program for extern storage class in C

    Example: Consider this main.c where a variable with extern is declared.

    #include <stdio.h>
    extern i;
    
    main() 
    {
      printf("The value of the external storage: %d\n", i);
      
      return 0;
    }
    

    Second File: Second.c is saved where the the value of the variable above is declared.

    #include <stdio.h>
    i=48;

    Output:

    The value of the external storage: 48

    Static Storage Class:

    This is another storage class that is declared as static in a program. The name static is given to variables that can hold their values between calls of a function. They are allocated only once and their values are preserved between any number of function calls.

    Space is allocated for static variables in the program code itself and hence no new memory is allocated to it as they are not re-declared in the program.

    Their scope is local to the function where they are defined. Also, global static variables can be accessed anywhere throughout the program

    NOTE: Every global variable, defined outside functions has the type static automatically. The opposite of static is auto.

    Program for static storage class in C

    You can see in the program that the two variables are declared, one is global(count) and another is local(temp). And both of these value does not reset no matter how many times you call the function to start from the beginning.

    #include <stdio.h>
    
    //global static variable
    static int count = 2;
    
    //function
    void iteration(void)
    {
      //local static variable
      static int temp = 10;
      temp++;
    
      printf("temp: %d\tcount: %d\n", temp, count);
    
    }
    
    main()
    {
      while (count < 5)
      {
    
        //calling function
        iteration();
        count++;
      }
    
      return 0;
    
    }

    Output:

    temp: 11	count: 2
    temp: 12	count: 3
    temp: 13	count: 4

    Register Storage class:

    Register storage class is only for those variables that are being used very often in a program. The reason is, there are very few CPU registers at our disposal and many of them might be busy processing something else. A typical application of the register storage class is loop counters, which get used a number of times in a program.

    Registers are mostly used for the quick access of variables in a program. The keyword register is used to declare a register storage class. The variables declared using the register storage class have lifespan throughout the program.

    Just like auto storage, it has the scope to a limited block where it is used. The difference is that the variables declared with a register keyword are stored in the register instead of RAM memory.

    Note: We cannot get the memory location when dealing with the CPU register. If you use pointers to access the memory location, the program will through an error.
    It does not have any default value.

    Registers are declared as:

    register int variable_name;


  • C – Dynamic Memory Allocation

    In this tutorial, you will learn how to dynamically allocate memory in C program using 4 standard library functions: malloc(), calloc(), free() and realloc() with examples. You will also learn the difference between malloc and calloc at the end.

    Dynamic Memory Allocation

    The main concept of dynamic memory allocation in c programming enables the programmer to allocate memory to the variable at runtime. In C, dynamic memory is allocated from the heap using some standard library functions.

    There may be times in a program where you may need to increase the size of an array. So to increase the array size, we can manually allocate the memory during run-time and this allocating and freeing of memory refers to dynamic memory allocation in C programming.

    These are mainly four library functions in the stdlib.h header file through which memory allocation is possible in C:

    1. malloc()
    2. calloc()
    3. realloc()
    4. free()
    Functionsyntax
    malloc()malloc (number *sizeof(int));
    calloc()calloc (number, sizeof(int));
    realloc()realloc (pointer_name, number * sizeof(int));
    free()free (pointer_name);

    1. malloc():

    This function stands for memory allocation. It is a function that is used to allocate a block of memory dynamically. It takes a single argument that is the amount of memory to allocate in bytes but does not initialize the memory allocated at execution time. So it has a garbage value initially.

    Syntax for malloc function:

    ptr=(cast-type*)malloc(byte-size);

    It is used in the program in the following way:
    In the block of code shown below, memory is allocated for space of size 8 bytes to store 8 characters.
    Applying it in programming:

    //use
    // char pointer
       char *p;
    
    // allocate memory
       p = (char *) malloc (8 * sizeof(char));

    Example: C Program for malloc()

    #include <stdio.h>
    #include <stdlib.h>
    
    int main()
    {
      int n, i, *ptr, sum = 0;
    
      printf("Enter number of elements: ");
      scanf("%d", &n);
    
      ptr = (int*) malloc(n* sizeof(int));
    
      //Checking for memory element to be null
      if (ptr == NULL)
      {
        printf("Sorry! Not able to allocate Memory.\n");
        exit(0);
      }
    
      printf("Enter %d Numbers that you want to sum of: ", n);
      for (i = 0; i < n; ++i)
      {
        scanf("%d", ptr + i);
        sum += *(ptr + i);
      }
    
      printf("Sum of the Numbers: %d", sum);
    
      //free memory location
      free(ptr);
    
      return 0;
    }

    Output:

    Enter number of elements: 2
    Enter 2 Numbers that you want to sum of: 5 4
    Sum of the Numbers: 9

    When the program no longer needs the dynamic array, it eventually calls free to return the memory it occupies. The malloc function returns a NULL value if it fails to allocate the specified memory space


    2. calloc():

    The calloc function stands for contiguous allocation. calloc() function is also like malloc () function. But calloc() initializes the specified bytes to zero. It is mainly used in complex data structures such as arrays and structures.

    Calloc() function is used to allocate multiple blocks of memory while malloc() is used for a single block of memory.

    Syntax for calloc function:

    ptr=(cast_type*)calloc(n,size);
    
    //n is the number of memory block of same size

    Example: C Program for calloc():

    calloc() needs two arguments that are the number of variables to allocate in memory, and the size is in bytes of a single variable.

    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    
    int main()
    {
      char *calloc_allocation;
      
      //memory allocated dynamically
      calloc_allocation = calloc(10, sizeof(char));
    
      if (calloc_allocation == NULL)
      {
        printf("Couldn't able to allocate requested memory\n");
      }
      else
      {
        strcpy(calloc_allocation, "Calloc working");
      }
    
      // display result
      printf("Dynamically allocated content: %s\n", call_allocation);
    
      // free memory location
      free(calloc_allocation);
    }

    Output:

    Dynamically allocated  content: Calloc working

    3. realloc():

    realloc stands for reallocation of memory. realloc() function is used to change the memory size of the previously allocated memory space or we can say that it increases or decreases the size of the block of memory that is specified to use and also realloc() moves it if necessary.

    Syntax for realloc function:

    realloc (pointer_name, number * sizeof(int));

    Example: C Program for relloc():

    #include <stdio.h>
    
    int main()
    {
      char *pt;
      pt = (char*) malloc(15);
      strcpy(pt, "realloc");
      printf(" %s,  located = %u\n", pt, pt);
    
      pt = (char*) realloc(pt, 15);	//pt is reallocated with new size
      strcat(pt, " in C");
    
      printf(" %s,  located = %u\n", pt, pt);
      free(pt);
    
      return 0;
    }

    Output:

    realloc, located = 38420496
    realloc in C, located = 38420496

    4. free()

    The free() function is called to release/deallocate memory. it releases the specified block of memory and returns it back to the system. It frees the allocated memory of malloc (), calloc (), realloc () function because these functions does not get freed on their own.

    Syntax:

    free (pointer_name); //it does not have return type

    C Program for free() with malloc():

    #include <stdio.h>
    #include <stdlib.h>
    
    int main()
    {
      int n, i, *ptr, sum = 0;
    
      printf("Enter number of elements: ");
      scanf("%d", &n);
    
      ptr = (int*) malloc(n* sizeof(int));
    
      //Checking for memory element to be null
      if (ptr == NULL)
      {
        printf("Sorry! Not able to allocate Memory.\n");
        exit(0);
      }
    
      printf("Enter %d Numbers that you want to sum of: ", n);
      for (i = 0; i < n; ++i)
      {
        scanf("%d", ptr + i);
        sum += *(ptr + i);
      }
    
      printf("Sum of the Numbers: %d", sum);
    
      //free memory location
      free(ptr);
    
      return 0;
    }

    Output:

    Enter number of elements: 2
    Enter 2 Numbers that you want to sum of: 5 4
    Sum of the Numbers: 9

    Difference between malloc() and calloc():

    malloc()calloc()
    Malloc() function will create a single block of memory of size specified by the user.Calloc() function can assign multiple blocks of memory for a variable.
    The number of arguments is 2.The number of arguments is 1.
    It is not initialized, so contains garbage values.It always initialized to zero
    Malloc is faster as compared to calloc.Calloc is slower as compared to malloc.
    This function returns only starting address and does not make it zero.This function returns the starting address and makes it zero.
     Time efficiency is higher. Time efficiency is lower.