Wednesday, July 17, 2019

Why learning C Programming is a must?



C is a procedural programming language. It was initially developed by Dennis Ritchie between 1969 and 1973. It was mainly developed as a system programming language to write operating system. The main features of C language include low-level access to memory, simple set of keywords, and clean style, these features make C language suitable for system programming like operating system or compiler development.
Learning C programming has lot of benefits, but the foremost thing in which it helps is to understand the underlying architecture of how things works?
Learning C has a similar benefit. If the person had learned driving on a manual car, he could have easily driven the automatic car as well. Similarly, if a person learns C programming first, it will help him to learn any modern programming language as well. As learning C help to understand a lot of underlying architecture of operating system. Like, pointers, working with memory locations etc.
Consider a situation where a person learns to drive a Car. In this modern era with advancement in technology, we have many options when it comes to buying car. There are cars with auto-driving mode, auto gear change features etc which reduces the manual overheads and makes driving the car easier. Suppose the person learns driving on a auto-gear change enabled car. After learning driving, the person applied for a driving licence for which he need to pass a driving test. The driving test is now on a manual car with no auto-gear change feature. The person was even not able to answer some basic questions related to gears as he was not even aware of it and eventually ended up getting disqualified.

Let us now look at some of the important advantages of learning C programming:
  • C is a Middle-Level Language. The middle-level languages are somewhere between the Low-level machine understandable assembly languages and High-Level user friendly languages. Being a middle-level language, C reduces the gap between the low-level and high-level languages. It can be used for writing operating systems as well as doing application level programming.
  • Helps to understand the fundamentals of Computer Theories. Most of the theories related to computers like Computer NetworksCompiler DesigningComputer ArchitectureOperating Systems are based on C programming language and requires a good knowledge of C programming if you are working on them. In the modern high level languages, the machine level details are hidden from the user, so in order to work with CPU cache, memory, network adapters, learning C programming is a must.
  • Fewer Libraries. C programming language has fewer libraries in comparison with other high-level languages. So, learning C programming also clears programming concepts to a great extent as you have to write lot of things from scratch. You will not be dependent on the programming language entirely for implementing some basic operations and implementing them on your own will also help you to build your analytical skills.
  • C is very fast in terms of execution time. Programs written and compiled in C executes much faster than compared to any other programming language. C programming language is very fast in terms of execution as it does not have any additional processing overheads such as garbage collection or preventing memory leaks etc. The programmer must take care of these things on his own.
  • Embedded Programming. C is extensively used in Embedded Programming. Embedded Programming is also referred to as micro-controller programming, where C program is used to control micro-controllers. Microcontrollers and embedded programming is widely used in auto-motives, Robotics, Hardwares etc.
Keeping the above things in mind, we have prepared an introductory course on C programming language to guide you through the basics following an intuitive environment so that you can practice alongside what you have learnt. Click the below link and start learning C programming today for free!

Monday, June 3, 2019

C Interview Question for Freshers

Basic C

C is oops or structure oriented programming language ?

C is not Object oriented programming language, it is structure oriented programming language.

Why C called mother language ?

C is also called mother Language of all programming Language, because it support some features of low level programming language and basic of all high level programming language.

Why use C language ?

C language is used for develop system software and Operating System.

C is platform dependent language ?

Yes, It is platform dependent language, because it not run on other system with respect to its development.

C is case sensitive language ?

Yes, C is a case sensitive programming language. In C programming 'break and BREAK' both are different.

What is keyword ?

Keyword is a predefined or reserved word in C library with a fixed meaning and used to perform an internal operation. C Language supports 32 keywords. Keywords in C

What is Constant ?

It is an identifier whose value can not be changed at the execution time of program. In general constant can be used to represent as fixed values in a C program. Read more.....

What is Garbage value ?

Garbage value can be any value given by system and that is no way related to correct programs. It is a disadvantage and it can overcome using variable initialization.
In c programming avoid garbage collection by using variable initialization

What is data type ?

Data type is a keyword used to identify type of data. Data types are used for representing the input of the user in the main memory (RAM) of the computer. Read more......

What is difference between compiler and interpreter

What is Data Type Modifiers ?

In c language Data Type Modifiers are keywords used to change the properties of current properties of data type. Read more....

What is Storage Class in C ?

Storage class specifiers in C language tells to the compiler where to store a variable (Storage area of variable), how to store the variable, Scope of variable, Default value of a variable (if it is not initialized it), what is the initial value of the variable and life time of the variable. Read more.......
NoCompilerInterpreter
1Compiler takes Entire program as input at a time.Interpreter takes Single instruction as input at a time.
2Intermediate Object code is generatedNo Intermediate Object code is generated
3It execute conditional control statements fastly.It execute conditional control statements slower than Compiler
4More memory is required.Less memory is required.
5Program need not to be compiled every timeEvery time higher level program is converted into lower level program
6It display error after entire program is checkedIt display error after each instruction interpreted (if any)
7Example: CExample: BASIC

What is buffer in C

Temporary storage area is called buffer. Read more.....

Which data type supported by switch case ?

A switch statement work with byte, short, char and int primitive data type, it also works with enumerated types and string.

What is || operator ?

The || is also known as the OR operator in C programming. This operator is return true when at least one condition is true.

What is limitations with switch case ?

Logical operators can not be used with switch statement.

Why use getch()

It is a predefined function in "conio.h" (console input output header file) will tell to the console wait for some time until a key is hit given after running of program.
By using this function we can read a character directly from the keyboard. Generally getch() are placing at end of the program after printing the output on screen.

Difference between source code and object code.

Source codeObject code
Source code is in the form of Text form.Object Code is in the form of Binary Numbers.
Source code is Human Readable Code.Object Code is in Machine Readable formats.
Source code is Generated by Human or Programmer.Object Code is Generated by Compiler.
Source code is receive Compiler as a Input.Object Code is Generated by Compiler as a Output.

Operator in C

What is Operator in C ?

Operator is a special symbol that tells the compiler to perform specific mathematical or logical Operation. Read more......

What is the modulus operator ?

Modulus operator return remainder. The modulus operator is used for get the remainder if you divide any number by other number.

What is Ternary Operator ?

If any operator is used on three operands or variable is known as Ternary Operator. It can be represented with ? : . It is also called as conditional operatorRead more....

Main advantage of Ternary operator ?

Using Ternary Operator reduce the number of line codes and improve the performance of application.

What is binary operator ?

Binary operator are used with two operands, example +, _ *, / operators are binary operators/

What is unary operator ?

Unary operators are those which are used with only on single or one operand, example ++, -- are unary operator

Control Statements in C

What is Decision Making Statement ?

Decision making statement is depending on the condition block need to be executed or not which is decided by condition.

What is else in C ?

It is a keyword, by using this keyword we can create a alternative block for "if" part. Read more.....

Why use Loop ?

Where need repetition of same code a number of times at that place use Loop in place of writing more than one statements. The way of the repetition will be forms a circle that's why repetition statements are called loops. Read more.......

When use Do-While Loop ?

When we need to repeat the statement block at least 1 time then we use do-while loop.

What is while Loop ?

In while loop First check the condition if condition is true then control goes inside the loop body other wise goes outside the body. while loop will be repeats in clock wise direction. Read more.......

Difference between while and do..while loop ?

In while loop First check the condition if condition is true then control goes inside the loop body other wise goes outside the body. but in case of do..while loop at least one time loop will be execute then condition is checked.

Which loop have fast execution for or while ?

Execution process of while loop is slower than for loop

Error in C

What is error in C ?

Error is a abnormal condition whenever it occurs execution of the program is stopped these are mainly classified into following types.
  • Compile time error
  • Run time error

What is Compile time error in C

If any error is generated at the time of compilation is known as compile time error, in general these are raised while break down the rules and regulation of programming language.

What is Run time error in C

If any error is generated at run time is known as runtime error, in general these are raised because of writing wrong logic in the program.

What is warning in C

Warning is also an abnormal condition but whenever it occurred execution of program will never be stopped.

Difference between call by value and call by reference.

call by valuecall by reference
This method copy original value into function as a arguments.This method copy address of arguments into function as a arguments.
Changes made to the parameter inside the function have no effect on the argument.Changes made to the parameter affect the argument. Because address is used to access the actual argument.
Actual and formal arguments will be created in different memory locationActual and formal arguments will be created in same memory location

By default which type of function are use C to pass arguments ?

By default, C uses call by value to pass arguments.

Advance C

Why need of structure ?

In C language array is also a user defined data type but array hold or store only similar type of data, If we want to store different-different type of data in then we need to defined separate variable for each type of data.

Difference between Structure and Union

StructureUnion
1For defining structure use struct keyword.For defining union we use union keyword
2Structure occupies more memory space than union.Union occupies less memory space than Structure.
3In Structure we can access all members of structure at a time.In union we can access only one member of union at a time.
4Structure allocates separate storage space for its every members.Union allocates one common storage space for its all members. Union find which member need more memory than other member, then it allocate that much space

What is advantage of union over structure ?

It occupies less memory because it occupies the memory of largest member only.

What is disadvantage of union over structure ?

It can store data in one member only.

What is syntax error ?

Whenever any mistake are occurred at the time write programming code.

What is the use of a '\0' character ?

It is referred to as a terminating null character, It is generally used to show the end of a string value.

What is wrong with this statement ? name = "porter";

You cannot use the = sign to assign values to a string variable. For assign string value in variable, use the strcpy function like below

Example

strcpy(name, "porte");

File Handling

What is FILE ?

FILE is predefined data type, which is defined in stdio.h.

What is NULL in C ?

NULL is a macro which is defined in C header files. The value of NULL macro is 0.

What is dangling pointer in C ?

When a pointer is pointing to non-existing memory location is called dangling pointer.

What are preprocessor directives ?

Preprocessor is a program which will executed automatically before passing the source program to compiler. This process is called pre-processing.

File Handling

File Handling concept in C language is used for store a data permanently in computer. Using this concept we can store our data in Secondary memory (Hard disk). All files related function are available in stdio.h header file.

How to achieve File Handling in C

For achieving file handling in C we need follow following steps
  • Naming a file
  • Opening a file
  • Reading data from file
  • Writing data into file
  • Closing a file

Functions use in File Handling in C

S.NoFunctionOperation
1fopen()To create a file
2fclose()To close an existing file
3getc()Read a character from a file
4putc()Write a character in file
5fprintf()To write set of data in file
6fscanf()To read set of data from file.
5getw()To read an integer from a file
6putw()To write an integer in file

Defining and Opening a File

Data structure of file is defined as FILE in the standard I/O function. So all files should be declared as type FILE.
Before opening any file we need to specify for which purpose we open file, for example file open for write or read purpose.

Syntax

FILE *fp;
pf=fopen("filename", "mode");
Here fp declare a variable as a pointer to the data type FILE.

Closing a File

A file must be close after completion of all operation related to file. For closing file we need fclose() function.

Syntax

fclose(Filepointer);

File Opening mode

S.NoModeMeaningPurpose
1rReadingOpen the file for reading only.
2wWritingOpen the file for writing only.
3aAppendingOpen the file for appending (or adding) data to it.
4r+Reading + WritingNew data is written at the beginning override existing data.
5w+Writing + ReadingOverride existing data.
6a+Reading + AppendingTo new data is appended at the end of file.

Input/Output Operation on files

To perform Input/Output Operation on files we need below functions.
S.NoFunctionOperationSyntax
1getc()Read a character from a filegetc( fp)
2putc()Write a character in fileputc(c, fp)
3fprintf()To write set of data in filefprintf(fp, "control string", list)
4fscanf()To read set of data from file.fscanf(fp, "control string", list)
5getw()To read an integer from a file.getw(fp)
6putw()To write an integer in file.putw(integer, fp)

Write data in File

Example

#include<stdio.h>
#include<conio.h>

void main()
{
FILE *fp;
char ch[20];
clrscr();
fp=fopen("hh.txt", "w");
printf("Enter any Text: ");
scanf("%s",&ch); // Read data from keyboard
fprintf(fp,"%s",ch); // Write data in file
fclose(fp);
getch();
}

Advance C

Typedef

The C programming language provides a keyword called typedef, by using this keyword you can create a user defined name for existing data type. Generally typedef are use to create an alias name (nickname).

Declaration of typedef

Syntax

 
typedef  datatype alias_name;

Example

 
typedef  int Intdata;

Example of typedef

#include<stdio.h>
#include<conio.h>

typedef int Intdata; // Intdata is alias name of int
void main()
{
int a=10;
Integerdata b=20;
typedef Intdata Integerdata; // Integerdata is again alias name of Intdata
Integerdata s;
clrscr();
s=a+b;
printf("\n Sum:= %d",s);
getch();
}

Output

 
Sum: 20

Code Explanation

  • In above program Intdata is an user defined name or alias name for an integer data type.
  • All properties of the integer will be applied on Intdata also.
  • Integerdata is an alias name to existing user defined name called Intdata.
Note: By using typedef only we can create the alias name and it is under control of compiler.
You can in another example, here myint is alias name for integer data and again smallint is alias name for myint.
typedef

Buffer in C

Temporary storage area is called buffer.
All standard input output devices are containing input output buffer.
In implementation when we are passing more than required number of values as a input then rest of all values will automatically holds in standard input buffer, this buffer data will automatically pass to next input functionality if it is exist.

Example

#include<stdio.h>
#include<conio.h>

void main()
{
int v1,v2;
clrscr();
printf("\n Enter v1 value: ");
scanf("%d",&v1);
printf("\n Enter v2 value: ");
scanf("%d",&v2);
printf("\n v1+v2=%d ",v1+v2);
getch();
}

Output

Enter v1 value: 10 Enter v2 value: 20 V1+v2=30 Again run program Enter v1 value: 10 20 30 Enter v2 value: V1+v2=30
Buffer
Explanation:
In the above example we pass three input in v1 and we cannot pass any value in v2 but value of v1 is automatically pass in v2.
In implementation when we need to remove standard input buffer data then go for flushall() or fflush() function.

flushall()

it is a predefined function which is declared in stdio.h. by using flushall we can remove the data from standard input output buffer.

fflush()

it is a predefined function in "stdio.h" header file used to flush or clear either input or output buffer memory.

fflush(stdin)

it is used to clear the input buffer memory. It is recommended to use before writing scanf statement.

fflush(stdout)

it is used to clear the output buffer memory. It is recommended to use before printf statement.

Example

#include<stdio.h>
#include<conio.h>
void main()
{
int v1,v2;
clrscr();
printf("\n Enter v1 value: ");
scanf("%d",&v1);
printf("\n Enter v2 value: ");
fflush(stdin);
scanf("%d",&v2);
printf("\n v1+v2=%d ",v1+v2);
getch();
}

Output

Enter v1 value: 10 20 30 Enter v2 value: 40 v1+v2=50
Buffer

Pre-processor in C

Preprocessor is a program which will executed automatically before passing the source program to compiler. This process is called pre-processing. The preprocessor provides the ability for the inclusion of header files, macro expansions, conditional compilation, and line control.



The C Preprocessor is not a part of compiler, it is a separate program invoked by the compiler as the first part of translation.
Commands used in preprocessor are called preprocessor directives and they begin with pond "#" symbol and should be not ended with (;).

Defined Proprocessor Directive

Proprocessor Directive can be place any where in the program, but generally it place top of the program before defining the first function.

Example

#include<stdio.h>
#define PI 3.14
void main()
{
printf("%f",PI);
}

Output

3.14

C language preprocessor directives

  • Macro substitution directives. example: #define
  • File inclusion directives. example: #include
  • Conditional compilation directive. example: #if, #else, #ifdef, #undef
  • Miscellaneous directive. example: #error, #line
PreprocessorSyntaxDescription
Macro#defineThis macro defines constant value and can be any of the basic data types.
Header file inclusion#include <file_name>The source code of the file "file_name" is included in the main program at the specified place
Conditional compilation#ifdef, #endif, #if, #else, #ifndefSet of commands are included or excluded in source program before compilation with respect to the condition
Other directives#undef, #pragma#undef is used to undefine a defined macro variable. #Pragma is used to call a function before and after main function in a C program

#ifdef, #else and #endif

"#ifdef" directive checks whether particular macro is defined or not. If it is defined, "If" clause statements are included in source file. Otherwise, "else" clause statements are included in source file for compilation and execution.

Example

#include<stdio.h>
#include<conio.h>

#define AGE 18

void main()
{
clrscr();
#ifdef AGE
{
printf("Eligible for voting\n");
}
#else
{
printf("Not eligible\n");
}
#endif
getch();
}

Output

Eligible for voting

#if, #else and #endif

"If" clause statement is included in source file if given condition is true. Otherwise, else clause statement is included in source file for compilation and execution.

Example

#include<stdio.h>
#include<conio.h>

#define AGE 18

void main()
{
clrscr();
#if (AGE>=18)
{
printf("Eligible for voting");
}
#else
{
printf("\nNot eligible");
}
#endif
getch();
}

Output

Eliginle for voting

undef

This directive undefines existing macro in the program. In below program we first undefine age variable and again it define with new value.

Example

#include<stdio.h>
#include<conio.h>

#define age 18
void main()
{
clrscr();
printf("First defined value for age: %d\n",age);
#undef age      // undefining variable
#define age 30  // redefining age value for for new value
printf("Age after undef redefine: %d",age);
getch();
}

Output

First defined value for age: 18
Age after undef redefine: 30

pragma

Pragma is used to call a function before and after main function in a C program.

Example

#include<stdio.h>
#include<conio.h>
#include<dos.h>

void function1( );
void function2( );

#pragma startup function1
#pragma exit function2

void main( )
{
delay(1000);
printf ("\nI am main function" ) ;
}
void function1( )
{
clrscr();
delay(500);
printf("\nI am function1");
}

void function2( )
{
delay(1000);
printf ( "\nI am function2" );
getch();
}

Output

I am function1
I am main function
I am function2
Explanation: Here delay() function are used for give delay or wait time for execution of code, this function is present in dos.h header file. With the help of delay function you can see clearly flow of above program.


Header Files in C

Header files contain definitions of functions and variables, which is imported or used into any C program by using the pre-processor #include statement. Header file have an extension ".h" which contains C function declaration and macro definition.



Each header file contains information (or declarations) for a particular group of functions. Like stdio.h header file contains declarations of standard input and output functions available in C which is used for get the input and print the output. Similarly, the header file math.h contains declarations of mathematical functions available in C.

Types of Header Files in C

  • System Header Files: It is comes with compiler.
  • User header files: It is written by programmer.

Why need of header files

When we want to use any function in our c program then first we need to import their definition from c library, for importing their declaration and definition we need to include header file in program by using #include. Header file include at the top of any C program.
For example if we use printf() in C program, then we need to include, stdio.h header file, because in stdio.h header file definition of printf() (for print message on screen) is written in stdio.h header file.

Syntax Header Files in C

 
#include<stdio.h>

How to use Header File in Program

Both user and system header files are include using the pre-processing directive #include. It has following two forms:

Syntax

#include<file>
This form is used for system header files. It searches for a file named file in a standard list of system directives.

Syntax

#include"file"
This form used for header files of our own program. It searches for a file named file in the directive containing the current file.
Note: The use of angle brackets <> informs the compiler to search the compilers include directory for the specified file. The use of the double quotes "" around the filename inform the compiler to search in the current directory for the specified file.

Compile and Link C Program

There are three basic phases occurred when we execute any C program.
  • Preprocessing
  • Compiling
  • Linking
Compiling Linking

Preprocessing Phase

A C pre-processor is a program that accepts C code with preprocessing statements and produces a pure form of C code that contains no preprocessing statements (like #include).



Compilation Phase

The C compiler accepts a preprocessed output file from the preprocessor and produces a special file called an object file. Object file contains machine code generated from the program



Linking Phase

The link phase is implemented by the linker. The linker is a process that accepts as input object files and libraries to produce the final executable program.





Dynamic Memory Allocation

  • It is a process of allocating or de-allocating the memory at run time it is called as dynamically memory allocation.
  • When we are working with array or string static memory allocation will be take place that is compile time memory management.
  • When we ate allocating the memory at compile we cannot extend the memory at run time, if it is not sufficient.
  • By using compile time memory management we cannot utilize the memory properly
  • In implementation when we need to utilize the memory more efficiently then go for dynamic memory allocation.
  • By using dynamic memory allocation whenever we want which type we want or how much we type that time and size and that we much create dynamically.
Dynamic memory allocation related all predefined functions are declared in following header files.
  • <alloc.h>
  • <malloc.h>
  • <mem.h>
  • <stdlib.h>

Dynamic memory allocation related functions

Malloc()

By using malloc() we can create the memory dynamically at initial stage. Malloc() required one argument of type size type that is data type size malloc() will creates the memory in bytes format. Malloc() through created memory initial value is garbage.
Syntax:
 
Void*malloc(size type);
Note: Dynamic memory allocation related function can be applied for any data type that's why dynamic memory allocation related functions return void*.
When we are working with dynamic memory allocation type specification will be available at the time of execution that's why we required to use type casting process.

Syntax

 
int *ptr;
ptr=(int*)malloc(sizeof (int)); //2 byte

long double*ldptr;
ldptr=(long double*)malloc(sizeof(long double)) // 2 byte

char*cptr;
cptr=(char*)malloc(sizeof(char)); //1 byte

int*arr;
arr=(int*)malloc(sizeof int()*10); //20 byte

cahr*str;
str=(char*)malloc(sizeof(char)*50); //50 byte

calloc()

  • By using calloc() we can create the memory dynamically at initial stage.
  • calloc() required 2 arguments of type count, size-type.
  • Count will provide number of elements; size-type is data type size.
  • calloc() will creates the memory in blocks format.
  • Initial value of the memory is zero.

Syntax

 
int*arr;
arr=(int*)calloc(10, sizeof(int)); // 20 byte
cahr*str;
str=(char*)calloc(50, siceof(char)); // 50 byte

realloc()

  • By using realloc() we can create the memory dynamically at middle stage.
  • Generally by using realloc() we can reallocation the memory.
  • Realloc() required 2 arguments of type void*, size_type.
  • Void* will indicates previous block base address, size-type is data type size.
  • Realloc() will creates the memory in bytes format and initial value is garbage.

Syntax

 
void*realloc(void*, size-type);
int *arr;
arr=(int*)calloc(5, sizeof(int));
.....
........
....
arr=(int*)realloc(arr,sizeof(int)*10);

free()

  • When we are working with dynamic memory allocation memory will created in heap area of data segment.
  • When we are working with dynamic memory allocation related memory it is a permanent memory if we are not de-allocated that's why when we are working with dynamic memory allocation related program, then always recommended to deleted the memory at the end of the program.
  • By using free(0 dynamic allocation memory can be de-allocated.
  • free() requires one arguments of type void*.

Syntax

 
void free(voie*);
int *arr;
arr=(int*)calloc(10,sizeof(int));
...
......
free(arr);
  • By using malloc(), calloc(), realloc() we can create maximum of 64kb data only.
  • In implementation when we need to create more than 64kb data then go for formalloc(), forcalloc() and forrealloc().
  • By using free() we can de-allocate 64kb data only, if we need to de-allocate more than 64kb data then go for

Syntax

 
forfree().
formalloc()
voidfor*formalloc(size-type);


Why learning C Programming is a must?

C is a procedural programming language. It was initially developed by Dennis Ritchie between 1969 and 1973. It was mainly developed as...