Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
18 views

C Notes

Uploaded by

Keshav Singh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

C Notes

Uploaded by

Keshav Singh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 56

Computer programming language, any of various languages for

expressing a set of detailed instructions for a digital computer. Such


instructions can be executed directly when they are in the computer
manufacturer-specific numerical form known as machine language,
after a simple substitution process when expressed in a
corresponding assembly language, or after translation from some
“higher-level” language. Although there are many computer
languages, relatively few are widely used.

1. Low level languages


. \ 2. HIgh level languages

1. High-Level Languages

High-level languages are designed to be used by the human operator or


the programmer. They are referred to as "closer to humans."
A high-level language does not require addressing hardware constraints
when developing a program. However, every single program written in a
high-level language
FORTRAN,COBOL, BASIC, Pascal etc

2.Machine Level Language.

machine language is a collection of binary digits or bits that


the computer reads and interprets. Machine language is the
only language a computer is capable of understanding.

Translator
.
The three types of translators used are-
• Assembler
• Compiler
• Interpreter'
History of C Language

History

C programming language was developed in 1970 by Dennis Ritchie at bell


laboratories of AT&T (American Telephone & Telegraph), located in the
U.S.A.

Dennis Ritchie is known as the founder of the c language.

It was developed to overcome the problems of previous languages such as


B, BCPL, etc.

Initially, C language was developed to be used in UNIX operating system.


It inherits many features of previous languages such as B and BCPL.

Let's see the programming languages that were developed before C


language.

Language Year Developed By

Algol 1960 International Group

BCPL 1967 Martin Richard

B 1970 Ken Thompson

Traditional C 1972 Dennis Ritchie


K&RC 1978 Kernighan & Dennis Ritchie

ANSI C 1989 ANSI Committee

ANSI/ISO C 1990 ISO Committee

C99 1999 Standardization Committee

C-Language
The C Language is developed for creating system applications that directly
interact with the hardware devices such as drivers, kernels, etc.

C programming is considered as the base for other programming languages,


that is why it is known as mother language.

It can be defined by the following ways:

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.

2) C as a system programming language


A system programming language is used to create system software. C
language is a system programming language because it can be used to do
low-level programming (for example driver and kernel). It is generally
used to create hardware devices, OS, drivers, kernels, etc. For example,
Linux kernel is written in C.

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.

A procedural language breaks the program into functions, data structures,


etc.

C is a procedural language. In C, variables and function prototypes must be


declared before being used.

4) C as a structured programming language


A structured programming language is a subset of the procedural
language. Structure means to break a program into parts or blocks so
that it may be easy to understand.

In the C language, we break the program into parts using functions. It


makes the program easier to understand and modify.
5) C as a mid-level programming language
C is considered as a middle-level language because it supports the feature
of both low-level and high-level languages. C language program is
converted into assembly code, it supports pointer arithmetic (low-level), but
it is machine independent (a feature of high-level).

A Low-level language is specific to one machine, i.e., machine dependent.


It is machine dependent, fast to run. But it is not easy to understand.

A High-Level language is not specific to one machine, i.e., machine


independent. It is easy to understand.

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

#include <stdio.h> includes the standard input output library functions.


The printf() function is defined in stdio.h .

int main() The main() function is the entry point of every program in
c language.

printf() The printf() function is used to print data on the console.

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() and scanf() in C


The printf() and scanf() functions are used for input and output in C
language. Both functions are inbuilt library functions, defined in stdio.h
(header file).

printf() function

The printf() function is used for output. It prints the given statement to
the console.

The syntax of printf() function is given below:

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.

It is a way to represent memory location through symbol so that it can be


easily identified.

Let's see the syntax to declare a variable:

1. type variable_list;

The example of declaring variable is given below:

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.

Basic Data Types


The basic data types are integer-based and floating-point based. C language
supports both signed and unsigned literals.

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.

Data Types Memory Size Range

char 1 byte −128 to 127

signed char 1 byte −128 to 127

unsigned char 1 byte 0 to 255

short 2 byte −32,768 to 32,767

signed short 2 byte −32,768 to 32,767

unsigned short 2 byte 0 to 65,535


int 2 byte −32,768 to 32,767

signed int 2 byte −32,768 to 32,767

unsigned int 2 byte 0 to 65,535

short int 2 byte −32,768 to 32,767

signed short int 2 byte −32,768 to 32,767

unsigned short int 2 byte 0 to 65,535

long int 4 byte -2,147,483,648 to 2,147,483,647

signed long int 4 byte -2,147,483,648 to 2,147,483,647

unsigned long int 4 byte 0 to 4,294,967,295

float 4 byte

double 8 byte

long double 10 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.

A list of 32 keywords in c language is given below:

auto break case char const continue


double else enum extern float for

int long register return short signed

struct switch typedef union unsigned void

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.

There are following types of operators to perform different types of


operations in C language.

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.

There are many ways to use if statement in C language:


o If statement
o If-else statement
o If else-if ladder
o Nested if

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

It is like if else-if ladder statement.

The syntax of switch statement in c language is given below:

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.

In other words, it iterates a code or group of code many times.


Why use loops in C language?

Suppose that you have to print table of 2, then you need to write 10 lines of
code.

By using the loop statement, you can do it by 2 or 3 lines of code only.

Advantage of loops in C

1) It saves code.

2) It helps to traverse the elements of array (which is covered in next


pages).

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.

It is better if you have to execute the code at least once.

The syntax of do-while loop in c language is given below:

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.

It is better if number of iteration is not known by the user.

The syntax of while loop in c language is given below:

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.

It is good if number of iteration is known by the user.

The syntax of for loop in c language is given below:

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

C break statement with the nested loop


1. #include<stdio.h>
2. int main(){
3. int i=1,j=1;//initializing a local variable
4. for(i=1;i<=3;i++){
5. for(j=1;j<=3;j++){
6. printf("%d &d\n",i,j);
7. if(i==2 && j==2){
8. break;//will break loop of j only
9. }
10. }//end of for loop
11. return 0;
12. }
Continue statement example 1

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;

Without Type Casting:

1. int f= 9/4;
2. printf("f : %d\n", f );//Output: 2

With Type Casting:

1. float f=(float) 9/4;


2. printf("f : %f\n", f );//Output: 2.250000

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.

o By using functions, we can avoid rewriting same logic/code again and


again in a program.
o We can call C functions any number of times in a program and from
any place in a program.
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 declaration A function must be declared globally in a c


program to tell the compiler about the function name, function
parameters, and return type.

o Function call Function can be called from anywhere in the program.


The parameter list must not differ in function calling and function
declaration. We must pass the same number of functions as it is
declared in the function declaration.

o Function definition It contains the actual statements which are to be


executed. It is the most important aspect to which the control comes
when the function is called. Here, we must notice that only one value
can be returned from the function.

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 such as scanf(), printf(), gets(), puts(), ceil(), floor() etc.
2. User-defined functions: are the functions which are created by the
C programmer, so that he/she can use it many times. It reduces the
complexity of a big program and optimizes the code.
C Functions
In c, we can divide a large program into the basic building blocks known as function. Th
contains the set of programming statements enclosed by {}. A function can be called m
to provide reusability and modularity to the C program. In other words, we can say tha
collection of functions creates a program. The function is also known as procedure or s
other programming languages.

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 declaration A function must be declared globally in a c program to tel


about the function name, function parameters, and return type.

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.

o Function definition It contains the actual statements which are to be executed.


most important aspect to which the control comes when the function is called. He
notice that only one value can be returned from the function.
SN C function aspects Syntax

1 Function declaration return_type function_name (argument list);

2 Function call function_name (argument_list)

3 Function definition return_type function_name (argument list) {functio

The syntax of creating function in c language is given below:

1. return_type function_name(data_type parameter...){


2. //code to be executed
3. }

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

Example without return value:

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.

Example with return value:

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.

Let's understand call by value and call by reference in c language one by


one.

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.

Let's try to understand the concept of call by value in c language by the


example given below:

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

Call by Value Example: Swapping the values of the two variables


1. #include <stdio.h>
2. void swap(int , int); //prototype of the function
3. int main()
4. {
5. int a = 10;
6. int b = 20;
7. printf("Before swapping the values in main a = %d, b = %d\n",a,b); // pr
inting the value of a and b in main
8. swap(a,b);
9. printf("After swapping values in main a = %d, b = %d\n",a,b); // The val
ue of actual parameters do not change by changing the formal parameters in
call by value, a = 10, b = 20
10. }
11. void swap (int a, int b)
12. {
13. int temp;
14. temp = a;
15. a=b;
16. b=temp;
17. printf("After swapping values in function a = %d, b = %d\n",a,b); /
/ Formal parameters, a = 20, b = 10
18. }

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.

In the following example, recursion is used to calculate the factorial of a


number.

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

Storage Storage Default Scope Lifetime


Classes Place Value

auto RAM Garbage Local Within function


Value

extern RAM Zero Global Till the end of the main


program Maybe declared
anywhere in the program
static RAM Zero Local Till the end of the main
program, Retains value
between multiple functions
call

register Register Garbage Local Within the function


Value

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.

The scope of the automatic variables is limited to the block in which


they are defined.
o The automatic variables are initialized to garbage by default.
o The memory assigned to automatic variables gets freed upon exiting
from the block.
o The keyword used for defining automatic variables is auto.
o Every local variable is automatic in C by default.

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.

C array is beneficial if you have to store similar elements. For example, if we


want to store the marks of a student in 6 subjects, then we don't need to
define different variables for the marks in the different subject. Instead of
that, we can define an array which can store the marks in each subject at
the contiguous memory locations.

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

The array contains the following properties.

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

1) Code Optimization: Less code to the access the data.

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

1) Fixed Size: Whatever size, we define at the time of declaration of the


array, we can't exceed the limit. So, it doesn't grow the size dynamically like
LinkedList which we will learn later.

Declaration of C Array
We can declare an array in the c language in the following way.

1. data_type array_name[array_size];

Now, let us see the example to declare the array.

1. int marks[5];

Here, int is the data_type, marks are the array_name, and 5 is


the array_size.

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

C Array Example: Sorting an array


In the following program, we are using bubble sort method to sort the array
in ascending order.
1. #include<stdio.h>
2. void main ()
3. {
4. int i, j,temp;
5. int a[10] = { 10, 9, 7, 101, 23, 44, 12, 78, 34, 23};
6. for(i = 0; i<10; i++)
7. {
8. for(j = i+1; j<10; j++)
9. {
10. if(a[j] > a[i])
11. {
12. temp = a[i];
13. a[i] = a[j];
14. a[j] = temp;
15. }
16. }
17. }
18. printf("Printing Sorted Element List ...\n");
19. for(i = 0; i<10; i++)
20. {
21. printf("%d\n",a[i]);
22. }
23. }

Program to print the largest and second largest


element of the array.
1. #include<stdio.h>
2. void main ()
3. {
4. int arr[100],i,n,largest,sec_largest;
5. printf("Enter the size of the array?");
6. scanf("%d",&n);
7. printf("Enter the elements of the array?");
8. for(i = 0; i<n; i++)
9. {
10. scanf("%d",&arr[i]);
11. }
12. largest = arr[0];
13. sec_largest = arr[1];
14. for(i=0;i<n;i++)
15. {
16. if(arr[i]>largest)
17. {
18. sec_largest = largest;
19. largest = arr[i];
20. }
21. else if (arr[i]>sec_largest && arr[i]!=largest)
22. {
23. sec_largest=arr[i];
24. }
25. }
26. printf("largest = %d, second largest = %d",largest,sec_largest);
27.
28. }

Two Dimensional Array in C


The two-dimensional array can be defined as an array of arrays. The 2D
array is organized as matrices which can be represented as the collection of
rows and columns. However, 2D arrays are created to implement a relational
database lookalike data structure. It provides ease of holding the bulk of
data at once which can be passed to any number of functions wherever
required.

Declaration of two dimensional Array in C


The syntax to declare the 2D array is given below.

1. data_type array_name[rows][columns];

Consider the following example.

1. int twodimen[4][3];

Here, 4 is the number of rows, and 3 is the number of columns.


Initialization of 2D Array in C
In the 1D array, we don't need to specify the size of the array if the
declaration and initialization are being done simultaneously. However, this
will not work with 2D arrays. We will have to define at least the second
dimension of the array. The two-dimensional array can be declared and
defined in the following way.

1. int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};

Two-dimensional array example in C


1. #include<stdio.h>
2. int main(){
3. int i=0,j=0;
4. int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
5. //traversing 2D array
6. for(i=0;i<4;i++){
7. for(j=0;j<3;j++){
8. printf("arr[%d] [%d] = %d \n",i,j,arr[i][j]);
9. }//end of j
10. }//end of i
11. return 0;
12. }

C language passing an array to function example


1. #include<stdio.h>
2. int minarray(int arr[],int size){
3. int min=arr[0];
4. int i=0;
5. for(i=1;i<size;i++){
6. if(min>arr[i]){
7. min=arr[i];
8. }
9. }//end of for
10. return min;
11. }//end of function
12.
13. int main(){
14. int i=0,min=0;
15. int numbers[]={4,5,7,3,8,9};//declaration of array
16.
17. min=minarray(numbers,6);//passing array with size
18. printf("minimum number is %d \n",min);
19. return 0;
20. }

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.

1. int *a;//pointer to int


2. char *c;//pointer to char

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.

By the help of * (indirection operator), we can print the value of pointer


variable p.

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.

2) We can return multiple values from a function using the pointer.

3) It makes you able to access any memory location in the computer's


memory.

Usage of pointer
There are many applications of pointers in c language.

1) Dynamic memory allocation

In c language, we can dynamically allocate memory using malloc() and


calloc() functions where the pointer is used.
2) Arrays, Functions, and Structures

Pointers in c language are widely used in arrays, functions, and structures. It


reduces the code and improves the performance.

2D array example: Storing elements in a matrix


and printing it.
1. #include <stdio.h>
2. void main ()
3. {
4. int arr[3][3],i,j;
5. for (i=0;i<3;i++)
6. {
7. for (j=0;j<3;j++)
8. {
9. printf("Enter a[%d][%d]: ",i,j);
10. scanf("%d",&arr[i][j]);
11. }
12. }
13. printf("\n printing the elements ....\n");
14. for(i=0;i<3;i++)
15. {
16. printf("\n");
17. for (j=0;j<3;j++)
18. {
19. printf("%d\t",arr[i][j]);
20. }
21. }
22. }
Dynamic memory allocation in C
The concept of dynamic memory allocation in c language enables the C
programmer to allocate memory at runtime. Dynamic memory allocation in c
language is possible by 4 functions of stdlib.h header file.

1. malloc()
2. calloc()
3. realloc()
4. free()

Before learning above functions, let's understand the difference between


static memory allocation and dynamic memory allocation.

static memory allocation dynamic memory allocation

memory is allocated at compile time. memory is allocated at run time.

memory can't be increased while executing memory can be increased while exec
program. program.

used in array. used in linked list.

Now let's have a quick look at the methods used for dynamic memory
allocation.

malloc() allocates single block of requested memory.

calloc() allocates multiple block of requested memory.

realloc() reallocates the memory occupied by malloc() or calloc() functions.

free() frees the dynamically allocated memory.


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.

It returns NULL if memory is not sufficient.

The syntax of malloc() function is given below:

1. ptr=(cast-type*)malloc(byte-size)

Let's see the example of malloc() function.

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.

It initially initialize all bytes to zero.

It returns NULL if memory is not sufficient.

The syntax of calloc() function is given below:

1. ptr=(cast-type*)calloc(number, byte-size)

Let's see the example of calloc() function.

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

Dynamic memory allocation in C


The concept of dynamic memory allocation in c language enables the C programm
memory at runtime. Dynamic memory allocation in c language is possible by 4 function
header file.

1. malloc()
2. calloc()
3. realloc()
4. free()

Before learning above functions, let's understand the difference between static memory
and dynamic memory allocation.

static memory allocation dynamic memory allocation

memory is allocated at compile time. memory is allocated at run time.

memory can't be increased while executing memory can be increased while


program. program.

used in array. used in linked list.

Now let's have a quick look at the methods used for dynamic memory allocation.

malloc() allocates single block of requested memory.

calloc() allocates multiple block of requested memory.

realloc() reallocates the memory occupied by malloc() or calloc() functions.

free() frees the dynamically allocated memory.

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.

It returns NULL if memory is not sufficient.

The syntax of malloc() function is given below:

1. ptr=(cast-type*)malloc(byte-size)

Let's see the example of malloc() function.

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:

Enter elements of array: 3


Enter elements of array: 10
10
10
Sum=30
calloc() function in C
The calloc() function allocates multiple block of requested memory.

It initially initialize all bytes to zero.

It returns NULL if memory is not sufficient.

The syntax of calloc() function is given below:

1. ptr=(cast-type*)calloc(number, byte-size)

Let's see the example of calloc() function.

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:

Enter elements of array: 3


Enter elements of array: 10
10
10
Sum=30

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.

Let's see the syntax of realloc() function.

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.

Let's see the syntax of free() function.

1. free(ptr)

C Structure

Why use structure?


In C, there are cases where we need to store multiple attributes of an entity.
It is not necessary that an entity has all the information of one type only. It
can have different attributes of different data types. For example, an
entity Student may have its name (string), roll number (int), marks (float).
To store such type of information regarding an entity student, we have the
following approaches:

o Construct individual arrays for storing names, roll numbers, and


marks.
o Use a special data structure to store the collection of different data
types.

Let's look at the first approach in detail.

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. };

Let's see the example to define a structure for an entity employee in c.

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.

Here, struct is the keyword; employee is the name of the


structure; id, name, and salary are the members or fields of the structure.
Let's understand it by the diagram given below:
C Structure example
Let's see a simple example of structure in C language.

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.

Advantage of union over structure


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

Disadvantage of union over structure


Only the last entered data can be stored in the union. It overwrites the data
previously stored in the union.

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. };

Let's see the example to define union for an employee in c.

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 Creation of the new file


o Opening an existing file
o Reading from the file
o Writing to the file
o Deleting the file

Functions for file handling


There are many functions in the C library to open, read, write, search and
close the file. A list of file functions are given below:

No. Function Description

1 fopen() opens new or existing file

2 fprintf() write data into the file

3 fscanf() reads data from the file

4 fputc() writes a character into the file


5 fgetc() reads a character from file

6 fclose() closes the file

7 fseek() sets the file pointer to given position

8 fputw() writes an integer to file

9 fgetw() reads an integer from file

10 ftell() returns current position

11 rewind() sets the file pointer to the beginning of the file

Opening File: fopen()


We must open a file before it can be read, write, or update. The fopen()
function is used to open a file. The syntax of the fopen() is given below.

1. FILE *fopen( const char * filename, const char * mode );

The fopen() function accepts two parameters:

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.

We can use one of the following modes in the fopen() function.

Mode Description

r opens a text file in read mode


w opens a text file in write mode

a opens a text file in append mode

r+ opens a text file in read and write mode

w+ opens a text file in read and write mode

a+ opens a text file in read and write mode

rb opens a binary file in read mode

wb opens a binary file in write mode

ab opens a binary file in append mode

rb+ opens a binary file in read and write mode

wb+ opens a binary file in read and write mode

ab+ opens a binary file in read and write mode

The fopen function works in the following way.

o Firstly, It searches the file to be opened.


o Then, it loads the file from the disk and place it into the buffer. The
buffer is used to provide efficiency for the read operations.
o It sets up a character pointer which points to the first character of the
file.

Consider the following example which opens a file in write mode.

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

C fprintf() and fscanf()

Writing File : fprintf() function


The fprintf() function is used to write set of characters into file. It sends
formatted output to a stream.

Syntax:

1. int fprintf(FILE *stream, const char *format [, argument, ...])

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

Reading File : fscanf() function


The fscanf() function is used to read set of characters from file. It reads a
word from the file and returns EOF at the end of file.

Syntax:

1. int fscanf(FILE *stream, const char *format [, argument, ...])

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

C fputc() and fgetc()

Writing File : fputc() function


The fputc() function is used to write a single character into file. It outputs a
character to a stream.

Syntax:

1. int fputc(int c, FILE *stream)

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

Reading File : fgetc() function


The fgetc() function returns a single character from the file. It gets a
character from the stream. It returns EOF at the end of file.

Syntax:

1. int fgetc(FILE *stream)

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

You might also like