Author: admin

  • 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.

  • C – Preprocessors

    As the “pre” means beforehand, similarly it means processing something before passing it on further. The preprocessor is a program that processes the source program before it is passed to the compiler. So we can say that it is a separate process in the compilation.

    Preprocessor commands (often known as directives) form what can almost be considered a language within the C language. We can certainly write C programs without knowing anything about the preprocessor or its facilities.

    It gives specific features called directives. A preprocessor directive begins with “#” symbol at the starting of the program. These directives are processed before the compilation of the program.

    The following are preprocessor directives:

    • Macro expansion
    • File inclusion
    • Conditional Compilation
    • Miscellaneous directives

    Macro Definition

    macro is defined by #define in a program. It is used to define some constant in a program that can be used anywhere during the entire program. This constant becomes global value.

    #define PI 3.1415

    This statement is called ‘macro definition’ or more commonly, just a ‘macro’.
    Its purpose: during preprocessing, the preprocessor replaces every occurrence of PI in the program with a 3.1415 value.

    You may try this program:

    #include <stdio.h>
    
    #define PI 3.1415 //macro
    
    int main()
    {
        float rad, area;
        printf("Enter the radius of a circle: ");
        scanf("%f", &rad);
    
        //PI is used here
        area = PI * rad * rad;
    
        printf("Area of a circle: %.2f", area);
        return 0;
    }

    File inclusion

    #include is used to include some files into the program. These are usually header files, but sometimes maybe any text file. The command looks something like this:

    #include <stdio.h>

    stdio.h is the header file that contains the library function that is used in a program such as printf, scanf, etc. #include is a preprocessor directive.

    Check the example of macro mentioned above where stdio.h file is defined by #include. If we do not include this header file then we will not be able to use the in-built function.


    Conditional Compilation

    The C preprocessor provides a series of directives for conditional compilation: #if, #elif, #else, #ifdef, #ifndef, and #endif. These commands cause the preprocessor to include or exclude sections of the source code from compilation depending on certain conditions.

    Conditional compilation is used for three main purposes:

    • Optionally include debugging code
    • Enclose non-portable code
    • Guard against multiple inclusion of header files.

    Syntax:

    #ifdef, #endif, #if, #else, #ifndef

    #ifndef

    #ifndef TEXT
       #define TEXT "Hello World"
    #endif

    It tells the C Preprocessor to define TEXT only if TEXT isn’t already defined.

    #ifdef Directive

    #ifdef MACRO     
       // conditional codes
    #endif
    #if expression
       conditional codes if expression is non-zero
    #else
       conditional if expression is 0
    #endif

    You can also add nested conditional to your #if...#else using #elif

    #if expression
        // conditional codes if expression is non-zero
    #elif expression1
        // conditional codes if expression is non-zero
    #elif expression2
        // conditional codes if expression is non-zero
    #else
        // conditional if all expressions are 0
    #endif

    Miscellaneous directives

    #undef is used to undefine a defined macro variable.

    #undef  FILE_SIZE
    #define FILE_SIZE 38

    It tells the C Preprocessor to undefine existing FILE_SIZE and define it as 38.

    #pragma is used to call a function before and after the main function in a C program.

    #undef, #pragma


    Predefined Macros

    MacroValue
    __DATE__A string containing the current date
    __FILE__A string containing the file name
    __LINE__An integer representing the current line number
    __STDC__If follows ANSI standard C, then the value is a nonzero integer
    __TIME__A string containing the current date.

    Example: print current time and date using predefined function.

    #include <stdio.h>
    int main()
    {
       printf("Current time: %s",__TIME__);
       printf("Current date: %s",__DATE__);   
    }

    You can run the above program in the compiler and the Current time and date will be displayed on the screen.


  • C – File System (I/O)

    In this tutorial, you will learn about file handling in C. You will learn how to read from a file, write to a file. close a file and more.

    File pointers: It is not enough to just display the data on the screen. We need to save it because memory is volatile and its contents would be lost once the program terminated, so if we need some data again there are two ways, one is retyped via keyboard to assign it to a particular variable, and the other is regenerate it via programmatically both options are tedious.

    At such times it becomes necessary to store the data in a manner that can be later retrieved and displayed either in part or in whole. This medium is usually a “file” on the disk.

    Introduction to file

    Until now we have been using the functions such as scanf, printf, getch, putch, etc to read and write data on the variables and arrays for storing data inside the programs But this approach poses the following problems.

    • The data is lost when program terminated or variable goes out of scope.
    • Difficulty to use large volume of data.

    We can overcome these problems by storing data on secondary devices such as Hard Disk. The data is stored on the devices using the concept of “file”. A file is a collection of related records, a record is composed of several fields and a field is a group of characters. The most straightforward use of files is via a file pointer.

    We need to declare the pointer first in a program and is done in the following ways:

    FILE *fp;
    //fp is a pointer to a file.

    The type FILE is not a basic type, instead, it is defined in the header file stdio.h, this file must be included in your program


    Types of Files

    Basically there are two types of file:

    1. Text files: These files are .txt files that contain the plain text when you open it and easy to edit and delete. You can create such files with text editors such as Notepad.
    2. Binary file: These are the .bin files present in the computer. They store the data in a binary form such as in 0’s and 1s instead of plain text. Although it is harder to understand, it gives better security than plain text files.

    File Operation

    • Create a new file (fopen with attributes as “a” or “a+” or “w” or “w++”).
    • Open an existing file (fopen).
    • Read from file (fscanf or fgets).
    • Write to a file (fprintf or fputs).
    • Moving a specific location in a file(Seeking) (fseek, rewind).
    • Closing File (fclose).

    Opening a file:

    fopen() is used to open a file by giving two values such as file_name and mode to which you want to open the file. The various modes are stated below.

    FILE *fp;
    fp = fopen ("file_name", "mode");

    There are various modes to open a file. Check the table given below.

    File ModesDescription
    rread
    wwrite, overwrite file if it exists
    awrite, but append instead of overwrite
    w+read & write, do not destroy file if it exists
    a+read & write, but append instead of overwrite
    b+may be appended to any of the above to force the file to be opened in binary mode rather than text mode.

    Sequential file access is performed with the following library functions: 

    • fopen()  – Create a new file
    • fclose()  – Close file
    • getc()    – Read character from file
    • putc()    – Write a character to a file
    • getw()   – Read Integer from file
    • putw()   – Write Integer to a file
    • fprintf()  – Write set of data values
    • fscanf()  – read set of data values

    Closing a file:

    fclose() function is used to close the file once the operation on file is done. And it is done in a flowing way:

    int fclose( FILE *fp );

    Example on how to use open and close mode.

    //Opens inputs.txt file in read mode
    FILE  *fp;
    fp=fopen("input.txt","r");
    
    //closing inputs.txt file
    fclose(fp); //close file

    Reading from a file:

    Reading operation are performed fgetc(), fgets() and fscanf(). You can use them according to your choice. If you want to read character by character then you may use fgetc() or for line by line, you can use fgets().

    The end of the file is denoted by EOF(end of file) ot NULL character (\0) value at the end. It tells the function that it has reached the end of the file.

    FILE * fp; 
    fp = fopen(“fileName.txt”, “r”);
    fscanf(fp, "%s %s %s %d", str1, str2, str3, &year);

    Writing to a file:

    Writing operation in a file can be performed with the use of fprintf, fputc and fputs.

    • fputc(char, file_pointer): It writes a character to the file.
    • fputs(str, file_pointer): It writes a string to the file..
    • fprintf(file_pointer, str, variable_lists): The first value is the file_pointer that points to the String that needs to be printed.
    FILE *fp; 
    fp= fopen(“file_Name.txt”, “w”);
    fprintf(fp, "%s %s %s %d", "This", "is", "new", 2021);

    Example of Writing and closing a file in C programming.

    #include < stdio.h > 
    #include <string.h >
    
      int main()
      {
        //file pointer
        FILE * fp;
    
        // Get the data to be written in file
        char writeData[50] = "Simple2Code: Learn Coding";
    
       //opening file in a write mode
        fp = fopen("TestFile.txt", "w");
    
       //Check for the null
        if (fp == NULL)
        {
          printf("TestFile.txt failed to open.");
        }
        else
        {
          printf("Successfully Opened.\n");
    
          if (strlen(writeData) > 0)
          {
           	//writing in the file using fputs()
            fputs(writeData, fp);
            fputs("\n", fp);
          }
    
         	//Closing the file
          fclose(fp);
    
          printf("The file is now closed.");
        }
    
        return 0;

  • Array in C

    An array is a group or the collection of data having the same data-type stored in a contiguous memory location. It is a simple data structure format where the primitive type of data such as int, char, double, float, etc are stored and accessed randomly through their index number.

    It can also store the collection of derived data types, such as pointers, structure, etc. Elements are arranged inside the array with index numbers starting from zero as the first elements.

    Types of Array in C:

    • One Dimensional Array
    • Two Dimensional Array
    • Multi-Dimensional Array

    One Dimensional Array

    An array with only one subscript is known as a one-dimensional array.
    Example: int arr[10].

    Syntax:

    data-type arrayName [ arraySize ];

    Declaration of on Array:

    For declaration of an array in C, the user needs to specify the type of element and number of elements in an array. Below is the declaration of single-dimensional Array.

    type arrayName [ arraySize ];

    The data-type must be a valid C data type, a unique name must be specified to each array and the arraySize must be of an integer constant. Let see an example for integer array with 10 elements:

    int arr[10];

    Initialization of an array:

    Array can be initialize by using a single statement or one by one. The Initialization is done within the curly braces {}.

    int arr[5] = {45, 23, 99, 23, 90};
    OR
    int arr[] = {45, 23, 99, 23, 90};

    In the second one of the above example, the array size is not declared so that you can initialize as much value as you want.

    Users can also directly assign the value to the particular element in an array by specifying the index number such as: below shows how to assign the value 23 to the 5th element of an array.

    arr[4] = 23;

    NOTE:
    In the above example, number 4 means the 5th element as the array index starts from 0.

    Accessing an Array:

    As told above, that each array elements are associated with specific number that is the index numbers.

    An array element can be accessed by using the specific index number. It can be achieved by placing the particular index number within the bracket []. Such as:

    arr[4]; //the 5th element is accessed
    arr[7]; //the 8th element is accessed

    We can also assign the value particular index number to other variable but their data type must be the same such as:

    int numb = arr[4];

    In the above, the value of 5th element from an array arr[] is assigned to the numb variable.


    Example: Demonstration for declaring, initializing, and accessing an array in C

    #include <stdio.h>
    
    int main()
    {
      /*declaration of an array 
      with 10 elements*/
      int arr[10];
      int i, j;
    
      /*Array intitalization */
      for (i = 0; i < 10; i++)
      {
        arr[i] = i + 1;
      }
    
      //accesing the array element and changing its value to 50
      arr[5] = 50;
    
      //Displaying
      for (j = 0; j < 10; j++)
      {
        printf("Element[%d] = %d\n", j, arr[j]);
      }
    
      return 0;
    }

    Output:

    Element[0] = 1
    Element[1] = 2
    Element[2] = 3
    Element[3] = 4
    Element[4] = 5
    Element[5] = 50
    Element[6] = 7
    Element[7] = 8
    Element[8] = 9
    Element[9] = 10

    Index Out of bound Checking: Accessing elements out of its bound.

    Out of bound means, suppose you declare an array with 10 number of elements (index between 0 to 9) and you try to access the 11th element, which is not present in that array such as:

    .........
    ........
    {
    int arr[10];
    
    printf("%d", arr[11]); //11th element not present
    .......
    }

    In the above program, the 11th element is not present but we are trying to print that element. In such cases, the program may run fine but you may get an unexpected output (undefined behavior) from a program.

    There is no index out of bounds checking in C.


    Empty Members in an array

    When we declare an array of size n, that means we can store the n number of elements of in that array. But what happens if we were to store less than n number of elements.

    Consider an example below:

    //size=10
    //stored = 6 elements
    int arr[10] = {19, 10, 8, 45, 2, 87};

    As you can see, the size of an array is 10 but we initialized it with only 6 elements. However, a 10 contiguous memory location is already allocated to this array. What will happen to the remaining un-initialized arrays?

    Now in such cases, random values are assigned by the compiler to the remaining places. And often these random values are 0.


    Advantages of Array in C

    • Less line of codes that is a single array with multiple elements, specifying code optimization.
    • Elements of an array can be accessed randomly with the index number.
    • The elements in an array can be easily traversed.
    • Array’s data are easy to manipulate.
    • Sorting becomes easy in an array with fewer lines of codes.

    Disadvantages of Array in C

    • The array is of fixed size once initialized. We cannot add new elements after initialization.
    • The number of elements you need to store in an array must be known in advance.
    • There may be a wastage of space if more memory is allocated than the required amount.

    Learn in Detail:

    1One-Dimensional Array
    2Two-Dimensional Array
    3Multi-Dimensional Array
    4Passing Array to Function
    5Pointers to Array

  • C – Passing Array to Function

    Passing an array to function in the one-Dimensional array is done through an actual parameter and array variables with subscript are passed as formal arguments. While passing array only the name of the array is passed to the function.

    Same method is applied for the multi-dimensional array.

    There are three methods that can be used to pass an array to a function.

    First Way: As a unsized array

    return_type function(type arrayname[])
    {
      .....    
    }

    Second Way: As a sized array

    return_type function(type arrayname[SIZE])
    {
      .....    
    }

    Third Way: As a pointer

    return_type function(type *arrayname)
     {
      .....    
     }

    Example: Passing a One-Dimensional Array in Function in C

    To find the average of given number.

    #include <stdio.h>
    
    float avgresult(float age[]);
    
    int main()
    {
      float avg, score[] = { 14.4, 23, 19.6, 9, 56.9, 18 };
      avg = avgresult(score); // Only name of an array is passed as an argument
    
      printf("Average Score = %.2f", avg);
      return 0;
    }
    
    //function
    float avgresult(float score[])
    {
      int i;
      float avg, sum = 0.0;
      for (i = 0; i < 6; ++i)
      {
        sum += score[i];
      }
    
      avg = (sum / 6);
      return avg;
    }

    Output:

    Average Score = 23.48

    Example: Passing a Multi-Dimensional Array in Function in C

    Program takes an input from the user and a function is used to display the array.

    #include <stdio.h>
    
    void displayArray(int arr[3][2]);
    
    int main()
    {
      int arr[3][2];
      printf("Enter 6 numbers for an array:\n");
      for (int i = 0; i < 3; ++i)
        for (int j = 0; j < 2; ++j)
          scanf("%d", &arr[i][j]);
    
      // passing multi-dimensional array to a function
      displayArray(arr);
      return 0;
    }
    
    void displayArray(int arr[3][2])
    {
      printf("Displaying the Entered Number: \n");
    
      for (int i = 0; i < 3; ++i)
      {
        for (int j = 0; j < 2; ++j)
        {
          printf("%d\n", arr[i][j]);
        }
      }
    }

    Output:

    Enter 6 numbers for an array:
    56
    22
    67
    88
    2
    8
    Displaying the Entered Number:
    56
    22
    67
    88
    2
    8

  • Pointer to an Array in C

    The basic idea of Pointer to an Array is that a pointer is used in with array that points to the address of the first element of that array.

    Before we begin, you need to have the knowledge of following C programming:


    Consider the following:

    double *ptr;		
    double arr[10];
    
    ptr = arr;

    In the above example, the variable arr will provide the base address, which is a constant pointer pointing to the first element of the array that is to arr[0]. And hence the arr will contain the address of arr[0]. Thus, the above program fragment assigns ptr with the address of the arr.

    Once the address of the first element is stored in the pointer ‘p’, we can access other elements of array elements using *p, *(p+1), *(p+2), and so on.

    Now lets apply it in a programs.

    Example 1: Array and Pointers in C

    #include <stdio.h>
    
    int main()
    {
      int i;
      int arr[5] = { 30, 42, 35, 4, 52 };
      int *p = arr;
    
      //displaying using pointer
      for (i = 0; i < 5; i++)
      {
        printf("Element at %d = %d\n", i, *p);
        p++;
      }
    
      return 0;
    }

    Output:

    Element at 0 = 30
    Element at 1 = 42
    Element at 2 = 35
    Element at 3 = 4
    Element at 4 = 52

    Example 2: Array and Pointers in C

    #include <stdio.h>
    
    int main() 
    {
      int arr[6] = {10, 20, 30, 40, 50, 60};
      int *ptr;
    
      //4th element address is assigned
      ptr = &arr[3]; 
    
      printf("Value pointed by *ptr: %d \n", *ptr);   // 40
      printf("Value pointed by *(ptr+1): %d \n", *(ptr+1)); // 50
      printf("Value pointed by: *(ptr-1): %d", *(ptr-1));  // 30
    
      return 0;
    }

    Output:

    Value pointed by *ptr: 40 
    Value pointed by *(ptr+1): 50 
    Value pointed by: *(ptr-1): 30

    In the above example array(arr) 4th element’s address is assigned to the pointer(ptr) and through that, we can print the value that the pointer points to by simply incrementing decrementing the pointer value such as by using ptr+1 or ptr-2, etc.


  • C – Multi-Dimensional Array in C

    What is Multi-Dimensional Array in C?

    In C programming, Multi-Dimensional Arrays refer to as array of arrays. This could be of 2D or 3D (two-dimensional or three-dimensional) Array. These arrays are stored in the form of a table (with rows and columns).

    The general form of multi-dimensional array:

    data-type array_name [size1][size2]...[sizeN];

    The data type must be a valid C data type, a unique name must be specified to each array and the size must be of an integer constant.


    Declaration of 2d and 3d Array in C.

    int arr1[3][4]; //2D Array
    OR
    int arr2[3][4][3]; //3D Array

    Initialization of multidimensional array.

    We can initialize a Multi Dimensional Array (two-dimensional or three-dimensional) in the following ways in C.

    1. Initialization of 2d Array

    //Method1
    //initializing with 5 rows and 3 columns
    int arr[5][3] = {
            {1, 2, 3},
            {2, 3, 4},
            {3, 4, 5},
            {4, 5, 6}, 
            {7, 8, 9}
         };
    OR
    //Method2
    int x[3][4] = {0, 1 ,2 ,3 ,4 , 5 , 6 , 7 , 8 , 9 , 10 , 11}

    2. Initialization of 3d Array

    //Method1
    int arr[2][3][4] = {
        {{3, 4, 2, 3}, {0, -3, 9, 11}, {23, 12, 23, 2}},
        {{13, 4, 56, 3}, {5, 9, 3, 5}, {3, 1, 4, 9}}};
    OR
    //method2
    int arr[2][3][4] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 
                     11, 12, 13, 14, 15, 16, 17, 18, 19,
                     20, 21, 22, 23};

    Accessing Multi-Dimensional Array Elements in C

    Accessing 2d Array:

    An array can be accessed by using a specific index number. It can be achieved by placing the particular index number within the brackets [][]. Such as:

    arr[2][3]; //the 4th element of the third row is accessed
    arr[3][2]; //the 3rd element of the fourth row is accessed
    OR
    int val = arr[2][3]; // assigning the element to val

    Accessing 3d Array:

    Accessing 3-dimensional array is also as same as a two-dimensional array, the only difference is that in 3d array we have to specify 3 subscripts with a required index number.


    Example of two -dimensional Array in C:

    Displaying the elements with index number from 2D Arrays.

    #include <stdio.h>
    
    int main()
    {
      //Array with 4 rows and 2 columns
      int arr[4][2] = {
        { 0, 1 },
        { 2, 3 },
        { 4, 5 },
        { 6, 7 }
      };
    
      int i, j;
    
      //Displaying the elements
      printf("Elements with index numbers:\n");
      for (i = 0; i < 4; i++)
      {
        for (j = 0; j < 2; j++)
        {
          printf("a[%d][%d] = %d\n", i, j, arr[i][j]);
        }
      }
    
      return 0;
    }

    Output: After executing the above code, the following result will be displayed.

    arr[0][0]: 0
    arr[0][1]: 1
    arr[1][0]: 2
    arr[1][1]: 3
    arr[2][0]: 4
    arr[2][1]: 5
    arr[3][0]: 6
    arr[3][1]: 7

    Example of three-dimensional Array in C:

    Displaying the elements with index number from 3D Arrays.

    #include <stdio.h>
    
    int main()
    {
      int arr[2][3][2] = { 
            { {0,1}, {2,3}, {4,5} }, 
            { {6,7}, {8,9}, {10,11} } 
        };
      int i, j, k;
    
     // Display with index number
      printf("Elements with index number: \n");
      for (i = 0; i < 2; ++i)
      {
        for (j = 0; j < 3; ++j)
        {
          for (k = 0; k < 2; ++k)
          {
            printf("Element at [%d][%d][%d] = %d\n", i, j, k, arr[i][j][k]);
          }
        }
      }
    
      return 0;
    }

    Output: After executing the above code, the following result will be displayed.

    Element at arr[0][0][0] = 0
    Element at arr[0][0][1] = 1
    Element at arr[0][1][0] = 2
    Element at arr[0][1][1] = 3
    Element at arr[0][2][0] = 4
    Element at arr[0][2][1] = 5
    Element at arr[1][0][0] = 6
    Element at arr[1][0][1] = 7
    Element at arr[1][1][0] = 8
    Element at arr[1][1][1] = 9
    Element at arr[1][2][0] = 10
    Element at arr[1][2][1] = 11

    As we saw the examples of 2D and 3D arrays, in a similar we can create any number dimension as required. However, the most used multidimensional array is a two-dimensional array.


  • C – Two Dimensional Array

    What is Two Dimensional Array in C?

    Array with two subscripts is known as two dimensional Array. The 2D array is organized as the collection of rows and columns to form a matrix. 2D arrays are created to manipulate data structures.

    Example: int arr[][];

    Declaration of 2D array.

    The following shows the syntax for declaring 2D Array.

    data_type array_name[rows][columns];

    The data-type must be a valid C data type, a unique name must be specified to each array and the arraySize must be of an integer constant. The 2D array is considered as the table with a specified number of rows and columns.

    Consider the following example of 2D integer type array with 5 rows and 3 columns:

    int arr[5][3];

    Initialization of 2D array.

    2D array is initialized using the curly braces {}. Such as:

    //initializing with 5 rows and 3 columns
    int arr[5][3] = {
            {1, 2, 3},
            {2, 3, 4},
            {3, 4, 5},
            {4, 5, 6}, 
            {7, 8, 9}
         };
    OR
    int arr[3][4] = {0, 1 ,2 ,3 ,4 , 5 , 6 , 7 , 8 , 9 , 10 , 11}

    Accessing Two-Dimensional Array Elements in C

    An array can be accessed by using the specific index number. It can be achieved by placing the particular index number within the bracket [][]. Such as:

    arr[2][3]; //the 4th element of the third row is accessed
    arr[3][2]; //the 3rd element of the fourth row is accessed
    OR
    int val = arr[2][3]; // assigning the element to val

    Example of 2D Array in C.

    Displaying the elements with index number from 2D Arrays.

    #include <stdio.h>
    
    int main()
    {
      //Array with 4 rows and 2 columns
      int arr[4][2] = {
        { 0, 1 },
        { 2, 3 },
        { 4, 5 },
        { 6, 7 }
      };
    
      int i, j;
    
      //Displaying the elements
      printf("Elements with index numbers:\n");
      for (i = 0; i < 4; i++)
      {
        for (j = 0; j < 2; j++)
        {
          printf("a[%d][%d] = %d\n", i, j, arr[i][j]);
        }
      }
    
      return 0;
    }

    Output: After executing the above code, the following result will be displayed.

    arr[0][0]: 0
    arr[0][1]: 1
    arr[1][0]: 2
    arr[1][1]: 3
    arr[2][0]: 4
    arr[2][1]: 5
    arr[3][0]: 6
    arr[3][1]: 7