C Notes
C Notes
1. High-Level Languages
Translator
.
The three types of translators used are-
• Assembler
• Compiler
• Interpreter'
History of C Language
History
C-Language
The C Language is developed for creating system applications that directly
interact with the hardware devices such as drivers, kernels, etc.
1. Mother language
2. System programming language
3. Procedure-oriented programming language
4. Structured programming language
5. Mid-level programming language
1) C as a mother language
C language is considered as the mother language of all the modern
programming languages because most of the compilers, JVMs, Kernels,
etc. are written in C language, and most of the programming languages
follow C syntax, for example, C++, Java, C#, etc.
It provides the core concepts like the array, strings, functions, file handling,
etc. that are being used in many languages like C++, Java, C#, etc.
It can't be used for internet programming like Java, .Net, PHP, etc.
3) C as a procedural language
A procedure is known as a function, method, routine, subroutine, etc. A
procedural language specifies a series of steps for the program to
solve the problem.
Features of C Language
C is the widely used language. It provides a lot of features that are given
below.
1. Simple
2. Machine Independent or Portable
3. Mid-level programming language
4. structured programming language
5. Rich Library
6. Memory Management
7. Fast Speed
8. Pointers
9. Recursion
10. Extensible
First C Program
Before starting the abcd of C language, you need to learn how to write,
compile and run the first c program.
To write the first c program, open the C console and write the following
code:
1. #include <stdio.h>
2. void main(){
3. printf("Hello C Language");
4. getch();
5. }
int main() The main() function is the entry point of every program in
c language.
return 0 The return 0 statement, returns execution status to the OS. The 0
value is used for successful execution and 1 for unsuccessful execution.
printf() function
The printf() function is used for output. It prints the given statement to
the console.
1. printf("format string",argument_list);
The format string can be %d (integer), %c (character), %s (string), %f
(float) etc.
scanf() function
The scanf() function is used for input. It reads the input data from the
console.
scanf("format string",argument_list);
Variables in C
A variable is a name of memory location. It is used to store data. Its
value can be changed and it can be reused many times.
1. type variable_list;
1. int a;
2. float b;
3. char c;
Data Types in C
A data type specifies the type of data that a variable can store such as
integer, floating, character etc.
There are 4 types of data types in C language.
The memory size of basic data types may change according to 32 or 64 bit
operating system.
Let's see the basic data types. Its size is given according to 32 bit architecture.
float 4 byte
double 8 byte
Keywords in C
A keyword is a reserved word. You cannot use it as a variable name,
constant name etc. There are only 32 reserved words (keywords) in C
language.
C Operators
An operator is simply a symbol that is used to perform operations. There can
be many types of operations like arithmetic, logical, bitwise etc.
o Arithmetic Operators
o Relational Operators
o Logical Operators
o Bitwise Operators
o Ternary or Conditional Operators
o Assignment Operator
C if else Statement
The if statement in C language is used to perform operation on the basis of
condition. By using if-else statement, you can perform operation either
condition is true or false.
#include<stdio.h>
int main()
{
int number=0;
printf("enter a number:");
scanf("%d",&number);
if(number%2==0){
printf("%d is even number",number);
}
else{
printf("%d is odd number",number);
}
return 0;
}
C Switch Statement
The switch statement in C language is used to execute the code from
multiple conditions.
1. switch(expression){
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
......
default:
code to be executed if all cases are not matched;
}
#include<stdio.h>
int main(){
int number=0;
printf("enter a number:");
scanf("%d",&number);
switch(number){
case 10:
printf("number is equals to 10");
break;
case 50:
printf("number is equal to 50");
break;
case 100:
printf("number is equal to 100");
break;
default:
printf("number is not equal to 10, 50 or 100");
}
return 0;
}
C Loops
The loops in C language are used to execute a block of code or a part of the
program several times.
Suppose that you have to print table of 2, then you need to write 10 lines of
code.
Advantage of loops in C
1) It saves code.
Types of C Loops
There are three types of loops in C language that is given below:
1. do while
2. while
3. for
do-while loop in C
It iterates the code until condition is false. Here, condition is given after the
code. So at least once, code is executed whether condition is true or false.
1. do{
2. //code to be executed
3. }while(condition);
Example
1. #include<stdio.h>
2. int main(){
3. int i=1;
4. do{
5. printf("%d \n",i);
6. i++;
7. }while(i<=10);
8. return 0;
9. }
while loop in C
Like do while, it iterates the code until condition is false. Here, condition is
given before the code. So code may be executed 0 or more times.
1. while(condition){
2. //code to be executed
3. }
Example-
1. #include<stdio.h>
2. int main(){
3. int i=1;
4. while(i<=10){
5. printf("%d \n",i);
6. i++;
7. }
8. return 0;
9. }
for loop in C
Like while, it iterates the code until condition is false. Here, initialization,
condition and increment/decrement is given before the code. So code may
be executed 0 or more times.
for(initialization;condition;incr/decr){
//code to be executed
}
Example-
1. #include<stdio.h>
2. int main(){
3. int i=0;
4. for(i=1;i<=10;i++){
5. printf("%d \n",i);
6. }
7. return 0;
8. }
1. #include<stdio.h>
2. void main ()
3. {
4. int i = 0;
5. while(i!=10)
6. {
7. printf("%d", i);
8. continue;
9. i++;
10. }
11. }
C goto statement
Syntax:
1. label:
2. //some part of the code;
3. goto label;
Example
1. #include <stdio.h>
2. int main()
3. {
4. int num,i=1;
5. printf("Enter the number whose table you want to print?");
6. scanf("%d",&num);
7. table:
8. printf("%d x %d = %d\n",num,i,num*i);
9. i++;
10. if(i<=10)
11. goto table;
12. }
Type Casting in C
Typecasting allows us to convert one data type into other. In C language, we
use cast operator for typecasting which is denoted by (type).
Syntax:
1. (type)value;
1. int f= 9/4;
2. printf("f : %d\n", f );//Output: 2
C Functions
In c, we can divide a large program into the basic building blocks known as
function. The function contains the set of programming statements enclosed
by {}. A function can be called multiple times to provide reusability and
modularity to the C program. In other words, we can say that the collection
of functions creates a program. The function is also known
as procedure or subroutine in other programming languages.
Advantage of functions in C
There are the following advantages of C functions.
Function Aspects
There are three aspects of a C function.
Types of Functions
There are two types of functions in C programming:
Advantage of functions in C
There are the following advantages of C functions.
o By using functions, we can avoid rewriting same logic/code again and again in a
o We can call C functions any number of times in a program and from any place in
o We can track a large C program easily when it is divided into multiple functions.
o Reusability is the main achievement of C functions.
o However, Function calling is always a overhead in a C program.
Function Aspects
There are three aspects of a C function.
o Function call Function can be called from anywhere in the program. The parame
not differ in function calling and function declaration. We must pass the same num
functions as it is declared in the function declaration.
Types of Functions
There are two types of functions in C programming:
1. Library Functions: are the functions which are declared in the C header files su
printf(), gets(), puts(), ceil(), floor() etc.
2. User-defined functions: are the functions which are created by the C programm
he/she can use it many times. It reduces the complexity of a big program and op
code.
Return Value
A C function may or may not return a value from the function. If you don't have to retu
from the function, use void for the return type.
Let's see a simple example of C function that doesn't return any value from the functio
1. void hello(){
2. printf("hello c");
3. }
If you want to return any value from the function, you need to use any data type such
char, etc. The return type depends on the value to be returned from the function.
Let's see a simple example of C function that returns int value from the function.
1. int get(){
2. return 10;
3. }
Call by value and Call by reference in C
There are two methods to pass the data into the function in C language,
i.e., call by value and call by reference.
Call by value in C
o In call by value method, the value of the actual parameters is copied
into the formal parameters. In other words, we can say that the value
of the variable is used in the function call in the call by value method.
o In call by value method, we can not modify the value of the actual
parameter by the formal parameter.
o In call by value, different memory is allocated for actual and formal
parameters since the value of the actual parameter is copied into the
formal parameter.
o The actual parameter is the argument which is used in the function call
whereas formal parameter is the argument which is used in the
function definition.
1. #include<stdio.h>
2. void change(int num) {
3. printf("Before adding value inside function num=%d \n",num);
4. num=num+100;
5. printf("After adding value inside function num=%d \n", num);
6. }
7. int main() {
8. int x=100;
9. printf("Before function call x=%d \n", x);
10. change(x);//passing value in function
11. printf("After function call x=%d \n", x);
12. return 0;
13. }
Recursion in C
Recursion is the process which comes into existence when a function calls a
copy of itself to work on a smaller problem. Any function which calls itself is
called recursive function, and such function calls are called recursive calls.
Recursion involves several numbers of recursive calls. However, it is
important to impose a termination condition of recursion. Recursion code is
shorter than iterative code however it is difficult to understand.
Recursion cannot be applied to all the problem, but it is more useful for the
tasks that can be defined in terms of similar subtasks. For Example,
recursion may be applied to sorting, searching, and traversal problems.
Generally, iterative solutions are more efficient than recursion since function
call is always overhead. Any problem that can be solved recursively, can also
be solved iteratively. However, some problems are best suited to be solved
by the recursion, for example, tower of Hanoi, Fibonacci series, factorial
finding, etc.
1. #include <stdio.h>
2. int fact (int);
3. int main()
4. {
5. int n,f;
6. printf("Enter the number whose factorial you want to calculate?");
7. scanf("%d",&n);
8. f = fact(n);
9. printf("factorial = %d",f);
10. }
11. int fact(int n)
12. {
13. if (n==0)
14. {
15. return 0;
16. }
17. else if ( n == 1)
18. {
19. return 1;
20. }
21. else
22. {
23. return n*fact(n-1);
24. }
25. }
Storage Classes in C
Storage classes in C are used to determine the lifetime, visibility, memory
location, and initial value of a variable. There are four types of storage
classes in C
o Automatic
o External
o Static
o Register
Automatic
o Automatic variables are allocated memory automatically at runtime.
o The visibility of the automatic variables is limited to the block in which
they are defined.
Example 1
1. #include <stdio.h>
2. int main()
3. {
4. int a; //auto
5. char b;
6. float c;
7. printf("%d %c %f",a,b,c); // printing initial default value of automatic variab
les a, b, and c.
8. return 0;
9. }
Static
o The variables defined as static specifier can hold their value between
the multiple function calls.
o Static local variables are visible only to the function or the block in
which they are defined.
o A same static variable can be declared many times but can be
assigned at only one time.
o Default initial value of the static integral variable is 0 otherwise null.
o The visibility of the static global variable is limited to the file in which it
has declared.
o The keyword used to define static variable is static.
Example 1
1. #include<stdio.h>
2. static char c;
3. static int i;
4. static float f;
5. static char s[100];
6. void main ()
7. {
8. printf("%d %d %f %s",c,i,f); // the initial default value of c, i, and f will be p
rinted.
9. }
Register
o The variables defined as the register is allocated the memory into the
CPU registers depending upon the size of the memory remaining in the
CPU.
o We can not dereference the register variables, i.e., we can not use
&operator for the register variable.
o The access time of the register variables is faster than the automatic
variables.
o The initial default value of the register local variables is 0.
o The register keyword is used for the variable which should be stored in
the CPU register. However, it is compiler?s choice whether or not; the
variables can be stored in the register.
o We can store pointers into the register, i.e., a register can store the
address of a variable.
o Static variables can not be stored into the register since we can not
use more than one storage specifier for the same variable.
Example 1
1. #include <stdio.h>
2. int main()
3. {
4. register int a; // variable a is allocated memory in the CPU register. The ini
tial default value of a is 0.
5. printf("%d",a);
6. }
External
o The external storage class is used to tell the compiler that the variable
defined as extern is declared with an external linkage elsewhere in the
program.
o The variables declared as extern are not allocated any memory. It is
only declaration and intended to specify that the variable is declared
elsewhere in the program.
o The default initial value of external integral type is 0 otherwise null.
o We can only initialize the extern variable globally, i.e., we can not
initialize the external variable within any block or method.
o An external variable can be declared many times but can be initialized
at only once.
o If a variable is declared as external then the compiler searches for that
variable to be initialized somewhere in the program which may be
extern or static. If it is not, then the compiler will show an error.
Example 1
1. #include <stdio.h>
2. int main()
3. {
4. extern int a;
5. printf("%d",a);
6. }
C Array
An array is defined as the collection of similar type of data items stored at
contiguous memory locations. Arrays are the derived data type in C
programming language which can store the primitive type of data such as
int, char, double, float, etc. It also has the capability to store the collection
of derived data types, such as pointers, structure, etc. The array is the
simplest data structure where each data element can be randomly accessed
by using its index number.
By using the array, we can access the elements easily. Only a few lines of
code are required to access the elements of the array.
Properties of Array
o Each element of an array is of same data type and carries the same
size, i.e., int = 4 bytes.
o Elements of the array are stored at contiguous memory locations
where the first element is stored at the smallest memory location.
o Elements of the array can be randomly accessed since we can
calculate the address of each element of the array with the given base
address and the size of the data element.
Advantage of C Array
2) Ease of traversing: By using the for loop, we can retrieve the elements
of an array easily.
3) Ease of sorting: To sort the elements of the array, we need a few lines
of code only.
4) Random Access: We can access any element randomly using the array.
Disadvantage of C Array
Declaration of C Array
We can declare an array in the c language in the following way.
1. data_type array_name[array_size];
1. int marks[5];
Initialization of C Array
The simplest way to initialize an array is by using the index of each element.
We can initialize each element of the array by using the index. Consider the
following example.
1. marks[0]=80;//initialization of array
2. marks[1]=60;
3. marks[2]=70;
4. marks[3]=85;
5. marks[4]=75;
C array example
1. #include<stdio.h>
2. int main(){
3. int i=0;
4. int marks[5];//declaration of array
5. marks[0]=80;//initialization of array
6. marks[1]=60;
7. marks[2]=70;
8. marks[3]=85;
9. marks[4]=75;
10. //traversal of array
11. for(i=0;i<5;i++){
12. printf("%d \n",marks[i]);
13. }//end of for loop
14. return 0;
15. }
1. data_type array_name[rows][columns];
1. int twodimen[4][3];
1. int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
C Pointers
The pointer in C language is a variable which stores the address of another
variable. This variable can be of type int, char, array, function, or any other
pointer. The size of the pointer depends on the architecture. However, in 32-
bit architecture the size of a pointer is 2 byte.
Consider the following example to define a pointer which stores the address
of an integer.
1. int n = 10;
2. int* p = &n; // Variable p of type pointer is pointing to the address of the va
riable n of type integer.
Declaring a pointer
The pointer in c language can be declared using * (asterisk symbol). It is
also known as indirection pointer used to dereference a pointer.
Pointer Example
An example of using pointers to print the address and value is given below.
As you can see in the above figure, pointer variable stores the address of
number variable, i.e., fff4. The value of number variable is 50. But the
address of pointer variable p is aaa3.
Let's see the pointer example as explained for the above figure.
1. #include<stdio.h>
2. int main(){
3. int number=50;
4. int *p;
5. p=&number;//stores the address of number variable
6. printf("Address of p variable is %x \n",p); // p contains the address of the n
umber therefore printing p gives the address of number.
7. printf("Value of p variable is %d \n",*p); // As we know that * is used to der
eference a pointer therefore if we print *p, we will get the value stored at th
e address contained by p.
8. return 0;
9. }
Pointer to array
1. int arr[10];
2. int *p[10]=&arr; // Variable p of type pointer is pointing to the address of a
n integer array arr.
Pointer to a function
1. void show (int);
2. void(*p)(int) = &display; // Pointer p is pointing to the address of a functio
n
Pointer to structure
1. struct st {
2. int i;
3. float f;
4. }ref;
5. struct st *p = &ref;
Advantage of pointer
1) Pointer reduces the code and improves the performance, it is used to
retrieving strings, trees, etc. and used with arrays, structures, and functions.
Usage of pointer
There are many applications of pointers in c language.
1. malloc()
2. calloc()
3. realloc()
4. free()
memory can't be increased while executing memory can be increased while exec
program. program.
Now let's have a quick look at the methods used for dynamic memory
allocation.
1. ptr=(cast-type*)malloc(byte-size)
1. #include<stdio.h>
2. #include<stdlib.h>
3. int main(){
4. int n,i,*ptr,sum=0;
5. printf("Enter number of elements: ");
6. scanf("%d",&n);
7. ptr=(int*)malloc(n*sizeof(int)); //memory allocated using malloc
8. if(ptr==NULL)
9. {
10. printf("Sorry! unable to allocate memory");
11. exit(0);
12. }
13. printf("Enter elements of array: ");
14. for(i=0;i<n;++i)
15. {
16. scanf("%d",ptr+i);
17. sum+=*(ptr+i);
18. }
19. printf("Sum=%d",sum);
20. free(ptr);
21. return 0;
22. }
calloc() function in C
The calloc() function allocates multiple block of requested memory.
1. ptr=(cast-type*)calloc(number, byte-size)
1. #include<stdio.h>
2. #include<stdlib.h>
3. int main(){
4. int n,i,*ptr,sum=0;
5. printf("Enter number of elements: ");
6. scanf("%d",&n);
7. ptr=(int*)calloc(n,sizeof(int)); //memory allocated using calloc
8. if(ptr==NULL)
9. {
10. printf("Sorry! unable to allocate memory");
11. exit(0);
12. }
13. printf("Enter elements of array: ");
14. for(i=0;i<n;++i)
15. {
16. scanf("%d",ptr+i);
17. sum+=*(ptr+i);
18. }
19. printf("Sum=%d",sum);
20. free(ptr);
21. return 0;
22. }
1. malloc()
2. calloc()
3. realloc()
4. free()
Before learning above functions, let's understand the difference between static memory
and dynamic memory allocation.
Now let's have a quick look at the methods used for dynamic memory allocation.
malloc() function in C
The malloc() function allocates single block of requested memory.
It doesn't initialize memory at execution time, so it has garbage value initially.
1. ptr=(cast-type*)malloc(byte-size)
1. #include<stdio.h>
2. #include<stdlib.h>
3. int main(){
4. int n,i,*ptr,sum=0;
5. printf("Enter number of elements: ");
6. scanf("%d",&n);
7. ptr=(int*)malloc(n*sizeof(int)); //memory allocated using malloc
8. if(ptr==NULL)
9. {
10. printf("Sorry! unable to allocate memory");
11. exit(0);
12. }
13. printf("Enter elements of array: ");
14. for(i=0;i<n;++i)
15. {
16. scanf("%d",ptr+i);
17. sum+=*(ptr+i);
18. }
19. printf("Sum=%d",sum);
20. free(ptr);
21. return 0;
22. }
Output:
1. ptr=(cast-type*)calloc(number, byte-size)
1. #include<stdio.h>
2. #include<stdlib.h>
3. int main(){
4. int n,i,*ptr,sum=0;
5. printf("Enter number of elements: ");
6. scanf("%d",&n);
7. ptr=(int*)calloc(n,sizeof(int)); //memory allocated using calloc
8. if(ptr==NULL)
9. {
10. printf("Sorry! unable to allocate memory");
11. exit(0);
12. }
13. printf("Enter elements of array: ");
14. for(i=0;i<n;++i)
15. {
16. scanf("%d",ptr+i);
17. sum+=*(ptr+i);
18. }
19. printf("Sum=%d",sum);
20. free(ptr);
21. return 0;
22. }
Output:
realloc() function in C
If memory is not sufficient for malloc() or calloc(), you can reallocate the memory by re
function. In short, it changes the memory size.
1. ptr=realloc(ptr, new-size)
free() function in C
The memory occupied by malloc() or calloc() functions must be released by calling free
Otherwise, it will consume memory until program exit.
1. free(ptr)
C Structure
1. #include<stdio.h>
2. void main ()
3. {
4. char names[2][10],dummy; // 2-
dimensioanal character array names is used to store the names of the stude
nts
5. int roll_numbers[2],i;
6. float marks[2];
7. for (i=0;i<3;i++)
8. {
9.
10. printf("Enter the name, roll number, and marks of the student %d",i
+1);
11. scanf("%s %d %f",&names[i],&roll_numbers[i],&marks[i]);
12. scanf("%c",&dummy); // enter will be stored into dummy character
at each iteration
13. }
14. printf("Printing the Student details ...\n");
15. for (i=0;i<3;i++)
16. {
17. printf("%s %d %f\n",names[i],roll_numbers[i],marks[i]);
18. }
19. }
What is Structure
Structure in c is a user-defined data type that enables us to store the
collection of different data types. Each element of a structure is called a
member. Structures ca; simulate the use of classes and templates as it can
store various information
The ,struct keyword is used to define the structure. Let's see the syntax to
define the structure in c.
1. struct structure_name
2. {
3. data_type member1;
4. data_type member2;
5. .
6. .
7. data_type memeberN;
8. };
1. struct employee
2. { int id;
3. char name[20];
4. float salary;
5. };
The following image shows the memory allocation of the structure employee
that is defined in the above example.
1. #include<stdio.h>
2. #include <string.h>
3. struct employee
4. { int id;
5. char name[50];
6. }e1; //declaring e1 variable for structure
7. int main( )
8. {
9. //store first employee information
10. e1.id=101;
11. strcpy(e1.name, "Sonoo Jaiswal");//copying string into char array
12. //printing first employee information
13. printf( "employee 1 id : %d\n", e1.id);
14. printf( "employee 1 name : %s\n", e1.name);
15. return 0;
16. }
C Union
Like structure, Union in c language is a user-defined data type that is used
to store the different type of elements.
At once, only one member of the union can occupy the memory. In other
words, we can say that the size of the union in any instance is equal to the
size of its largest element.
Defining union
The union keyword is used to define the union. Let's see the syntax to
define union in c.
1. union union_name
2. {
3. data_type member1;
4. data_type member2;
5. .
6. .
7. data_type memeberN;
8. };
1. union employee
2. { int id;
3. char name[50];
4. float salary;
5. };
C Union example
Let's see a simple example of union in C language.
1. #include <stdio.h>
2. #include <string.h>
3. union employee
4. { int id;
5. char name[50];
6. }e1; //declaring e1 variable for union
7. int main( )
8. {
9. //store first employee information
10. e1.id=101;
11. strcpy(e1.name, "Sonoo Jaiswal");//copying string into char array
12. //printing first employee information
13. printf( "employee 1 id : %d\n", e1.id);
14. printf( "employee 1 name : %s\n", e1.name);
15. return 0;
16. }
File Handling in C
In programming, we may require some specific input data to be generated
several numbers of times. Sometimes, it is not enough to only display the
data on the console. The data to be displayed may be very large, and only a
limited amount of data can be displayed on the console, and since the
memory is volatile, it is impossible to recover the programmatically
generated data again and again. However, if we need to do so, we may store
it onto the local file system which is volatile and can be accessed every time.
Here, comes the need of file handling in C.
File handling in C enables us to create, update, read, and delete the files
stored on the local file system through our C program. The following
operations can be performed on a file.
o The file name (string). If the file is stored at some specific location,
then we must mention the path at which the file is stored. For
example, a file name can be like "c://some_folder/some_file.ext".
o The mode in which the file is to be opened. It is a string.
Mode Description
1. #include<stdio.h>
2. void main( )
3. {
4. FILE *fp ;
5. char ch ;
6. fp = fopen("file_handle.c","r") ;
7. while ( 1 )
8. {
9. ch = fgetc ( fp ) ;
10. if ( ch == EOF )
11. break ;
12. printf("%c",ch) ;
13. }
14. fclose (fp ) ;
15. }
Syntax:
Example:
1. #include <stdio.h>
2. main(){
3. FILE *fp;
4. fp = fopen("file.txt", "w");//opening file
5. fprintf(fp, "Hello file by fprintf...\n");//writing data into file
6. fclose(fp);//closing file
7. }
Syntax:
Example:
1. #include <stdio.h>
2. main(){
3. FILE *fp;
4. char buff[255];//creating char array to store data of file
5. fp = fopen("file.txt", "r");
6. while(fscanf(fp, "%s", buff)!=EOF){
7. printf("%s ", buff );
8. }
9. fclose(fp);
10. }
Syntax:
Example:
1. #include <stdio.h>
2. main(){
3. FILE *fp;
4. fp = fopen("file1.txt", "w");//opening file
5. fputc('a',fp);//writing single character into file
6. fclose(fp);//closing file
7. }
file1.txt
Syntax:
Example:
1. #include<stdio.h>
2. #include<conio.h>
3. void main(){
4. FILE *fp;
5. char c;
6. clrscr();
7. fp=fopen("myfile.txt","r");
8.
9. while((c=fgetc(fp))!=EOF){
10. printf("%c",c);
11. }
12. fclose(fp);
13. getch();
14. }