0% found this document useful (0 votes)
4 views28 pages

C-Notes by Coding

C NOTES FOR BEGINNERS

Uploaded by

abhijeets082000
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)
4 views28 pages

C-Notes by Coding

C NOTES FOR BEGINNERS

Uploaded by

abhijeets082000
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/ 28

C-Notes by Coding Age

Basics of C programming

Programming Language :
A programming language is a vocabulary and a set of grammatical rules that is used to communicate with a computer.

C Language :
C is a Procedural Programming Language.

A procedural language follows a sequence of statements or commands in order to achieve a desired output.

Entire Program is divided into several smaller programs called procedures or functions which makes it manageable and
easy to understand.

C is a statically typed language, meaning the variables and their data types are recognized during compile time.

Compiling a program :
The code that we write(also known as Source Code) is not directly understandable for the computer since the
computer can understand only 0s and 1s.

Compiling a program, translates the human readable code(source code), into a binary machine code(0s and 1s) which
can be executed by the computer.

To compile a program, we use the command gcc.filename . This creates an executable file (a.exe) for the compiled file.

We need to compile a program every time we make a change to it, so that the change is updated in the executable file
as well.

Running a program(execution) :
The process when a program performs the given task after it has been compiled, is known as running or execution.

To run a program after it has been compiled, we use the command a.exe

Below we have our first code in C language :


Example 1

#include <stdio.h>
int main(){

C-Notes by Coding Age 1


printf("Hello World!");
return 0;
}

Output: Hello world!

Following is the list of what each line means:


#include - preprocessor

<stdio.h> - Header file

(Header file provides us with pre-defined functions that make it easier for us to code in C)
int main(){} - Function

printf("Hello World!”); — Statement that has to be printed.

return 0 - Return value of main function

Semicolon (' ; ') at the end of a line indicates the end of the statement written in that line.

To save a C file, we use the '.c ʼ extension. E.g.: ‘ file.c ʼ . Here, ‘ file.c ʼ is the filename.

Example 2 :

#include <stdio.h>
int main(){
int n = 5;
char b = 's';
return 0;
}

In the above code, we have two lines that are new to us :

First is, int n = 5;

- Here, n is a variable and the word 'int' written right before it, is the datatype of variable n.

- 5 is the value that has been assigned to the variable n.

- This is how we declare a variable in C.

- Assigning value to a variable is called initialization.

second is, char b = 's';

- This statement is similar to the first one. The only difference is that the datatype of variable b is char.

- The value assigned to variable b is 's'(a letter or character).

Variable :
A variable is a name assigned to a memory location, which has been allocated to store the value that has been
assigned to that variable.

In the above example, ‘nʼ and ‘bʼ are two distinct variables.

Data type :
Data type is classification of data.

As the name suggests, data type tells the type of information that can be stored in a given variable.

Data can be classified into any of the following data types in C :

1. int

2. long

3. float

C-Notes by Coding Age 2


4. double

5. char

(These are only the frequently used ones, there are a few more data types in C.)

Data type Size Description Example

int 2 or 4 bytes Stores only an integer int n  1;

long 8 bytes Stores integer but range of values is greater than int data type long k  5;

float 4 bytes Stores decimal numbers. Sufficient for storing up to 6-7 decimal digits float  2.5;

double  3.5;
double 8 bytes Stores decimal numbers. Sufficient for storing up to 15 decimal digits
double  100;

char m = 't';
char 1 bytes Stores a single character/letter/number, within single quotes.
char c = 'm';

Formula to calculate the range of a data type (i.e. the range of values that can be assigned to a
variable depending on its data type ) :
2(n-1) to 2(n-1)

where, n is the number of bits in that data type. (1 byte = 8 bits)


Note: Size and range of a data type may vary depending on the system being used. The sizes
mentioned above are the general ones.

Variable naming rules :


Variable names can consist only of alphabets, numbers, underscore(‘ _ ʼ) or dollar sign(‘ $ ʼ).

No other special character is allowed. Space is also not allowed.

The first character in the variable name must be an alphabet or underscore.

A variable name has to be unique in its scope and has to be declared only once.

The length of a variable name should not be more than 31 characters.

Keywords :
Keywords are the words that have meanings already assigned to them by the language and theyʼre fixed.

They cannot be used as the name of a variable, function etc.

Every keyword has its own job which makes code writing easier for us.

Below is the complete list of all 32 keywords available in C :

int if return auto

long else register void

float break signed unsigned

double continue sizeof const

char default static extern

short do struct goto

switch while typedef enum

case for union volatile

Example 3 :

#include <stdio.h>
int main(){
int v, m, n;
float b;
scanf("%d", &v);// taking input for int data type, storing it in variable 'v'

C-Notes by Coding Age 3


printf("%d", v); // output
scanf(“%f”, &b); // taking input for float data type, storing it in variable 'b'
printf(“%f “, b); // output
scanf("%d%d", &m, &n); // taking multiple inputs, storingthem
//in variable 'm' and 'n'respectively
printf("%d and %d", m, n); // output
return 0;
}

On execution, this code will ask for an integer value as user input. Once we give that, it will print that same number as
output.

Then again it will ask for user input but this time for two integer values. After we input two numbers, it will print those
two numbers separated with ‘andʼ. This how we can place multiple values in the same string.

Things that are new to us in the above code :


scanf( ) → function to take user input

printf( ) → function to give output

(**printf() and scanf() are two of the many functions defined in stdio.h header file)
"%d" , “%f" → format specifier

"&v", &m, &n , &b → address of variable (location where a variable is located in the memory)

Format Specifier :
Tells the compiler about the type of data that needs to be printed or scanned.

It starts with a ' % ' symbol.

Every data type has its own format specifier, below is the list of format specifiers of some commonly used data types:

Data type format specifier

int %d

long %ld

float %f

double %lf

char %c

User Input :
To take input from the user, we use a function called scanf( ) .

Inside this function, we pass :

1. A formatted string (which basically means, format specifier inside double


quotes) e.g. :
“%d”. It tells the system, the type of value that has to be taken as

input.

2. Address of the variable in which we want to store the user input (attaching '&'
to the left of variable name gives the address of that variable) e.g. : &v

3. Both 1) and 2) are separated with a comma. (refer to Example 3)

Output :
To get an output in C, we use printf( ) function.

This function displays what is passed to it inside double quotes.

If we want to print the value of a variable/function then we can :

use the format specifier of the data type of that variable inside double quotes
(formatted string)

and the variable name outside of the double quotes in the right hand side.

C-Notes by Coding Age 4


Both should be separated with a comma.(refer to Example 3).

Binary Number System:


The Binary Number System uses a combination of 0s and 1s in order to represent a value.

Conversion from decimal to binary :

Binary representation of 25 is 11001

Conversion from binary to decimal :

C-Notes by Coding Age 5


Operators :
Operator is a symbol that performs an operation on one or more operands.
For example, the addition of two numbers 2 and 3.

If we write it as 2+3, the ‘+ʼ symbol is an operator and the two numbers 2 and 3 are operands.

Unary Operator:
1) Increment Operator :

Pre Increment -
Placed on the immediate left of the variable.

First it increases the value by 1, then assigns it to the variable.

Post Increment -
Placed on the immediate right of the variable.

C-Notes by Coding Age 6


Keeps the value as it is for the on going expression and increases by 1 in the next expression of the variable.

2) Decrement Operator :
Pre Decrement -
Placed on the immediate left of the variable.

First it decreases the value by 1, then assigns it to the variable.

Post Decrement -
Placed on the immediate right of the variable.

Keeps the value as it is for the on going expression and decreases by 1 in the next expression of the variable
Example 4 :

#include <stdio.h>
int main(){
int a = 4, b = 10;
int z = ++a; //Pre Increment
printf("%d ", z); // Output is 5 (increased immediate
ly)
int y = b++; //Post Increment
printf("%d ", y);
// Output is 10 (did not increase in the current expression)
y = b; //now increased by 1
printf("%d ", y); // Output is 11
//-------------------------Same goes for Decrement Operator,
it decreases by 1
int c = 21, d = 7;
int x = --c; //Pre Decrement
printf("%d ", x); // Output is 20 (decreased immediatel
y)
int w = d--; //Post decrement
printf("%d ", w); // Output is 7 (did not decrease in t
he current expression)
w = d;//now decreased by 1
printf("%d ", w); // Output is 6
return 0;
}

Binary Operator:
1) Arithmetic Operator( +, - , *, /, %) :
Performs basic mathematical operations.

Gives numeric value as an output.


Example 5 :

#include <stdio.h>
int main(){
int a = 3;
int b = 2;
printf(“%d”, (a+b)); // Output is 5
return 0;
}

C-Notes by Coding Age 7


2) Relational Operator(<, <=, >, >=, == , !=) :
Compares the operands.

Gives output as either true(1) or false(0).


Example 6:

#include <stdio.h>
int main(){
int a = 3;
int b = 5;
printf(“%d”, a<b); //Output is 1 (true)
return 0;
}

3) Logical Operator (&&, ||, ! ) :


Logical Operator, evaluates the result of a statement (or condition) consisting of a relational operator.

i) && (logical AND)


returns true, only when both conditions(operands) are true.

ii) || (logical OR)


returns false, only when both conditions(operands) are false.

iii) ! (logical NOT)


return true when the condition is false and false when it is true
Example 7 :

#include <stdio.h>
int main(){
int a = 5, b= 7, c = 9;
printf(“%d”, ( (a<b) && (a>=c) ) );//Output is 0, since o
nly first condition is true
printf(“%d”, ( (a<b) || (a>=c) ) );//Output is 1, since o
nly second condition is false
print(“%d”, !(a == 5)); // Output is 0, since the conditi
on is true
return 0;
}

4) Bitwise Operator(&, |, <<, >>, ~, ^) :


Performs operation on bit-level.

The operands are first converted into bits, after that operation is performed on the converted operands.

i) & (bitwise AND)


returns 1 only if both bits are 1.
Example 8:

#include <stdio.h>
int main(){
int a = 10; //1010
int b = 2; //0010
printf(“%d”, a&b); //Output is 2 which is 0010 in binary

C-Notes by Coding Age 8


return 0;
}

ii) | (bitwise OR)


returns 0 only if both bits are 0.
Example 9 :

#include <stdio.h>
int main(){
int a = 10; //1010
int b = 2; //0010
printf(“%d”, a|b); //Output is 10 which is 1010 in binar
y
return 0;
}

iii) << (left - shift)


shifts the bits of the left operand towards left by the number specified by the right operand and appends equal number
of zeroes to the right
Example 10:

#include <stdio.h>
int main(){
int a = 10; //001010
printf(“%d”, a<<2); //Output is 40 which is 101000 in binary
return 0;
}

iv) >> (right - shift)


shifts the bits of the left operand towards right by the number specified by the right operand and appends an equal
number of zeroes to the left.
Example 11:

#include <stdio.h>
int main(){
int a = 10; //1010
int b = 2; //0010
printf(“%d”, a>>b); //Output is 2 which is 0010 in binar
y
return 0;
}

v) ^ (bitwise XOR)
returns 0 if both bits are same
Example 12:

#include <stdio.h>
int main(){
int a = 10; //1010
int b = 2; //0010
printf(“%d”, a^b); //Output is 8 which is 1000 in binary
return 0;
}

C-Notes by Coding Age 9


Example 13:

#include <stdio.h>
int main(){
int a = 11;
print("%d",
return 0;
}

5) Assignment Operator(=, +=, -=, *=, /=, %=) :


Assigns the value of one operand or operation to the other operand

Operator Description

= c = a assigns the value of a to c

+= c += a is equivalent to c = c + a

-= c -= a is equivalent to c = c - a

*= c *= a is equivalent to c = c * a

/= c /= a is equivalent to c = c / a

% c % a is equivalent to c = c % a

Example 14:

#include <stdio.h>
int main(){
int x = 20;
x += 10;
printf("x+10 = %d", x);//now x is 30

x -= 10;
printf("\nx-10 = %d", x);//now x is 20

x *= 10;
printf("\nx*10 = %d", x);//now x is 200

x /= 10;
printf("\nx/10 = %d", x);//now x is 20

x %= 10;
printf("\nx%%10 = %d", x);//now x is 0
return 0;
}

Ternary Operator:
1) Conditional Operator( ? : ):
As the name suggests, this operator depends upon whether the given condition is true or false.

The conditional statement is written to the left of the question mark.

At the right of the question mark, we place the statement that needs to be executed if the condition is true.

Then after a semi colon, we write the statement that is executed if the condition is false.

Condition Operator can be used to shorten the if else code blocks.


Syntax :

C-Notes by Coding Age 10


Example 15:

#include <stdio.h>
int main(){
int num = 13;
(num % 2 == 0)? printf("The number is even") : printf("Th
e number is odd");
return 0;
}
//Since the condition is false, the output is "The number is odd"

Conditional statements :
The purpose of a condition is to help us make decisions based on the result.

We can make required conditions using the operators or their combinations. Relational and Logical operators among all
are the most important operators for making conditions since both of them return a true(1) or false(0) value.

To instruct the machine with a task to perform if the specified condition is true/false, we use conditional statements.

Following are the conditional statements used in C:


1. If → Used to specify a block of code, that needs to be executed only if the
specified condition is true.

2. else→ Used together with ‘if condition’, it specifies the block of code that
needs to be executed when the ‘if condition’ is false.

3. Nested if - else → Used when we need to check for a new condition only if the
earlier one is true.

4. else if → Like ‘else’ , ‘else if’ also can only be used along with ‘if condition’. It
adds a new condition and specifies the block of code that needs to be
executed when ‘if condition’ is false but the new condition is true.

5. switch → Specifies alternative blocks of code within different cases(condition)


that is to be executed depending upon the condition that is met.
Example 16 :

#include <stdio.h>
int main(){
//------------------------------------------if - else stateme
nt
int r = 2, p = 5;
if(r > p){
// since condition (a>b) is false this block is not executed
print("Not equal");
}
else{
print("Equal");
//since the 'if condition'(r>p) is false, else block will be executed
}
//—-----------------------------------------nested if - else
statement
int z;
printf("Enter a number = ");

C-Notes by Coding Age 11


scanf("%d", &z);
if(z%2 == 0){
if(z%3 ==0){
printf("%d is an even number divisible by 3", z);
}
else{
printf("%d is an even number but not divisible by 3",
z);
}
}
else{
printf("%d is not an even number", z);
}
//--------------------------------------------else if statement
int a = 10, b = 13;
if (a>b) {
// since condition (a>b) is false this block is not executed
printf("%d", a);
}
else if (a<b) {
//since 'if' condition is false, a new condition is checked here.
printf("%d", b);
// new condition is true. Output is 13
}
else{
//this block would've been executed if both 'if' and 'else if conditions
//were false
printf("a and b are equal");
}
return 0;
}

Example 17 :

//------------------------------------------------Switch case
#include <stdio.h>
int main(){
int option;
printf("Enter option - ");
scanf("%d", &option);
switch(option){
case 1:
printf("Selected option is 1");
break; // break statement is used to end the flow of executi
on
case 2:
printf("Selected option is 2");
break;
case 3:
printf("Selected option is 3");
break;
default: // executed when case for an input does not exist
printf("Invalid option");
}
return 0;
}

C-Notes by Coding Age 12


To prevent the code from being executed further, after the required case block has been executed , we've add a 'break'
statement at the end of each block.

Loops :
Loops are a control structure that are used to execute a block of code repeatedly.

Loops automate the task that has to be performed and control the flow of the program.

There are three types of loop in C.

For loop is used when we know the number of times a block of code needs to be executed consecutively.

While loop is used when we do not know the exact number of times the block of code will get executed but we know
the condition that needs to be fulfilled for the block to get executed.

Do-while loop is similar to while loop but thereʼs one difference. It does not check the condition for the first iteration
and starts checking it after the first execution. Hence, even if the condition is false from the beginning(unreachable),
the flow will get inside the loop, perform the task for one time and then exit.ʼ
Example 18 :

//----------------------------------FOR LOOP
#include <stdio.h>
int main(){
// print the statement 5 times.
for(int i = 1 /*initialization*/;i<=5 /*condition*/;i++/*updation*/){
printf("This is a for loop. ");
}
//-----------------------------------WHILE LOOP
int j = 1; //variable is initialized beforehand
while(j<=3){ // print the statement till j is equal to 3
printf("This is a while loop. ");
j++;
}
//----------------------------------DO-WHILE LOOP
// print the statement if k is greater than 5
int k = 1;

C-Notes by Coding Age 13


do{
printf("This is a do-while loop. ");
k++;
}while(k>5);
//Even though the condition is unreachable, the statement is printed once.
return 0;
}

Nested Loops:
Nested loop means ‘loop inside loopʼ. There can be any number of loops inside a loop.

A loop inside a loop means, for each iteration of the outer loop, there will be a completion of the inner loop.
Example 19 :

#include <stdio.h>
int main(){
int n = 3, i, j ;
//----------------------------------Nested for loop
for(i = 1; i<=n; i++){
for(j = 1; j<=n; j++){
printf("* ");
}
printf("\n");
}
//----------------------------------Nested while loop
int k = 1;
while(k<=n){
int m = 1;
while(m<=n){
printf("* ");
m++;
}
printf("\n");
k++;
}
//--------------------------------Nested do-while loop
int a = 1;
do{
int b = 1;
do{
printf("* ");
b++;
}while(b<=n);
printf("\n");
a++;
}while(a<=n);

return 0;
}

Break statement :
Break statement bypasses the flow of execution to outside of the loop or to outside of the block depending upon where
it is used.

If used in a block, it skips the remaining instructions.

C-Notes by Coding Age 14


If used in a loop, it skips the remaining instructions as well as remaining iterations of that loop and passes the flow to
the outside of that loop.

Continue Statement :
Continue statement skips the instructions according to the condition.

When used inside a loop, it bypasses the flow of execution to the start of the next iteration by skipping the remaining
instructions of the current iteration.
Example 20 :

#include <stdio.h>
int main(){
int i, j;
for(i = 1; i<=5; i++){
if(i == 3){
printf("Loop terminated at %d\n", i);
break; //—------------using break statement
}
printf("Break Statement %d\n", i);
}
for(j = 1; j<=5; j++){
if(j == 4){
continue; //—---------using continue statement
printf("j = 4");
}
printf("%d ", j);
}
return 0;
}

Function:
Function is a block of code that performs a specific task and is enclosed within curly brackets.

The code written inside a function can be executed only when the function is called.

Syntax of a function:

Function can be of two types -

1) Return type function

int addTwoNumbers(int m, int n){


int sum = m+n;

C-Notes by Coding Age 15


return sum;
}

In the "Return type function" , the function returns a value after execution. That value has to be of data type that is
mentioned in ‘Return typeʼ,

For example, the addTwoNumbers function returns the sum which is an integer.

2) Void function

void sumOfTwoNumbers(int k, int j){


int sum = k+j;
printf("sum is %d", sum);
}

The "Void function" does not return any value. Hence, we write void at the beginning, which indicates that the function
upon being called, does not return any value.

For example, the sumOfTwoNumbers function prints the value of sum but does not return any value.

Function name:
A function name is the identifier given to a function. It is used to call the function.

In the given examples, addTwoNumbers and sumOfTwoNumbers are function names.

Parameters:
Parameters are variables(values) that are passed in a function as input values upon which the function will perform the
operation written in the block of code.

Parameters are placed inside parentheses.

Any number of parameters can be passed in a function depending upon their usage.

Calling a function:

#include <stdio.h>
//A function always has to be defined outside of the 'main'
int addTwoNumbers(int m, int n){ //Return type function
int sum = m+n;
return sum;
}
void sumOfTwoNumbers(int k, int j){ //Void function

int sum = k+j;


printf("Sum is %d",sum);
}
int main(){
/*'main' is also a function that has integer as its return
type and that is why we write return zero at the end.*/
int a=5, b=6;

C-Notes by Coding Age 16


//Calling the Return type function:
printf("sum is %d", addTwoNumbers(a, b)); // Output is 11
// Here we will hav
e to print the value that is returned by the function
//Calling the void function:
printName(a); //Output is 11
/*here the printf function is there itself in the function and the function
does not return anything, hence we don't need to use the print statement here*/
return 0;
}

What happens when a function is called:


Step 1: The moment a function is called, the control of the program moves to the definition of that function.

Step 2:The function then performs the specific task that it is intended to do. Meaning, the code written inside that function
is executed.

Step 3: If the function is a return type function, it returns a value after execution. If it is a void function, it does not return
any value.

Step 4:Once the function has completed its task, the control of the program returns back to the point where the function
was called and then the statement written after the function call is executed.

Note: Execution of a code always starts from the ‘main function’.

Arrays:
An array is a data structure in C that allows you to store multiple values of the same data type in a single variable. It is
used to store a list of values.

Each element (value or variable) of an array is given an array index which is a series of whole numbers. This makes it
easier to identify them by their respective index.

The index of array starts from zero (also called zero indexed). So, if we have an array of 5 elements, the index of first
element will be 0, index of second element will be 1 and so on.

Arrays are multidimensional but there are two types of array that are most commonly used - 1D array and 2D array.

1D Array:
A 1D array, also known as a one-dimensional array, is a simple data structure in C that holds multiple values of the
same data type in a linear form.
Here's an example of a 1D array with indexes in a visual form:

This represents a 1D array where:

at index 0, the value is 5

at index 1, the value is 8

at index 2, the value is 2

at index 3, the value is 6

at index 4, the value is 9

C-Notes by Coding Age 17


#include <stdio.h>
int main(){
int array1[5]; //This is how we declare a 1D array.
//The number inside [] is the size of array
int array2[3]={19, 17, 32};
//This is how we declare as well as initialize a 1D array
printf("Value at the first index of array2 is %d", array2[0]);
//Output is 19
printf("Value at the second index of array2 is %d", array2[1]);
//Output is 17
printf("Value at the third index of array2 is %d", array2[2]);
//Output is 32

return 0;
}

2D Array:
On the other hand, a 2D array, also known as a two-dimensional array, is a data structure that is a collection of 1D
arrays.

It is represented in a tabular form which consists of rows and columns, where each row is a 1D array.

For example, if we want to store the data of a matrix, we can use a 2D array. In a matrix, we store data at the
intersection of each row and column.

The coordinates(x, y) of these intersection point are the index of elements in a 2D array.
Here's an example of a 2D array which is represented by a matrix :

This represents a matrix of size 3*3 where:

At index matrix[0][0] , the value is 1

At index matrix[0][1] , the value is 2

At index matrix[0][2] , the value is 3

At index matrix[1][0] , the value is 4

At index matrix[1][1] , the value is 5

At index matrix[1][2] , the value is 6

At index matrix[2][0] , the value is 7

At index matrix[2][1] , the value is 8

At index matrix[2][2] , the value is 9

#include <stdio.h>
int main(){
int array1[5][5]; //This is how we declare a 2d array
//The number inside first [] is the number of rows
//The number inside second [] is the number of columns
int array2[3][3] = {{1, 2, 3},{4, 5, 6},{7, 8, 9}};
/*This is how we declare as well as initialize a 2D array*/

C-Notes by Coding Age 18


printf("Value at first row and first column of array2 is %d",array2[0][0]);
//Output is 1
printf("Value at third row and second column of array2 is %d",array2[2][1]);
//Output is 8
printf("Value at second row and first column of array2 is %d",array2[1][0]);
//Output is 4
return 0;
}

Size of an array:
When the size of an array is not known to us, it can be calculated by using the sizeof operator. sizeof gives the size in
bytes.

If we want to find the number of elements in an array, we can divide the total size of the array by the size of one
element (which is the byte size of the datatype of that array).
Here's how to do it:

#include <stdio.h>
int main() {
int array[10];
/*Here the array is of int data type, the size of each element here
is equal to the size of integer in bytes.*/
int size = sizeof(array) / sizeof(array[0]);
printf("The size of the array is: %d\\n", size);
return 0;
}

In the above example, sizeof(array) gives the total size of the array in bytes, and sizeof(array[0]) gives the size of one
element. The division of these two values gives the total number of elements in the array.

Note: It is important to note that arrays in C are fixed in size. This means once you declare
an array, you can't change its size.

Strings:
There is a ‘charʼ data type in C which allows only one character to be stored in a variable. The value assigned to the
variable has to be inside single quotes (ʼ ‘).
For Example.

#include <stdio.h>
int main(){
char letter = 'a'; // assigning value to the variable of char
Basics of C programming 39
r data type
return 0;
}

Since we do not have String data type in C, in order to store a string we use an array of ‘charʼ data type.

This stores each character of the string on each index of the array.

When a string is stored in a char array, the array ends with a null character. To elaborate, the element at the last index
of a char array is ‘\0ʼ, which is a null character.

The null character signifies the end of a string.

Syntax :

C-Notes by Coding Age 19


#include <stdio.h>
#include <string.h> //has functions that can be used to manip
ulate strings
int main(){
char arr[50]; //char array of size 50
printf("Enter a string: ");
fgets(arr, sizeof(arr), stdin);//user input
printf("%s", arr);//prints the output
//or
puts(arr); //prints the output
return 0;
}

‘string.hʼ is a header file which contains functions that can be used to manipulate a string.

To take input in the form of a string, we use ‘fgets()ʼ function.

Format specifier used for string(or char array) is ‘%sʼ ,

fgets function:
fgets() function requires three arguments -

first, the char array, where we are going to store the string input.

second, size of the char array(if not known, can be calculated by using ‘sizeofʼ operator).

stdin, takes input from the user through keyboard.

Some of the frequently used functions from ‘string.hʼ :


strlen() - Returns the length of the string.

strcmp() - Compares two strings. (returns the difference in ascii value of two strings)

strcpy() - Copy first n characters of one string to another.

strcat() - Concatenates(joins) two strings.

strtok() - Split the given string into tokens based on some character as a delimiter such as space, comma, dot etc.

#include <stdio.h>
#include <string.h>
int main(){
char first[] = "Sbc";
char second[] = "Tyx";
char third[] = "check-in";
printf("Length of the first string is %d", strlen(first));//output is 3
printf("ascii difference is %d", strcmp(first, second));//output is -1
//(ascii value of S=83, T=84, 83-84=-1)
printf("%s\n", strcpy(first, second));
//output is'Tyx'(value of second is copied to first)
printf("\n%s\n", strcat(third, second));//output is 'check-i
nTyx'
printf("\n%s", strtok(third,"-"));//output is 'check'(here'-' is a delimiter)
return 0;
}

Pointers:
A pointer is a type of variable that can be of any data type. It stores the address of a different variable of same data
type as its own.
(address refers to a unique numeric value that represents the location of a variable in the memory)

C-Notes by Coding Age 20


For example:
if variable ‘aʼ stores the address of variable ‘bʼ , then variable ‘aʼ has to be a pointer. It also means that variable ‘aʼ
points(→) to the location where variable ‘bʼ is located.

If pointer is of int data type, the address that it stores has to be of a variable of int data type only. Same goes for
pointers of other data types as well. Meaning, pointer and the variable whose address it stores have to be of same data
type.

Pointers allow us to make changes at the memory level.

This is how we declare a pointer:

data type* nameOfPointer ; where, ‘*ʼ is known as dereference operator.

#include <stdio.h>
int main(){
int a = 5;
int* p = &a; /*declaring and initializing a pointer 'p' that stores the
address of variable 'a'(symbol '&' is known as'address of' operator)*/
return 0;
}

Using a pointer we can access the value of the variable that is being pointed by that pointer.

To do this, we need to add asterisk(*) to the left of the pointer variable.

#include<stdio.h>
int main(){
int a = 5;
int* p = &a;
printf("%d\n ", p);//output is address of 'a'
printf("%d\n ", *p); //output is 5
*p = 7; //assigning 7 as value to the variable that is pointed by 'p'
/*here *p means the value of variable whose addressis stored in 'p' which
is 'a' in this case*/
printf("%d\n ", a);//output is 7
printf("%d\n ", *p);//output is 7
printf("%d ", *(&a));//output is 7
return 0;
}

Pointer to an array:
Pointer to an array points to the address of memory block of an array .

We can easily move the pointer to point to each index of the array.

#include <stdio.h>
int main(){
int arr[6] = {1, 2, 3, 4, 5, 6};
int* p = arr;//pointer that points to the array
//(name of the array gives the address of 0th index)
printf("%p\n", &arr[0]);//output is the address of 0th index
printf("%p\n", arr);//output is the address of 0th index
printf("%p\n", p);//output is the address of 0th index
//(points to the same location)
//(adding an index to the array name or pointer, gives the address of that index)
printf("%p\n", &arr[1]);//output is the address of 1st index
printf("%p", arr+1);//output is the address of 1st index
printf("%p", p+1);//output is the address of 1st index

C-Notes by Coding Age 21


//(points to the same location again)
//(accessing the value at an index through pointer)
printf("%d\n", arr[2]); //output is 3
printf("%d\n", *(arr+2)); //output is 3
printf("%d\n", *(p+2)); //output is 3
return 0;
}

Passing pointer as argument to a function:


//-------Swap two numbers using pointers-------
#include<stdio.h>
void swap(int *a, int *b){ //swapping the variables at memory location
int temp;
temp=*a;
*a=*b;
*b=temp;
}
int main(){
int a=3, b=4;
printf("%d and %d", a, b);//output is 3 and 4
swap(&a, &b); //function call
printf("\n");
printf("%d and %d", a, b);//output is 4 and 3
return 0;
}

Types of pointer:
There are various types of pointer in C. Some of them are listed below:

Null pointer : Null pointer does not store the address of any variable, hence it does not point to any location. It holds
the value Null.

Dangling pointer : This is a pointer pointing to a memory location that has been deleted or freed.

Void pointer : Void pointer does not have a specific data type. It can store the address of a variable of any data type.

Pointer to Pointer (Double Pointer) : This pointer stores the address of

another pointer and is denoted by adding double asterisks to the left of the pointer.
For Example:

int z= &a;

**int y = &z;

Here, variable ‘yʼ is a double pointer.

Dynamic Memory Allocation:


Dynamic Memory Allocation is the process of allocating memory at runtime.

When we declare an array(known as static memory allocation), we get a block of space in the memory which is fixed in
size. We cannot change the size of that block later in the code.

For Example:
We declared an array of size 10 to store 10 elements, but later we removed 3 elements and are left with only 7
elements. The array is going to continue occupying space worth 10 elements leaving the space of those 3 removed
elements unused.

This is clearly a wastage of the space available in memory.

C-Notes by Coding Age 22


In order to prevent the wastage of available space and use it efficiently, we make use of the concept called Dynamic
Memory Allocation.

Process of Dynamically Allocating Memory:


To allocate memory dynamically, we use 4 specific functions that are available in a header file called ‘stdlib.hʼ .

These four functions are:

1) malloc()

2) calloc()

3) realloc()

4) free()

malloc() function:
It allocates a single block of memory based on user-specified size.

It returns null if memory is not sufficient.

It returns a pointer to the beginning of the newly allocated memory block.


Syntax :

#include<stdio.h>
#include<stdlib.h> //headerfile that contains DMA function
int main()
{
int n,i,ptr,sum=0;
printf("Enter the number of elements: ");
scanf("%d",&n);
ptr=(int)malloc(nsizeof(int)); //memory allocated using malloc
//ptr=(data type)malloc(size of array * byte size)
if(ptr==NULL) {
printf("Unable to allocate memory");
exit(0);
}
printf("Enter elements of array: ");
for(i=0;i<n;++i){
scanf("%d",ptr+i);
sum+=*(ptr+i);
}
printf("Sum = %d",sum);
free(ptr);
return 0;
}

calloc() function:
It not only reserves the requested amount of memory but also initializes the values to 0.

It allocates multiple blocks of memory in multiple chunks at different locations (if enough space is not available at a
single location).

It returns null if memory is not sufficient.

It returns a pointer to the beginning of the newly allocated memory block.


Syntax :

#include<stdio.h>
#include<stdlib.h>
int main(){
int n,i,ptr,sum=0;

C-Notes by Coding Age 23


printf("Enter the number of elements: ");
scanf("%d",&n);
ptr=(int)calloc(n, sizeof(int)); //memory allocated using c
alloc()
//ptr=(data type*)calloc(size of array, byte size)
if(ptr==NULL){
printf("Unable to allocate memory");
exit(0);
}
printf("Enter the elements of array: ");
for(i=0;i<n;++i){
scanf("%d",ptr+i);
sum+=*(ptr+i);
}
printf("Sum=%d",sum);
free(ptr);
return 0;
}

realloc() function:
This allows to adjust the size of previously allocated memory dynamically.

It works by allocating a new block of memory with the newly mentioned size, copying the contents of the old block into
the new one, and finally freeing the old block.
Syntax :

#include <stdio.h>
#include <stdlib.h>
int main()
{
int ptr, i , n1, n2;
printf("Enter the number of elements to declare size required: ");
scanf("%d", &n1);
ptr = (int) malloc(n1 * sizeof(int)); //memory allocated using malloc()
printf("Addresses of previously allocated memory:\n");
for(i = 0; i < n1; ++i){
printf("%p\n",ptr + i);
}
printf("\nEnter the number of elements to declare the new size required: ");
scanf("%d", &n2);
ptr = realloc(ptr, n2 * sizeof(int));// rellocating the memory
//ptr=realloc(ptr, new-size*byte size)
printf("Addresses of newly allocated memory:\n");
for(i = 0; i < n2; ++i){
printf("%p\n", ptr + i);
}
free(ptr);
return 0;
}

free() function:
It enables you to release previously allocated dynamic memory.

Advantages of Dynamic Memory Allocation:


Dynamic Memory Allocation provides Flexibility by enabling you to allocate memory as per the actual data size and
change it dynamically, unlike static allocation, which is fixed.

C-Notes by Coding Age 24


It also provides efficient usage of memory as it optimizes memory usage by allocating memory only when required
and releasing it when no longer needed. This dynamic management of memory prevents wastage and improves overall
program efficiency.

Structure:
Structure is a user-defined data type that can be used to group variables even of different data types into a single type.

The variables in the structure are called its member and they can be of any valid data type.

All the members of a structure are stored in contiguous memory regions and every member has their own memory
place.

The overall size of a structure is the sum of the sizes of all data members.
Syntax :

#include<stdio.h>
#include<string.h>
struct employee{
char name[20];
int id;
};

int main(){
struct employee e1, e2; //First way to declare variable
strcpy(e1.name, "Employee001");
//(A char array can't be assigned a value directly, only initialized.
//To write a string into a char array, we can use strcpy.)
e1.id = 12345;
printf("Employee name is %s\nEmployee id is %d", e1.name, e1.id);
return 0;
}

#include<stdio.h>
#include<string.h>
struct employee{
char name[20];
int id;
}emp1, emp2; //Second way to declare variable

int main(){
strcpy(emp2.name, "Employee002");
emp2.id = 12345;
printf("Employee name is %s\nEmployee id is %d", emp2.name,emp2.id);
return 0;
}

Union:
Similar to structure, union is a data type in C programming that allows different data types to be stored but unlike
structure, it stores them in the same memory location.

Union provides an efficient way of reusing the memory location, as only one of its members can be accessed at a time.

A user can create a union with numerous members, but only one member can hold a value at any given moment.

The total storage space allotted for the union is equal to the storage space required by the unionʼs biggest data
member, and all fields are stored at the same space. This way, union efficiently uses the space available in the memory.
Syntax :

C-Notes by Coding Age 25


#include<stdio.h>
#include<string.h>
union myunion{
int a;
char b[20];
}emp1, emp2;
int main(){
//only one of these variables can be assigned value at a time.
/*If you try to assign values to more than one variable at a time, it will take
the one with greater size.*/
//In this example, it will give garbage value for int typevariable.
/*Comment out the initialization of other variables in order to assign value to
anyone of them.*/
emp1.a = 874;
printf("Employee id is %d", emp1.a);
strcpy(emp1.b, "Employee name");
printf("Employee name is %s", emp1.b);
return 0;
}
//**Like structure, union variables can also be declared in the same two ways.

File Handling:
File handling in C provides a mechanism to store the output of a program in a file and to perform various operations on
it. C supports a large number of functions to handle files.

Basic File Operations:


Creating a new file: You can create a new file in C using the fopen() function.
It allows you to specify the name of the file and the mode in which you want to
open it.

Opening an existing file: You can open an existing file in C using the fopen()

function.

Closing a file: After finishing all the operations on the file, it is closed using the
fclose() function. It's a good practice to close a file after all operations are done.

Writing to a file: We can write to a file in C using fprintf() , fputc() , fputs() , fwrite() etc.

Reading from a file: We can read from a file in C using fscanf() , fgetc() , fgets() , fread() etc.

Access a record at a specific position: We can move the file pointer associated with a given file to a specific position
using fseek() .

File Modes:
"r" - Opens the file for reading.

"w" - Opens the file for writing. If the file already exists, its content is cleared.
If the file doesn't exist, a new file is created.

"a" - Opens the file for appending new information to the end. If the file
doesn't exist, a new file is created.

"r+" - Opens the file for both reading and writing.

"w+"- Opens the file for both reading and writing. If the file already exists, its
content is cleared. If the file doesn't exist, a new file is created.

"a+"- Opens the file for both reading and appending. If the file doesn't exist,
a new file is created

C-Notes by Coding Age 26


Example:
#include <stdio.h>
int main() {
FILE *fp;
fp = fopen("file.txt", "w+");
if(fp == NULL)
{
printf("File not found!");
Basics of C programming 55
exit(1);
}
fprintf(fp, "This file is created by me while learning file handling. ");
fclose(fp);
return 0;
}

In this example, we're creating a file named "file.txt", writing to it, and then closing it. If "file.txt" already exists, its
existing content is cleared and the new content is written.

It's a good practice to close the file after you are done with all operations. Doing this, frees up the resources that were
tied with the file.

fseek() :

👉 int fseek(FILE *pointer, long int offset, int position);


Parameters :
pointer : It is the pointer that points to the FILE that we need to modify.

offset : It is the number of characters or bytes, where the position of the file pointer needs to be shifted relative to the
current position to determine the new position.

position : It is the position from where the offset is added. Position defines the
point with respect to which the file pointer needs to be moved. It has three values:

SEEK_END : It denotes the end of the file.

SEEK_SET : It denotes starting of the file

SEEK_CUR : It denotes the file pointer’s current position.

Return value :
It returns zero if successful, or else it returns a non-zero value.
Syntax :

#include <stdio.h>
int main()
{
FILE* fp;
fp = fopen("file.txt", "w+");
if(fp == NULL)
{
printf("File not found!");
exit(1);
}
fprintf(fp, "abcdefghijk");
printf("%ld\n", ftell(fp)); //11
//ftell() returns the current position of the pointer in
the file.

C-Notes by Coding Age 27


fseek(fp, 4, SEEK_END);
printf("%ld", ftell(fp)); //15
return 0;
}

C-Notes by Coding Age 28

You might also like