0% found this document useful (0 votes)
18 views58 pages

C Programming Micro 1 - 045421

All notes about c programming

Uploaded by

megharjmk88
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views58 pages

C Programming Micro 1 - 045421

All notes about c programming

Uploaded by

megharjmk88
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 58

What is C?

C is a general-purpose, procedural,(assembly) Middle-level


programming language used in the development of computer software
and applications, system programming, games, and more.
• C language was developed by Dennis M. Ritchie at the Bell
Telephone Laboratories in 1972.
• It is a powerful and flexible language which was first developed for
the programming of the UNIX operating System.
• C is one of the most widely used programming languages.

Features of C Language
C is the widely used language. It provides many features that are given
below 1 Simple C is a simple language in the sense that it provides a
structured approach (to break the problem into parts), the rich set of
library functions, data types, etc.
2) Machine Independent or Portable Unlike assembly language, c
programs can be executed on different machines with some machine
specific changes. Therefore, C is a machine independent language.
3) Mid-level programming language Although, C is intended to do
lowlevel programming. It is used to develop system applications such as
kernel, driver, etc. It also supports the features of a high-level language.
That is why it is known as mid-level language.
4) Structured programming language C is a structured programming
language in the sense that we can break the program into parts using
functions. So, it is easy to understand and modify. Functions also provide
code reusability.
5) Rich Library C provides a lot of inbuilt functions that make the
development fast.
6) Memory Management It supports the feature of dynamic memory
allocation. In C language, we can free the allocated memory at any time by
calling the free() function.
7) Speed The compilation and execution time of C language is fast since
there are lesser inbuilt functions and hence the lesser overhead.
8) Pointer C provides the feature of pointers. We can directly interact with
the memory by using the pointers. We can use pointers for memory,
structures, functions, array, etc.

9) Recursion In C, we can call the function within the function. It


provides code reusability for every function. Recursion enables us to use the
approach of backtracking.
10) Extensible C language is extensible because it can easily adopt new
features.

What is a compilation?
The compilation is a process of converting the source code into object code. It is done
with the help of the compiler. The compiler checks the source code for the syntactical or
structural errors, and if the source code is error-free, then it generates the object code.

The c compilation process converts the source code taken as input into the
object code or machine code. The compilation process can be divided into
four steps, i.e., Pre-processing, Compiling, Assembling, and Linking. The
preprocessor takes the source code as an input, and it removes all the
comments from the source code. The preprocessor takes the preprocessor
directive and interprets it. For example, if <stdio.h>, the directive is available
in the program, then the preprocessor interprets the directive and replace
this directive with the content of the 'stdio.h' file. The following are the
phases through which our program passes before being transformed into an
executable form:
o Preprocessor o

Compiler o
Assembler o
Linker

A constant in C is a user-assigned name to a location in the


memory, whose value cannot be modified once declared. This is in
contrast to a variable in C, which is also a named memory location,
however whose value may be changed during the course of the
code.

Instead of repeatedly using hard-coded values in a program, it is


advised to define a constant and use it. Constants in a C program are
usually employed to refer to a value which may be error-prone if it
is to be used repetitively in the program, at the same time its value
is not likely to change.

For example, the value of mathematical constant PI is a


highprecision floating point number 3.14159265359, and if it is
likely to appear frequently, it is declared as a constant and used by
its name. We may consider a constant in C as a read-only variable,
as its value can only be used subsequently but cannot be modified.
You can declare a constant in C program with either of the following
two ways −

• Using the const Keyword


• Using the #define Directive

Let's understand these two ways of declaring a constant in C. The


syntax of declaring a constant is as follows −

const type NAME = val;

For example,

const float PI = 3.14159265359;


We can now use PI in any expression, as we would use any variable
Example
#include <stdio.h>
int
main(){
const float PI = 3.14159265359;
float radius = 5; float area =
PI*radius*radius; printf
("area: %f", area); return 0;}
A variable in C is a memory location with some name that helps store some
form of data and retrieves it when required. We can store different types of
data in the variable and reuse the same variable for storing some other data
any number of times.
C Variable Syntax
The syntax to declare a variable in C specifies the name and the type of the
variable.
data_type variable_name = valu e; // defining single variabl e
or
data_ type variable_name1, variable_name2 ; // defining multiple
variabl e

Here,
• data_type: Type of data that a variable can store.
• variable_name: Name of the variable given by the user.

C Variable Types
The C variables can be classified into the following types:
1. Local Variables
2. Global Variables
3. Static Variables
4. Automatic Variables
5. Extern Variables
6. Register Variables
There are 3 aspects of defining a variable:
1. Variable Declaration
2. Variable Definition
3. Variable Initialization
Variable declaration in C tells the compiler about the existence of the variable
with the given name and data type.When the variable is declared compiler
automatically allocates the memory for it.
In the definition of a C variable, the compiler allocates some memory and
some value to it. A defined variable will contain some random garbage value
till it is not initialized. Initialization of a variable is the process where the user
assigns some meaningful value to the variable.
Data Types in C
A data type specifies the type of data that a variable can store such as integer, floating,
character, etc.

Basic Data Types The basic data types are integer-based and
floatingpoint based. C language supports both signed and unsigned literals. The
memory size of the basic data types may change according to 32 or 64-bit
operating system.
Int: Integers are entire numbers without any fractional or decimal parts, and the int data
type is used to represent them. It is frequently applied to variables that include values, such
as counts, indices, or other numerical numbers. The int data type may represent both
positive and negative numbers because it is signed by default. An int takes up 4 bytes of
memory on most devices, allowing it to store values between around -2 billion and +2 billion.
Char: Individual characters are represented by the char data type. Typically used to hold
ASCII or UTF-8 encoding scheme characters, such as letters, numbers, symbols, or
commas. There are 256 characters that can be represented by a single char, which takes up
one byte of memory. Characters such as 'A', 'b', '5', or '$' are enclosed in single quotes.
Float: To represent integers, use the floating data type. Floating numbers can be used
to represent fractional units or numbers with decimal places.

The float type is usually used for variables that require very good precision but may not
be very precise. It can store values with an accuracy of about 6 decimal places and a
range of about 3.4 x 1038 in 4 bytes of memory.
Double: Use two data types to represent two floating integers. When additional
precision is needed, such as in scientific calculations or financial applications, it provides
greater accuracy compared to float.

Double type, which uses 8 bytes of memory and has an accuracy of about 15 decimal
places, yields larger values. C treats floating point numbers as doubles by default if no
explicit type is supplied.

1. int age = 25;


2. char grade = 'A';
3. float temperature = 98.6;
4. double pi = 3.14159265359;

In the example above, we declare four variables: an int variable for the person's age, a
char variable for the student's grade, a float variable for the temperature reading, and
two variables for the number pi.

Derived Data Type Beyond the fundamental data types, C also supports
derived data types, including arrays, pointers, structures, and unions. These
data types give programmers the ability to handle heterogeneous data, directly
modify memory, and build complicated data structures.

Array: An array, a derived data type, lets you store a sequence of fixed-size elements
of the same type. It provides a mechanism for joining multiple targets of the same data
under the same name.

The index is used to access the elements of the array, with a 0 index for the first entry.
The size of the array is fixed at declaration time and cannot be changed during program
execution. The array components are placed in adjacent memory regions.
Here is an example of declaring and utilizing an array:

#include <stdio.h>

int main() { int numbers[5]; // Declares an integer array with a size


of 5 elements

// Assign values to the array elements


numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;

// Display the values stored in the array


printf("Values in the array: ");
for (int i = 0; i < 5; i++) {
printf("%d ", numbers[i]);
}
printf("\n");

return 0;
}

Output:
Values in the array: 10 20 30 40 50

Pointer:

A pointer is a derived data type that keeps track of another data type's memory address.
When a pointer is declared, the data type it refers to is stated first, and then the
variable name is preceded by an asterisk (*).

You can have incorrect access and change the value of variable using pointers by
specifying the memory address of the variable. Pointers are commonly used in tasks such
as function pointers, data structures, and dynamic memory allocation.

Here is an example of declaring and employing a pointer:


#include <stdio.h>

int main() { int num = 42; // An integer variable


int *ptr; // Declares a pointer to an integer

ptr = # // Assigns the address of 'num' to the pointer

// Accessing the value of 'num' using the pointer printf("Value


of num: %d\n", *ptr);
return 0;
}

Here is an example of declaring and utilizing an array:

1. #include <stdio.h>
2.
3. int main() {
4. int numbers[5]; // Declares an integer array with a size of 5 elements
5.
6. // Assign values to the array elements
7. numbers[0] = 10;
8. numbers[1] = 20;
9. numbers[2] = 30;
10. numbers[3] = 40; 11. numbers[4] = 50;
12.
13. // Display the values stored in the array
14. printf("Values in the array: ");
15. for (int i = 0; i < 5; i++) {
16. printf("%d ", numbers[i]);
17. }
18. printf("\n");
19.
20. return 0;
21. }

Output:
Values in the array: 10 20 30 40 50
Pointer:
A pointer is a derived data type that keeps track of another data type's memory address.
When a pointer is declared, the data type it refers to is stated first, and then the
variable name is preceded by an asterisk (*).

You can have incorrect access and change the value of variable using pointers by
specifying the memory address of the variable. Pointers are commonly used in tasks such
as function pointers, data structures, and dynamic memory allocation.

Here is an example of declaring and employing a pointer:

#include <stdio.h>
int main() {
int num = 42; // An integer variable
int *ptr; // Declares a pointer to an integer
ptr = # // Assigns the address
of 'num' to the pointer

// Accessing the value of 'num' using the


pointer
printf("Value of num: %d\n", *ptr);
return 0;
}

Output:
Integer Value: 42
Float Value: 3.14

Enumeration Data Type


A set of named constants or enumerators that represent a collection of connected values
can be defined in C using the enumeration data type (enum). Enumerations give you
the means to give names that make sense to a group of integral values, which makes your
code easier to read and maintain.

Here is an example of how to define and use an enumeration in C:

1. #include <stdio.h>
2.
3. // Define an enumeration for days of the
week
4. enum DaysOfWeek {
5. Monday,
6. Tuesday,
7. Wednesday,
8. Thursday,
9. Friday,
10. Saturday,
11. Sunday
12. };
13. int main() {
14. // Declare a variable of type
enum DaysOfWeek
15. enum DaysOfWeek today;
17.
18. // Assign a value from the enumeration
19. today = Wednesday;
20.
21. // Accessing the enumeration value
22. printf("Today is %d\n", today);
23.
24. return 0;
25. }
Output:
Today is 2

Void Data Type


The void data type in the C language is used to denote the lack of a particular type.
Function return types, function parameters, and pointers are three situations where it
is frequently utilized.

Conclusion: As a result, data types are essential in the C programming language


because they define the kinds of information that variables can hold. They provide the
data's size and format, enabling the compiler to allot memory and carry out the necessary
actions. Data types supported by C include void, enumeration, derived, and basic types.
In addition to floating-point types like float and double, basic data types in C also include
integer-based kinds like int, char, and short. These forms can be signed or unsigned,
and they fluctuate in size and range. To create dependable and efficient code, it is crucial
to comprehend the memory size and scope of these types.

Tokens in C
Tokens in C is the most important element to be used in creating a program in C. We can
define the token as the smallest individual element in C. For `example, we cannot create a
sentence without using words; similarly, we cannot create a program in C without using
tokens in C. Therefore, we can say that tokens in C is the building block or the basic
component for creating a program in C language.

Classification of tokens in C

Tokens in C language can be divided into the following categories:

• Keywords in C
• Identifiers in C
• Strings in C
• Operators in C
• Constant in C
• Special Characters inC
Keywords in C
Keywords in C are reserved words that have predefined meanings and are
part of the C language syntax. These keywords cannot be used as variable
names, function names, or any other identifiers within the program except
for their intended purpose. They are used to define the structure flow and
behavior of a C program.

The compiler recognizes a defined set of keywords in the C programming


language. These keywords have specialized purposes and play critical roles
in establishing the logic and behavior of a program.

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


auto break case char const continue default do

double else enum extern float for goto if

int long register return short signed sizeof static

struct switch typedef union unsigned void volatile while

C Identifiers
C identifiers represent the name in the C program, for example, variables, functions, arrays,
structures, unions, labels, etc. An identifier can be composed of letters such as uppercase,
lowercase letters, underscore, digits, but the starting letter should be either an alphabet
or an underscore. If the identifier is not used in the external linkage, then it is called as an
internal identifier. If the identifier is used in the external linkage, then it is called as an
external identifier.

We can say that an identifier is a collection of alphanumeric characters that begins either
with an alphabetical character or an underscore, which are used to represent various
programming elements such as variables, functions, arrays, structures, unions, labels, etc.
There are 52 alphabetical characters (uppercase and lowercase), underscore character, and
ten numerical digits (0-9) that represent the identifiers. There is a total of 63
alphanumerical characters that represent the identifiers.
Rules for constructing C identifiers o The first character of an identifier
should be either an alphabet or an underscore, and then it can be followed
by any of the character, digit, or underscore.
o It should not begin with any numerical digit. o In identifiers, both
uppercase and lowercase letters are distinct. Therefore, we can say that
identifiers are case sensitive.
o Commas or blank spaces cannot be specified within an identifier.
o Keywords cannot be represented as an identifier.
o The length of the identifiers should not be more than 31 characters. o
Identifiers should be written in such a way that it is meaningful, short,
and easy to read.
Keyword Identifier

Keyword is a pre-defined word. The identifier is a user-defined word

It must be written in a lowercase letter. It can be written in both lowercase and uppercase letters.

Its meaning is pre-defined in the c compiler. Its meaning is not defined in the c compiler.

It is a combination of alphabetical characters. It is a combination of alphanumeric characters.

It does not contain the underscore character. It can contain the underscore character.
Operators : Operators means special symbol, are used to perform operations on
variables and values.

C divides the operators into the following groups:

1. Binary Operator
2. Unary Operator
3. Ternary Operator

1.Binary Operators:

In the binary operators included five types of operators

1. Arithmetic Operators
2. Relational /Comparison Operators
3. Logical Operators
4. Bitwise Operators
5. Assignment Operators

Arithmetic Operators
Arithmetic operators are used to perform common mathematical operations.
H

Operator Name Description Example

+ Addition Adds x+y


together
two values

- Subtraction Subtracts x-y


one value
from
another

2.

* Multiplication Multiplies x*y


two values

/ Division Divides one x/y


value by
another

% Modulus Returns the x%y


division
remainder

Comparison Operators :

Comparison operators are used to compare two values (or


variables). This is important in programming, because it helps us
to find answers and make decisions.
The return value of a comparison is either 1 or 0, which means
true (1) or false (0). These values are known as Boolean values

Operator Name Example Description

== Equal x == y Returns 1 if
to the values
are equal

!= Not x != y Returns 1 if
equal the values
are not
equal

> Greater x>y Returns 1 if


than the first
value is
greater than
the second
value

< Less x<y Returns 1 if


than the first
value is less
than the
second
value
>= Greater x >= y Returns 1 if
than or the first
equal value is
to greater
than, or
equal to, the
second
value

<= Less x <= y Returns 1 if


than or the first
equal value is less
to than, or
equal to, the
second
value

3.logical Operators

You can also test for true or false values with logical operators.

Logical operators are used to determine the logic between


variables or values:

Operator Name Example Description


&& Logical and x < 5 && x < 10 Returns 1 if both statements are true

|| Logical or x < 5 || x < 4 Returns 1 if one of the statements is true

! Logical not !(x < 5 && x < Reverse the result, returns 0 if the result is
10) 1

4.Bitwise Operators :
The Bitwise operators are used to perform bit-level operations on the
operands. The operators are first converted to bit-level and then the
calculation is performed on the operands. Mathematical operations such as
addition, subtraction, multiplication, etc. can be performed at the bit level for
faster processing.
There are 6 bitwise operators in C:

Operator Meaning of operator

& Bitwise AND operator

| Bitwise OR operator

^ Bitwise exclusive OR operator

~ One's complement operator (unary operator)

<< Left shift operator

>> Right shift operator

5.Assignment operators

Assignment operators are used to assign values to variables.

A list of all assignment operators:

Operator Example Same As


= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
&= x &= 3 x=x&3
|= x |= 3 x=x|3
^= x ^= 3 x=x^3
>>= x >>= 3 x = x >> 3
<<= x <<= 3 x = x << 3

2. Unary operators :
Operators that work on single operand. This includes :

++ Increment Increases the value of a variable by 1 Ex: ++x

-- Decrement Decreases the value of a variable by 1 --x

3.Ternary Operators :
Conditional Operator ( ? : )

The conditional operator is the only ternary operator in C+.

Here, Expression1 is the condition to be evaluated. If the


condition(Expression1) is True then we will execute and return
the result of Expression2 otherwise if the condition(Expression1)
is false then we will execute and return the result of Expression3.

We may replace the use of if..else statements with conditional


operators.

Syntax: Operand1 ? operand2 : operand3;


conditional statements :
The conditional statements (also known as decision control structures)
such as if, if else, switch, etc. are used for decision-making purposes in C
programs.
They are also known as Decision-Making Statements and are used to
evaluate one or more conditions and make the decision whether to execute
a set of statements or not. These decision-making statements in
programming languages decide the direction of the flow of program
execution.
Types of Conditional Statements in C

1. if Statement
2. if-else Statement
3. Nested if Statement
4. if-else-if Ladder
5. switch Statement
6. Conditional Operator
7. Jump Statements:
• break
• continue
• goto
• return

Switch case statement evaluates a given expression and based on the


evaluated value(matching a certain condition), it executes the statements
associated with it. Basically, it is used to perform different actions based on
different conditions(cases).
• Switch case statements follow a selection-control mechanism and
allow a value to change control of execution.
• They are a substitute for long if statements that compare a variable
to several integral values.
• The switch statement is a multiway branch statement. It provides
an easy way to dispatch execution to different parts of code based
on the value of the expression.
In C, the switch case statement is used for executing one condition from
multiple conditions. It is similar to an if-else-if ladder.
The switch statement consists of conditional-based cases and a default
case.
Syntax of switch Statement in C
switch(expression)
{
case value1: statement_1;
break;
case value2: statement_2;
break;
.
.
.
case value_n: statement_n;
break;

default: default_statement;
}
For Ex: #include <stdio.h>

/* C program to Demonstrate returning of day based


numeric*/

void main()

// switch variable

int month;

printf("Enter the number of month:\n");

scanf("%d",&month);

// switch statement

switch (month) {

case 1:

printf("January");

break;

case 2:

printf("February");

break;

case 3:

printf("march");

break;

default:
printf("Invalid input! Please enter month number
between 1-12.");

break;

Break in switch case


This keyword is used to stop the execution inside a switch block. It helps to
terminate the switch block and break out of it. When a break statement is
reached, the switch terminates, and the flow of control jumps to the next
line following the switch statement.
The break statement is optional. If omitted, execution will continue on into
the next case. The flow of control will fall through to subsequent cases until
a break is reached.
C Loops
The looping can be defined as repeating the same process multiple times
until a specific condition satisfies. There are three types of loops used in the
C language. In this part of the tutorial, we are going to learn all the aspects
of C loops.

Why use loops in C language?

The looping simplifies the complex problems into the easy ones. It enables
us to alter the flow of the program so that instead of writing the same code
again and again, we can repeat the same code for a finite number of times.
For example, if we need to print the first 10 natural numbers then, instead of
using the printf statement 10 times, we can print inside a loop which runs up
to 10 iterations.

Advantage of loops in C

1) It provides code reusability.


2) Using loops, we do not need to write the same code again and again.

3) Using loops, we can traverse over the elements of data structures (array or linked lists).

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

A "do-while" loop is a form of a loop in C that executes the code block first,
followed by the condition. If the condition is true, the loop continues to run;
else, it stops. However, whether the condition is originally true, it ensures
that the code block is performed at least once.

do while loop syntax

The syntax of the C language do-while loop is given below:

do{
//code to be executed
}while(condition);

The components are divided into the following:

o The do keyword marks the beginning of the Loop.


o The code block within curly braces {} is the body of the loop, which
contains the code you want to repeat.
o The while keyword is followed by a condition enclosed in parentheses
(). After the code block has been run, this condition is verified. If the
condition is true, the loop continues else, the loop ends.

Example:
#include <stdio.h>
#include <string.h>
1. int main() {
char password[] = "secret";
2. char input[20];
3. do {
4. printf("Enter the password: ");
5. scanf("%s", input);
} while (strcmp(input, password) != 0);
6. printf("Access granted!\n");
7. return 0;
8. }

Output
Enter the password: 123
Enter the password: abc
Enter the password: secret
Access Granted!

2.while loop in C

While loop is also known as a pre-tested loop. In general, a while loop allows
a part of the code to be executed multiple times depending upon a given
boolean condition. It can be viewed as a repeating if statement. The while
loop is mostly used in the case where the number of iterations is not known
in advance.

Syntax of while loop in C language

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

1. while(condition){
2. //code to be executed
}
Flowchart of while loop in C

Example of the while loop in C language


Let's see the simple program of while loop that prints table of 1.

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. }
Output
1
2
3
4
5
6
7
8
9
10

for loop in C

The for loop in C language is used to iterate the statements or a part of the
program several times. It is frequently used to traverse the data structures like the
array and linked list.

Syntax of for loop in C


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

1. for(Expression 1; Expression 2; Expression 3){


2. //code to be executed
3. }

EX: C Program: Print table for the given number using C for
loop
1. #include<stdio.h>
2. int main(){
3. int i=1,number=0;
4. printf("Enter a number: ");
5. scanf("%d",&number);
6. for(i=1;i<=10;i++){
7. printf("%d \n",(number*i));
8. }
9. return 0;
10. }

Output

Enter a number: 2
2
4
6
8
10
12
14
16
18
20

C Program: Print table for the given number using C for loop
Flowchart of for loop in C
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.

Initialization of Arrays

• Arrays can be initialized during declaration or after declaration.


• Initialization assigns meaningful values to array elements.
• Ways to initialize arrays:
1. With Declaration and Initialization:

int arr[] = {10, 20, 30, 40, 50}; // Initializes


the array during declaration

Without Declaring Size (Compiler Deduces Size):

int arr_auto[] = {1, 2, 3, 4, 5}; // Compiler


deduces size (here, 5)

After Declaration (Using Loops):

float arr_float[5];
for (int i = 0; i < 5; i++) {
arr_float[i] = i * 2.5;
}
Types of Array :
1. One-Dimensional Arrays (1D Arrays)
The array is declared with one value of size in square brackets,
it is called one dimensional array. In a one dimensional array,
each element is identified by its index or subscript.

• A one-dimensional array (also known as a 1D array) consists of a


single row of elements.
• Elements are accessed using a single index (position).
• Syntax for declaring a 1D array:
• data_type array_name[size];

Example:

int arr_int[5]; // An integer array with 5 elements


char arr_char[5]; // A character array with 5 elements

2. Two-dimensional Arrays (2D)

A two-dimensional array is like a table or a matrix. The


elements can be considered to be logically arranged in rows
and columns. Hence, the location of any element is
characterized by its row number and column number. Both row
and column index start from 0.

• Syntax for declaring a 2D array:


• data_type array_name[row_size][column_size];

The following statement declares and initializes a


two−dimensional array −

3. int arr[3][5] = {1,2,3,4,5, 10,20,30,40,50, 5,10,15,20,25};


3.Multidimensional Arrays

Multi−dimensional arrays can be termed as nested arrays. In such a


case, each element in the outer array is an array itself. Such type of
nesting can be up to any level.

Multidimensional arrays have more than one dimension (rows and


columns).

• Common examples include 2D arrays (matrices) and 3D arrays


(cubes).
• Elements are accessed using multiple indices.
• Depending on the nesting level, the multi−dimensional array is
declared as follows −
• type name[size1][size2]...[sizeN];
• For example, the following declaration creates a three
dimensional integer array −
• int threedim[3][3][3];

A 3D (three−dimensional) array is a array of 2D arrays. Such an


array is declared with three subscripts. Imagine the students
appearing for an exam are seated in five halls, each hall having
twenty rows of desks, and each row has 5 tables. Such an
arrangement is represented by a three dimensional array such as −

Students[hall][row][column]

To locate each student, you need to have three indices, hall


number, row and column of his table in the hall.

The following program stores numbers in a 3 X 3 X 3 array −

Example
#include<stdio.h>

int main(){
int i, j, k;
int arr[3][3][3]= {
{
{11, 12, 13},
{14, 15, 16},
{17, 18, 19}
},
{
{21, 22, 23},
{24, 25, 26},
{27, 28, 29}
},
{
{31, 32, 33},
{34, 35, 36},
{37, 38, 39}
},
};

printf("Printing 3D Array Elements\n");

for(i=0;i<3;i++) {
for(j=0;j<3;j++){
for(k=0;k<3;k++){
printf("%4d",arr[i][j][k]);
}
printf("\n");
}
printf("\n");
}
return 0;

Output:

Printing 3D Array Elements


11 12 13
14 15 16
17 18 19

21 22 23
24 25 26
27 28 29

31 32 33
34 35 36
37 38 39

A String in C programming is a sequence of characters terminated with a


null character ‘\0’. The C String is stored as an array of characters. The
difference between a character array and a C string is that the string in C is
terminated with a unique character ‘\0’.
C String Declaration Syntax
Declaring a string in C is as simple as declaring a one-dimensional array.
Below is the basic syntax for declaring a string.
char string_name[size];
In the above syntax string_name is any name given to the string variable
and size is used to define the length of the string, i.e. the number of
characters strings will store.
There is an extra terminating character which is the Null character (‘\0’)
used to indicate the termination of a string that differs strings from
normal character arrays.
C String Initialization
A string in C can be initialized in different ways. We will explain this with
the help of an example. Below are the examples to declare a string with the
name str and initialize it with “GeeksforGeeks”.
We can initialize a C string in 4 different ways which are as follows:
1. Assigning a String Literal without Size
String literals can be assigned without size. Here, the name of the string str
acts as a pointer because it is an array.
char str[] = "GeeksforGeeks";
2. Assigning a String Literal with a Predefined Size
String literals can be assigned with a predefined size. But we should always
account for one extra space which will be assigned to the null character. If
we want to store a string of size n then we should always declare a string
with a size equal to or greater than n+1.
char str[50] = "GeeksforGeeks";
3. Assigning Character by Character with Size
We can also assign a string character by character. But we should
remember to set the end character as ‘\0’ which is a null character.
char str[14] = {
'G','e','e','k','s','f','o','r','G','e','e','k','s','\0'};
4. Assigning Character by Character without Size
We can assign character by character without size with the NULL character
at the end. The size of the string is determined by the compiler
automatically.
char str[] = {
'G','e','e','k','s','f','o','r','G','e','e','k','s','\0'};
Note: When a Sequence of characters enclosed in the double quotation
marks is encountered by the compiler, a null character ‘\0’ is appended at
the end of the string by default.
Let us now look at a sample program to get a clear understanding of
declaring, and initializing a string in C, and also how to print a string with its
size.
C String Example
// C program to illustrate strings

#include <stdio.h>
#include <string.h>

int main()
{
// declare and initialize string
char str[] = "Geeks";

// print string
printf("%s\n", str);

int length = 0;
length = strlen(str);

// displaying the length of string


printf("Length of string str is %d", length);

return 0;
}

Output
Geeks
Length of string str is 5

We can see in the above program that strings can be printed using normal
printf statements just like we print any other variable. Unlike arrays, we do
not need to print a string, character by character.

What is a Pointer in C?
A pointer is defined as a derived data type that can store the address of
other C variables or a memory location. We can access and manipulate the
data stored in that memory location using pointers.
As the pointers in C store the memory addresses, their size is independent
of the type of data they are pointing to. This size of pointers in C only
depends on the system architecture.
Syntax of C Pointers
The syntax of pointers is similar to the variable declaration in C, but we use
the ( * ) dereferencing operator in the pointer declaration.
datatype * ptr;

where
• ptr is the name of the pointer.
• datatype is the type of data it is pointing to.
The above syntax is used to define a pointer to a variable. We can also
define pointers to functions, structures, etc.
How to Use Pointers?
The use of pointers in C can be divided into three steps:
1. Pointer Declaration
2. Pointer Initialization
3. Pointer Dereferencing
1. Pointer Declaration
In pointer declaration, we only declare the pointer but do not initialize it. To
declare a pointer, we use the ( * ) dereference operator before its name.
Example
int *ptr;

The pointer declared here will point to some random memory address as it
is not initialized. Such pointers are called wild pointers.
2. Pointer Initialization
Pointer initialization is the process where we assign some initial value to the
pointer variable. We generally use the ( & ) addressof operator to get the
memory address of a variable and then store it in the pointer variable.
Example
int var = 10;
int * ptr;
ptr = &var;

We can also declare and initialize the pointer in a single step. This method is
called pointer definition as the pointer is declared and initialized at the same time.
Example
int *ptr = &var;
Note: It is recommended that the pointers should always be initialized to some value
before starting using it. Otherwise, it may lead to number of errors.
3. Pointer Dereferencing
Dereferencing a pointer is the process of accessing the value stored in the memory
address specified in the pointer. We use the same ( * ) dereferencing operator that
we used in the pointer declaration.

Uses of Pointers in C
The C pointer is a very powerful tool that is widely used in C programming
to perform various useful operations. It is used to achieve the following
functionalities in C:
1. Pass Arguments by Reference
2. Accessing Array Elements
3. Return Multiple Values from Function
4. Dynamic Memory Allocation
5. Implementing Data Structures
6. In System-Level Programming where memory addresses are
useful.
7. In locating the exact value at some memory location.
8. To avoid compiler confusion for the same variable name.
9. To use in Control Tables.
Advantages of Pointers
• Following are Pointers are used for dynamic memory allocation and
deallocation.
• An Array or a structure can be accessed efficiently with pointers
• Pointers are useful for accessing memory locations.
• Pointers are used to form complex data structures such as linked
lists, graphs, trees, etc.
• Pointers reduce the length of the program and its execution time as
well.
Disadvantages of Pointers
Pointers are vulnerable to errors and have following disadvantages:
• Memory corruption can occur if an incorrect value is provided to
pointers.
• Pointers are a little bit complex to understand.
• Pointers are majorly responsible for memory leaks in C.
• Pointers are comparatively slower than variables in C.
• Uninitialized pointers might cause a segmentation fault.

Conclusion
In conclusion, pointers in C are very capable tools and provide C language
with its distinguishing features, such as low-level memory access,
referencing, etc. But as powerful as they are, they should be used with
responsibility as they are one of the most vulnerable parts of the language.
the major advantages of pointers in C:

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.

Syntax:

1. struct structure_name
2. {
3. data_type member1;
4. data_type member2;
5. .
6. .
7. data_type memeberN;
8. };

Initialize struct array


Let use define a struct type named as book as follows −

struct book{
char title[10];
double price;
int pages;
};

During the program, you can declare an array and initialize it by giving the
values of each element inside curly brackets. Each element in the struct
array is a struct value itself. Hence, we have the nested curly brackets as
shown below −

struct book b[3] ={


{"Learn C", 650.50, 325}, {"C Pointers", 175, 225}, {"C Pearls", 250, 250}
};

How does the compiler allocate the memory? Since we have an array of
three elements, of struct whose size is 32 bytes, the array occupies 32X3
bytes. Each block of 32 bytes will accommodate a title, price and pages
element.

Declare struct array


You can also declare an empty struct array. Afterwards, you can
either read the data in it with scanf() statements, or assign value to
each element as shown below −

struct book b[3];


strcpy(b[0].title, " Learn C ");
b[0].price = 650.50;
b[0].pages=325;

strcpy(b[1].title, " C Pointers ");


b[1].price = 175;
b[1].pages=225;

strcpy(b[2].title, "C Pearls ");


b[2].price = 250;250
b[2].pages=325;

We can also accept data from the user to fill the array

Read struct array


In the following code, a for loop is employed to accept inputs for the title,
price and pages elements of each struct element of the array.

Example
#include <stdio.h>
#include <string.h>
struct book{
char title[10];
double price;
int pages;
};
int main (){
struct book b[3];
strcpy(b[0].title, " Learn C ");
b[0].price = 650.50;
b[0].pages=325;
strcpy(b[1].title, " C Pointers ");
b[1].price = 175;
b[1].pages=225;
strcpy(b[2].title, "C Pearls ");
b[2].price = 250;
b[2].pages=325;
printf("\nList of books\n");
for (int i=0; i<3; i++){
printf("Title: %s Price: %7.2lf No of Pages: %d\n", b[i].title, b[i].price,
b[i].pages);
}
return 0;
}
Output
List of books
Title: Learn C Price: 650.50 No of Pages: 325
Title: C Pointers Price: 175.00 No of Pages: 225
Title: C Pearls Price: 250.00 No of Pages: 325

Union in C

Union can be defined as a user-defined data type which is a collection of


different variables of different data types in the same memory location. The
union can also be defined as many members, but only one member can
contain a value at a particular point in time.

Union is a user-defined data type, but unlike structures, they share the same
memory location.

For Example:

1. struct abc
2. {
3. int a;
4. char b;
5. }

The above code is the user-defined structure that consists of two members, i.e., 'a' of
type int and 'b' of type character. When we check the addresses of 'a' and 'b', we found
that their addresses are different. Therefore, we conclude that the members in the
structure do not share the same memory location.

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.

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

The content of the file will be printed.

#include;
void main( )
{
FILE *fp; // file pointer
char ch;
fp = fopen("file_handle.c","r");
while ( 1 )
{
ch = fgetc ( fp ); //Each character of the file is read and stored in
the character file.
if ( ch == EOF )
break;
printf("%c",ch);
}
fclose (fp );
}

Closing File: fclose()


The fclose() function is used to close a file. The file must be closed after performing all the
operations on it. The syntax of fclose() function is given below:

int fclose( FILE *fp );


A function in C is a set of statements that when called perform some
specific task. It is the basic building block of a C program that provides
modularity and code reusability. The programming statements of a function
are enclosed within { } braces, having certain meanings and performing
certain operations. They are also called subroutines or procedures in other
languages.
In this article, we will learn about functions, function definition. declaration,
arguments and parameters, return values, and many more.

Syntax of Functions in C
The syntax of function can be divided into 3 aspects:
1. Function Declaration
2. Function Definition
3. Function Calls
Function Declarations
In a function declaration, we must provide the function name, its return type,
and the number and type of its parameters. A function declaration tells the
compiler that there is a function with the given name defined somewhere
else in the program.

Syntax

return_type name_of_the_function (parameter_1, parameter_2);


The parameter name is not mandatory while declaring functions. We can
also declare the function without using the name of the data variables.

Example

int sum(int a, int b);


int sum(int , int);
Function Definition
The function definition consists of actual statements which are executed
when the function is called (i.e. when the program control comes to the
function).
A C function is generally defined and declared in a single step because the
function definition always starts with the function declaration so we do not
need to declare it explicitly. The below example serves as both a function
definition and a declaration.
return_type function_name (para1_type para1_name, para2_type
para2_name)
{
// body of the function
}
Function Call
A function call is a statement that instructs the compiler to execute the
function. We use the function name and parameters in the function call.
In the below example, the first sum function is called and 10,30 are passed
to the sum function. After the function call sum of a and b is returned and
control is also returned back to the main function of the program.

Example of C Function

// C program to show function

// call and definition

#include <stdio.h>

// Function that takes two parameters

// a and b as inputs and returns

// their sum

int sum(int a, int b)

return a + b;

// Driver code

int main()

{
// Calling sum function and

// storing its value in add variable

int add = sum(10, 30);

printf("Sum is: %d", add);

return 0;

Output
Sum is: 40

As we noticed, we have not used explicit function declaration. We simply


defined and called the function.

Function Return Type

Function return type tells what type of value is returned after all function is
executed. When we don’t want to return a value, we can use the void data
type.
Example:
int func(parameter_1,parameter_2);

The above function will return an integer value after running statements
inside the function.
Note: Only one value can be returned from a C function. To return multiple
values, we have to use pointers or structures.

Function Arguments : Function Arguments (also known as Function


Parameters) are te data that is passed to a function.

Example:
int function_name(int var1, int var2);

Conditions of Return Types and Arguments


In C programming language, functions can be called either with or without
arguments and might return values. They may or might not return values to
the calling functions.
1. Function with no arguments and no return value
2. Function with no arguments and with return value
3. Function with argument and with no return value
4. Function with arguments and with return value
Types of Functions
There are two types of functions in C:
1. Library Functions
2. User Defined Functions

1. Library Function

A library function is also referred to as a “built-in function”. A compiler


package already exists that contains these functions, each of which has a
specific meaning and is included in the package. Built-in functions have the
advantage of being directly usable without being defined, whereas user-
defined functions must be declared and defined before being used.
For Example:
pow(), sqrt(), strcmp(), strcpy() etc.
Advantages of C library functions
C Library functions are easy to use and optimized for better

performance.
• C library functions save a lot of time i.e, function development time.
• C library functions are convenient as they always work.
Example:

// C program to implement

// the above approach

#include <math.h>

#include <stdio.h>
// Driver code

int main()

double Number;

Number = 49;

// Computing the square root with

// the help of predefined C

// library function

double squareRoot = sqrt(Number);

printf("The Square root of %.2lf = %.2lf",

Number, squareRoot);

return 0;

Output
The Square root of 49.00 = 7.00

2. User Defined Function

Functions that the programmer creates are known as User-Defined functions


or “tailor-made functions”. User-defined functions can be improved and
modified according to the need of the programmer. Whenever we write a
function that is case-specific and is not defined in any header file, we need to
declare and define our own functions according to the syntax.
Advantages of User-Defined Functions
Changeable functions can be modified as per need.

• The Code of these functions is reusable in other programs.
• These functions are easy to understand, debug and maintain.
Example:

// C program to show

// user-defined functions

#include <stdio.h>

int sum(int a, int b)

return a + b;

// Driver code

int main()

int a = 30, b = 40;

// function call

int res = sum(a, b);


printf("Sum is: %d", res);

return 0;

Output
Sum is: 70

Passing Parameters to Functions


The data passed when the function is being invoked is known as the Actual
parameters. In the below program, 10 and 30 are known as actual
parameters. Formal Parameters are the variable and the data type as
mentioned in the function declaration. In the below program, a and b are
known as formal parameters.

Passing Parameters to Functions

We can pass arguments to the C function in two ways:


1. Pass by Value
2. Pass by Reference
1. Pass by Value
Parameter passing in this method copies values from actual parameters into
formal function parameters. As a result, any changes made inside the
functions do not reflect in the caller’s parameters.
Example:

// C program to show use

// of call by value

#include <stdio.h>

void swap(int var1, int var2)

int temp = var1;

var1 = var2;

var2 = temp;

// Driver code

int main()

int var1 = 3, var2 = 2;

printf("Before swap Value of var1 and var2 is: %d, %d\n",

var1, var2);
swap(var1, var2);

printf("After swap Value of var1 and var2 is: %d, %d",

var1, var2);

return 0;

2. Pass by Reference
The caller’s actual parameters and the function’s actual parameters refer to
the same locations, so any changes made inside the function are reflected in
the caller’s actual parameters.
Example:

// C program to show use of

// call by Reference

#include <stdio.h>

void swap(int *var1, int *var2)

int temp = *var1;

*var1 = *var2;

*var2 = temp;

// Driver code

int main()
{

int var1 = 3, var2 = 2;

printf("Before swap Value of var1 and var2 is: %d, %d\n",

var1, var2);

swap(&var1, &var2);

printf("After swap Value of var1 and var2 is: %d, %d",

var1, var2);

return 0;

Output
Before swap Value of var1 and var2 is: 3, 2
After swap Value of var1 and var2 is: 2, 3

Advantages of Functions in C
Functions in C is a highly useful feature of C with many advantages as
mentioned below:
1. The function can reduce the repetition of the same statements in
the program.
2. The function makes code readable by providing modularity to our
program.
3. There is no fixed number of calling functions it can be called as
many times as you want.
4. The function reduces the size of the program.
5. Once the function is declared you can just use it without thinking
about the internal working of the function.
Disadvantages of Functions in C
The following are the major disadvantages of functions in C:
1. Cannot return multiple values.
2. Memory and time overhead due to stack frame allocation and
transfer of program control.
Conclusion
In this article, we discussed the following points about the function as
mentioned below:
1. The function is the block of code that can be reused as many times
as we want inside a program.
2. To use a function we need to call a function.
3. Function declaration includes function_name, return type, and
parameters.
4. Function definition includes the body of the function.
5. The function is of two types user-defined function and library
function.
6. In function, we can according to two types call by value and call by
reference according to the values passed.

A user-defined function is a type of function in C language that is


defined by the user himself to perform some specific task. It provides code
reusability and modularity to our program. User-defined functions are
different from built-in functions as their working is specified by the user and
no header file is required for their usage.
In this article, we will learn about user-defined function, function
prototype, function definition, function call, and different ways in which
we can pass parameters to a function.
How to use User-Defined Functions in C?
To use a user-defined function, we first have to understand the different
parts of its syntax. The user-defined function in C can be divided into three
parts:
1. Function Prototype
2. Function Definition
3. Function Call
C Function Prototype
A function prototype is also known as a function declaration which specifies
the function’s name, function parameters, and return type. The function
prototype does not contain the body of the function. It is basically used to
inform the compiler about the existence of the user-defined function which
can be used in the later part of the program.

Syntax

return_type function_name (type1 arg1, type2 arg2, ... typeN


argN);

You might also like