0% found this document useful (0 votes)
3 views91 pages

Module 1b

The document provides an overview of arrays in C, including single and multi-dimensional arrays, their syntax, initialization methods, and examples. It discusses array operations such as sorting, traversal, and matrix operations, as well as string handling and input methods. Additionally, it highlights common pitfalls like buffer overflows and the importance of proper input handling.

Uploaded by

moksheshveera
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)
3 views91 pages

Module 1b

The document provides an overview of arrays in C, including single and multi-dimensional arrays, their syntax, initialization methods, and examples. It discusses array operations such as sorting, traversal, and matrix operations, as well as string handling and input methods. Additionally, it highlights common pitfalls like buffer overflows and the importance of proper input handling.

Uploaded by

moksheshveera
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

Array

• An array is a collection of variables of the same type that are referred


to through a common name.
• A specific element in an array is accessed by an index.
• In C, all arrays consist of contiguous memory locations. The lowest
address corresponds to the first element and the highest address to
the last element.
• Arrays can have from one to several dimensions.

1
Single-Dimension Arrays
• Syntax:
• type var_name[size];
• Example:
• double balance[100];
• The size of an array is fixed at compile time.
• All arrays have 0 as the index of their first element.
• An element is accessed by indexing the array name.
• balance[3] = 12.23;

2
A seven-element character array beginning at
location 1000

char a[7];

3
Array Initialization
• Array Initialization with Declaration
• data_type array_name [size] = {val1, val2, ... valN};
• Array Initialization with Declaration without Size
• data_type array_name[] = {val1, val2, ... valN};
• Array Initialization after Declaration (Using Loops)
• for (int i = 0; i < N; i++) {
array_name[i] = valuei;
}
4
Example
#include <stdio.h>
int main(void)
{
int x[100]; /* this declares a 100-integer array */
int t;
/* load x with values 0 through 99 */
for(t=0; t<100; ++t)
x[t] = t;
/* display contents of x */
for(t=0; t<100; ++t)
printf(''%d ", x[t]);
return 0;
}

5
• C has no bounds checking on arrays.
int count[10], i;
/* this causes count to be overrun */
for(i=0; i<100; i++)
count[i] = i;

6
Sorting
int i, j;
for (i = 0; i < n - 1; i++)
{
for (j = 0; j < n - i - 1; j++)
{
if (arr[j] > arr[j + 1])
{
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
7
#include <stdio.h>
int main(){
int a[5]={1,2,3};
for(int i=0;i<5;i++)
printf("%d",a[i]);
return 0;
}

8
#include <stdio.h>
int main(){
int a[]={1,2,3};
for(int i=0;i<5;i++)
printf("%d ",a[i]);
return 0;
}

9
#include <stdio.h>
int main(){
int a[5]={1,2,3,4,5,6,7};
for(int i=0;i<5;i++)
printf("%d",a[i]);
return 0;
}

10
#include <stdio.h>
int main(){
int a[5]=0;
for(int i=0;i<5;i++)
printf("%d",a[i]);
return 0;
}

11
#include <stdio.h>
int main(){
int a[5]={0};
for(int i=0;i<5;i++)
printf("%d",a[i]);
return 0;
}

12
#include <stdio.h>
int main(){
int a[5]={‘a’};
for(int i=0;i<5;i++)
printf("%d",a[i]);
return 0;
}

13
#include <stdio.h>
int main(){
float a[5]={27.9,27.4};
for(int i=0;i<5;i++)
printf("%f ",a[i]);
return 0;
}

14
Two-Dimensional Arrays
• A two-dimensional array is an array of one-dimensional arrays.
• Syntax:
datatype var_name[rowsize][columnsize];

15
16
17
How to Initialize a 2D Array in C?
• int arr[3][4] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}

• int arr[3][4] = {{0, 1, 2, 3}, {4, 5, 6, 7}, {8, 9, 10, 11}};

• int arr[3][4] = {0};

• int count=1;
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 4; j++)
{
arr[i][j] = count++;
}
} 18
How to Initialize a 2D Array in C?

19
Initializing an unsized 2D array

20
21
Simple operations on 2D array

22
2D Array Traversal
#include <stdio.h>
int main(void)
{
int t, i, num[3][4];
for(t=0; t<3; ++t)
for(i=0; i<4; ++i)
scanf(“%d”, &num[t][i]);
for(t=0; t<3; ++t)
{
for(i=0; i<4; ++i)
printf(''%d ", num[t][i]);
printf("\n");
}
return 0;
} 23
Matrix Transpose
#include <stdio.h>
int main() { // computing the transpose
int a[10][10], transpose[10][10], r, c; for (int i = 0; i < r; ++i)
printf("Enter rows and columns: "); for (int j = 0; j < c; ++j)
scanf("%d %d", &r, &c); transpose[j][i] = a[i][j];
printf("\nEnter matrix elements:\n"); // printing the transpose printf("\nTranspose
for (int i = 0; i < r; ++i) of the matrix:\n");
for (int j = 0; j < c; ++j) for (int i = 0; i < c; ++i)
scanf("%d", &a[i][j]); {
// printing the matrix a[][] for (int j = 0; j < r; ++j)
printf("\nEntered matrix: \n"); printf("%d ", transpose[i][j]);
for (int i = 0; i < r; ++i) { printf("\n");
for (int j = 0; j < c; ++j) }
printf("%d ", a[i][j]); return 0;
printf("\n"); }
24
}
Matrix Addition
#include <stdio.h> // add the matrices
int main() { for (i = 0; i < m; i++) {
int m, n, i, j; for (j = 0; j < n; j++) {
printf("Enter the number of rows and columns: "); c[i][j] = a[i][j] + b[i][j];
scanf("%d%d", &m, &n); }
int a[m][n], b[m][n], c[m][n]; }
printf("Enter the elements of matrix A: \n"); // print the result
for (i = 0; i < m; i++) { printf("The sum of the two matrices is: \n");
for (j = 0; j < n; j++) {
scanf("%d", &a[i][j]); for (i = 0; i < m; i++) {
} for (j = 0; j < n; j++) {
} printf("%d ", c[i][j]);
printf("Enter the elements of matrix B: \n"); }
for (i = 0; i < m; i++) { printf("\n");
for (j = 0; j < n; j++) { }
scanf("%d", &b[i][j]); return 0;
} } 25
}
Strings

26
Strings
• When declaring a character array that will hold a string, you need to
declare it to be one character longer than the largest string that it will
hold.
• For example, to declare an array str that can hold a 10-character
string, you would write char str[11];
• Specifying 11 for the size makes room for the null at the end of the
string.

27
28
// C program to read string from user
#include<stdio.h>
int main()
{
char str[50]; // declaring string
scanf("%s",str); // reading string
printf("%s",str); // printing string
return 0;
}

29
C program to illustrate fgets()
#include <stdio.h>
#define MAX 50
int main() {
char str[MAX];
fgets(str, MAX, stdin);
printf("String is: \n");
puts(str);
return 0;
}
30
String Input using scanset
#include <stdio.h>
int main()
{
char str[20];
scanf("%[^\n]s", str); // using scanset in scanf
printf("%s", str); // printing read string
return 0;
}

31
#include <stdio.h>
int main(){
char s1[15]="Good Day!";
printf("s1=%s\n",s1);
char s2[]="Good Day!";
printf("s2=%s\n",s2);
char s3[15]={'G','o','o','d',' ','D','a','y','!','\0’};
printf("s3=%s\n",s3);
char s4[]={'G','o','o','d',' ','D','a','y','!','\0’};
printf("s4=%s\n",s4);

32
char s5[15];
printf("Enter a String: ");
scanf("%s",s5);
printf("s5=%s\n",s5);
char s6[15];
printf("Enter a String: ");
fgets(s6,15,stdin);
printf("s6=%s\n",s6);
printf("Enter a String: ");
scanf("%[^\n]",s5); //Reads all characters until a newline (\n)
//DOES NOT consume the newline
getchar();//Consume the leftover newline before fgets()
printf("s5=%s\n",s5);
printf("Enter a String: ");
fgets(s6,15,stdin);
printf("s6=%s\n",s6);
return 0;} 33
scanf("%s", s5); scanf("%[^\n]", s5);
Reads a word Reads everything until a newline
Stops reading when it encounters: Can read spaces
space ' ' Does NOT consume the newline (\n)
tab \t Does NOT skip leading whitespace
newline \n
Automatically skips leading whitespace Suitable for Full sentences, Strings with
Suitable for Single words spaces Example
Example char s5[50];
char s5[20]; scanf("%[^\n]", s5);
scanf("%s", s5); printf("%s", s5);
printf("%s", s5); Input
Input Hello World from C
Hello World Output
Output Hello World from C
Hello 34
• Reads up to (n−1) characters
• Stops when:
• newline \n is read, or
• size limit is reached
• Consumes the newline fgets()
• Stores newline in the string (if space allows)
• Safe (prevents buffer overflow)
• Reads spaces
• Preferred for string input
char s[15];
fgets(s, 15, stdin);
printf("%s", s);
• Input
C programming is fun
• Output
C programming
• (only first 14 chars + \0)

35
• Don’t mix scanf() and fgets()
• Prefer fgets() for string input

36
Header <string.h>

37
#include <stdio.h>
#include <string.h>
int main(void)
{
char s1[80], s2[80];
gets(s1);
gets (s2);
printf("lengths: %d %d\n", strlen(s1), strlen(s2));
if(!strcmp(s1, s2))
printf("The strings are equal\n");
strcat(s1, s2);
printf (''%s\n", s1);
strcpy(s1, "This is a test.\n");
printf(s1);
if(strchr("hello", 'e')) printf("e is in hello\n");
if(strstr("hi there", "hi")) printf("found hi");
return 0;
38
}
39
To calculate string length without using built-
in functions
#include <stdio.h>
int main()
{
char s[50];
int len = 0;
scanf("%[^\n]s", s);
while (s[len]) // while (s[len]!='\0’) Count each character from start to end
len++;
printf("Length of %s is %d\n",s,len);
return 0;
}

40
To calculate string length without using built-
in functions
#include <stdio.h>
int main()
{
char s[50];
int len = 0;
fgets(s, 50, stdin); //Stores newline character also
while (s[len]) // Count each character from start to end
len++;
printf("Length of %s is %d\n",s,len);
return 0;
} 41
To concatenate 2 strings without using built-
in functions
// Copy characters from str2 to str1
#include <stdio.h> int j = 0;
int main(){ while (s2[j] != '\0') {
char s1[50], s2[50]; s1[i] = s2[j];
int i = 0; i++;
scanf("%s", s1); j++;
scanf(" %s", s2); }
// Count each character from start to end // Null-terminate the concatenated string
while (s1[i] != '\0') s1[i] = '\0';
i++; printf("Concatenated string is %s\n",s1);
return 0;
}

42
// C program to illustrate strstr()
#include <stdio.h>
#include <string.h>
int main()
{
char s1[] = "Something Nothing Everything";
char s2[] = "thing";
char* p;
p = strstr(s1, s2); // Find first occurrence of s2 in s1
if (p) {
printf("String found\n");
printf("First occurrence of string “%s” in “%s” is “%s”, s2, s1, p); // Prints the result
}
else
printf("String not found\n");
return 0;
}

43
#include<stdio.h>
void main()
{
char c;
printf("Input No.1\n");
Input No.1
scanf("%c", &c); s
printf("c = %c\n", c); c = s
Input No.2
c =
printf("Input No.2\n");
scanf("%c", &c); Input No.3
printf("c = %c\n", c); a
c = a

printf("Input No.3\n");
scanf("%c", &c);
printf("c = %c\n", c);
}

As you see, the input No.2 was skipped. As a result, first scanf will
read the s. Second scanf will read the enter! That’s why, the second
printf of the value of c leaves just a newline after “c=”. Then the
third scanf waits for a key press. You input a and then you hit enter.
a is been assigned to variable c and enter remains in the stdin
buffer, ready to be read by the next scanf. If we had a fourth scanf,
then it would read the enter.
44
So, just change scanf_s("%c", &c,1); to scanf_s(" %c", &c,1);
and you will be just fine. You can see in the code below:

#include<stdio.h>
void main()
{
char c;
printf("Input No.1\n");
scanf("%c", &c);
printf("c = %c\n", c); Input No.1
s
c = s
printf("Input No.2\n"); Input No.2
scanf(" %c", &c); a
printf("c = %c\n", c); c = a
Input No.3
m
printf("Input No.3\n"); c = m
scanf(" %c", &c);
printf("c = %c\n", c);
}

45
Arrays of Strings
• To create an array of strings, use a two-dimensional character array.
• The size of the left dimension determines the number of strings, and the
size of the right dimension specifies the maximum length of each string.
• The following declares an array of 30 strings, each with a maximum length
of 79 characters:
• char str_array[30][80];
• It is easy to access an individual string: You simply specify only the left
index.
• For example, the following statement calls gets( ) with the third string in
str_array.
• gets(str_array[2]);
46
Arrays of Strings
#include <stdio.h>

int main() {

// Creating array of strings for 3 strings


// with max length of each string as 10
char arr[3][10] = {"Bright", "Brighter", "Brightest"};

for (int i = 0; i < 3; i++)


printf("%s\n", arr[i]);
return 0;
}

47
String Sorting for(i=0;i<n;i++){
for(j=i+1;j<n;j++){
#include<stdio.h> if(strcmp(str[i],str[j])>0){
#include<string.h> strcpy(s,str[i]);
main(){ strcpy(str[i],str[j]);
int i,j,n; strcpy(str[j],s);
char str[100][100],s[100]; }
printf("Enter number of names :"); }
scanf("%d",&n); }
printf("Enter names in any order:"); printf("The sorted order of names are:");
for(i=0;i<n;i++){ for(i=0;i<n;i++){
scanf("%s",str[i]); printf("%s",str[i]);
} }
}
48
Functions
• A function is a block of code which only runs when it is called.
• The programming statements of a function are enclosed within { }
braces.
• Define the function once, and use it many times.

49
Types of functions
1. Library Function - pow(), sqrt(), strcmp(), strcpy() etc.
• 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.
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.

50
Functions

51
• The syntax of function can be divided into 3 aspects:
• Function Declaration
• Function Definition
• Function Calls

52
Function Declarations
• A function declaration tells the compiler that there is a function with
the given name defined somewhere else in the program.
• In a function declaration, we must provide the function name, its
return type, and the number and type of its parameters.
• The parameter name is not mandatory while declaring functions.
int sum(int a, int b); // Fn declaration with parameter names

int sum(int , int); // Fn declaration without parameter names

53
Function Definition
• The function definition consists of actual statements which are
executed when the function is called.
• Syntax
return_type function_name (para1_type para1_name, para2_type para2_name)
{
// body of the function
}

int sum(int a, int b)


{
int total;
total=a+b;
return total;
}
54
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.

55
#include <stdio.h>
void add(){
int n1,n2;
scanf("%d%d",&n1,&n2);
printf("the sum is %d",n1+n2);
}
int main(){
add();
return 0;
}

56
#include <stdio.h>
void add();
int main(){
add();
return 0;
}
void add(){
int n1,n2;
scanf("%d%d",&n1,&n2);
printf("the sum is %d",n1+n2);
}
57
#include <stdio.h>
void add(int,int);
int main(){
int n1,n2;
scanf("%d%d",&n1,&n2);
add(n1,n2);
return 0;
}
void add(int x, int y){
printf("the sum is %d",x+y);
}
58
#include <stdio.h>
int add(int,int);
int main(){
int n1,n2,sum;
scanf("%d%d",&n1,&n2);
sum=add(n1,n2);
printf("The sum is %d",sum);
return 0;
}
int add(int x, int y){
return x+y;
} 59
60
Types of functions
• Function with no arguments and no return value
• Function with no arguments and with return value
• Function with argument and with no return value
• Function with arguments and with return value

61
Pass Array to Functions in C
#include <stdio.h> #include <stdio.h> #include <stdio.h>
// Array passed as an array with the // Array passed as an array without the // Array passed as an array without
// size of its dimension // size of its dimension // the size of its dimension
void printArr(int arr[5]) { void printArr(int arr[], int n) { void printArr(int arr[]) {
for (int i = 0; i < 5; i++) for (int i = 0; i < n; i++) for (int i = 0; i < 5; i++)
printf("%d ", arr[i]); printf("%d ", arr[i]); printf("%d ", arr[i]);
} } }
int main() { int main() { int main() {
int arr[] = {1, 2, 3, 4, 5}; int arr[] = {1, 2, 3, 4, 5}; int arr[] = {1, 2, 3, 4, 5};
// Pass array to function // Pass array to function // Pass array to function
printArr(arr); printArr(arr, 5); printArr(arr);
return 0; return 0; return 0;
} } }

62
Pass Array to Functions in C
#include <stdio.h> #include <stdio.h>

// Passing Array as Pointer Notation // Passing Array as Pointer Notation


void printArr(int* arr, int n) { void printArr(int* arr) {
for (int i = 0; i < n; i++) for (int i = 0; i < 5; i++)
printf("%d ", arr[i]); printf("%d ", arr[i]);
} }
int main() { int main() {
int arr[] = {1, 2, 3, 4, 5}; int arr[] = {1, 2, 3, 4, 5};
// Pass array to function // Pass array to function
printArr(arr, 5); printArr(arr, 5);
return 0; return 0;
} }

63
Pass 2D Array to Functions in C
When passing a 2D array, number of columns
must be specified.
Rows are optional.

64
Pass 2D Array to Functions in C

#include <stdio.h> int main()


{
void displayNumbers(int num[2][3]) int num[2][3];
{ printf("Enter 4 numbers:\n");
printf("Displaying:\n"); for (int i = 0; i < 2; ++i) {
for (int i = 0; i < 2; ++i) for (int j = 0; j < 3; ++j) {
{ scanf("%d", &num[i][j]); } }
for (int j = 0; j < 3; ++j) // pass multi-dimensional array to a function
{ displayNumbers(num);
printf("%d\n", num[i][j]); return 0;
} }
}
}

65
Pass 2D Array to Functions in C

#include <stdio.h> int main()


{
void displayNumbers(int num[][3]) int num[2][3];
{ printf("Enter 4 numbers:\n");
printf("Displaying:\n"); for (int i = 0; i < 2; ++i) {
for (int i = 0; i < 2; ++i) for (int j = 0; j < 3; ++j) {
{ scanf("%d", &num[i][j]); } }
for (int j = 0; j < 3; ++j) // pass multi-dimensional array to a function
{ displayNumbers(num);
printf("%d\n", num[i][j]); return 0;
} }
}
}

66
Pass 2D Array to Functions in C

#include <stdio.h> int main()


{
void displayNumbers(int num[][3],int rows) int num[2][3];
{ printf("Enter 4 numbers:\n");
printf("Displaying:\n"); for (int i = 0; i < 2; ++i) {
for (int i = 0; i < rows; ++i) for (int j = 0; j < 3; ++j) {
{ scanf("%d", &num[i][j]); } }
for (int j = 0; j < 3; ++j) // pass multi-dimensional array to a function
{ displayNumbers(num, 2);
printf("%d\n", num[i][j]); return 0;
} }
}
}

67
Pass 2D Array to Functions in C

#include <stdio.h> int main()


{
void displayNumbers(int (*num)[3],int rows) int num[2][3];
{ printf("Enter 4 numbers:\n");
printf("Displaying:\n"); for (int i = 0; i < 2; ++i) {
for (int i = 0; i < rows; ++i) for (int j = 0; j < 3; ++j) {
{ scanf("%d", &num[i][j]); } }
for (int j = 0; j < 3; ++j) // pass multi-dimensional array to a function
{ displayNumbers(num, 2);
printf("%d\n", num[i][j]); return 0;
} }
}
}

68
Pass String to Functions in C
#include <stdio.h> #include <stdio.h> #include <stdio.h>

void display(char str[]) { void display(char *str) { void change(char *str) {


printf("String is: %s\n", str); printf("String is: %s\n", str); str[0] = 'h';
} } }

int main() { int main() { int main() {


char name[] = "C Programming"; char name[] = "Hello World"; char word[] = "Hello";
display(name); display(name); change(word);
return 0; return 0; printf("%s\n", word); // hello
} } return 0;
}

69
Pass String to Functions in C
#include <stdio.h> #include <stdio.h> #include <stdio.h>

void show(const char *str) { void display(char str[], int size) { void compare(char *s1, char *s2) {
printf("%s\n", str); printf("String: %s\n", str); if (strcmp(s1, s2) == 0)
} printf("Size: %d\n", size); printf("Strings are equal\n");
} else
int main() { printf("Strings are not equal\n");
show("Welcome to C"); int main() { }
return 0; char name[20] = “Arjun";
} display(name, sizeof(name)); int main() {
return 0; char a[] = "C";
} char b[] = "C";
compare(a, b);
return 0;
}

70
Passing a 2D character array (Fixed length
strings)
#include <stdio.h>
void display(char arr[][20], int rows) {
for(int i = 0; i < rows; i++) {
printf("%s\n", arr[i]);
}
}

int main() {
char names[3][20] = { "C", "Java", "Python” };
display(names, 3);
return 0;
}

71
Passing array of string pointers (char *arr[])
#include <stdio.h>

void display(char *arr[], int n) {


for(int i = 0; i < n; i++) {
printf("%s\n", arr[i]);
}
}

int main() {
char *names[] = { "Apple", "Banana", "Mango” };
display(names, 3);
return 0;
}

72
Passing array of strings using pointer to array
#include <stdio.h>

void display(char (*arr)[20], int rows) {


for(int i = 0; i < rows; i++) {
printf("%s\n", arr[i]);
}
}

int main() {
char cities[2][20] = {"Chennai", "Delhi"};
display(cities, 2);
return 0;
}

73
C Recursion
• Recursion is the process of a function calling itself repeatedly till the
given condition is satisfied.
• A function that calls itself directly or indirectly is called a recursive
function and such kind of function calls are called recursive calls.
• Syntax
• type function_name (args) {
// function statements
// base condition
// recursion case (recursive call)
}
74
Example
// C Program to calculate the sum of first N natural numbers using recursion
#include <stdio.h>
int nSum(int n) int main()
{
{ int n = 5;
// base condition to terminate the recursion when N = 0 // calling the function
int sum = nSum(n);
if (n == 0) printf("Sum of First %d Natural Numbers: %d", n, sum);
return 0; return 0;
}
int res = n + nSum(n - 1); // recursive call
return res;
}

75
76
Factorial using recursion
int factorial(unsigned int n) {
if (n == 1) { // Base Case:
return 1;
}
return n * factorial(n - 1); // Multiplying the current N with the previous product of
Ns
}
int main() {
int num = 5;
printf("Factorial of %d is %d", num, factorial(num));
return 0;
}
77
Call by Value and Call by Reference
• Call by value
• In call by value method, the value of the actual parameters is copied
into the formal parameters.
• The actual parameter is the argument which is used in the function
call whereas formal parameter is the argument which is used in the
function definition.
• We can not modify the value of the actual parameter by the formal
parameter.
• Different memory is allocated for actual and formal parameters since
the value of the actual parameter is copied into the formal parameter.

78
Call by Value
#include<stdio.h>
void change(int num) {
printf("Before adding value inside function num=%d \n",num);
num=num+100;
printf("After adding value inside function num=%d \n", num);
}
int main() {
int x=100;
printf("Before function call x=%d \n", x);
change(x);//passing value in function
printf("After function call x=%d \n", x);
return 0;
}

79
Call by Value and Call by Reference
• Call by Reference
• In call by reference, the address of the variable is passed into the
function call as the actual parameter.
• The value of the actual parameters can be modified by changing the
formal parameters since the address of the actual parameters is
passed.
• The memory allocation is similar for both formal parameters and
actual parameters. All the operations in the function are performed
on the value stored at the address of the actual parameters, and the
modified value gets stored at the same address.
80
Call by Reference
#include<stdio.h>
void change(int *num) {
printf("Before adding value inside function num=%d \n",*num);
(*num) += 100;
printf("After adding value inside function num=%d \n", *num);
}
int main() {
int x=100;
printf("Before function call x=%d \n", x);
change(&x);//passing reference in function
printf("After function call x=%d \n", x);
return 0;
}

81
Storage Classes in C
• Storage classes in C are used to determine the lifetime, visibility,
memory location, and initial value of a variable.
• There are four types of storage classes in C
• Automatic
• External
• Static
• Register

82
Storage Class Storage Place Default Value Scope Lifetime
auto RAM Garbage Value Local Within function
Till the end of the main
program Maybe
extern RAM Zero Global
declared anywhere in
the program
Till the end of the main
program, Retains value
static RAM Zero Local
between multiple
functions call
register Register Garbage Value Local Within the function

83
Local Variable
int main()
The variables declared inside a block are {
automatic or local variables. The local int n1; // n1 is a local variable to main()
variables exist only inside the block in which
}
it is declared.
void func()
#include <stdio.h> {
int n2; // n2 is a local variable to func()
int main(void) {
}
for (int i = 0; i < 5; ++i) {
printf("C programming");
} // Error: i is not declared at this point
printf("%d", i);
return 0;
}

84
Global Variable
Variables that are declared outside of all
functions are known as external or global
variables. They are accessible from any
function inside the program.
#include <stdio.h>
void display(); // function declaration
int n = 5; // global variable
int main()
{
++n;
display(); // function call
return 0;
}
void display() // function definition
{
++n;
printf("n = %d", n);
}
85
Static variable
#include<stdio.h>
void sum() {
static int a = 10;
static int b = 24;
int c=0;
printf("%d %d %d\n",a,b,c);
a++;
b++;
}
void main() {
int i;
for(i = 0; i< 3; i++)
sum(); // The static variables holds their value between multiple function calls.
}
86
Auto Vs Static
#include <stdio.h> #include <stdio.h>
int fun() int fun()
{ {
int count = 0; static int count = 0;
count++; count++;
return count; return count;
} }

int main() int main()


{ {
printf("%d ", fun()); printf("%d ", fun());
printf("%d ", fun()); printf("%d ", fun());
return 0; return 0;
87
} }
register
• Registers are faster than memory to access, so the variables which are
most frequently used in a C program can be put in registers using the
register keyword.
• If you use & operator with a register variable then the compiler may give
an error or warning.
• register keyword can be used with pointer variables.
• the register can not be used with static.
• Register can only be used within a block (local), it can not be used in the
global scope.
• There is no limit on the number of register variables in a C program, but
the point is compiler may put some variables in the register and some not.

88
register
#include <stdio.h>

// error (global scope)


register int x = 10;
int main()
{
// works (inside a block)
register int i = 10;
printf("%d\n", i);
// printf("%d", x);
return 0;
}

89
extern
• The extern keyword in C is a storage class specifier used to declare a
variable or function that is defined in another source file or library.
• It informs the compiler about the existence and type of the identifier
without allocating memory for it in the current file, and the linker
resolves the actual memory address during the linking phase.
• We can only initialize the extern variable globally, i.e., we can not
initialize the external variable within any block or method.
• An external variable can be declared many times but can be initialized
at only once.

90
extern
//data.c //primary.c
#include <stdio.h> #include <stdio.h>

int count = 10; // Definition (memory extern int count; // Declaration (no
allocated) memory allocated)
void display(); // Function declared
void display()
{ int main()
printf("Count value = %d\n", count); {
} count = count + 5;
display();
return 0;
gcc primary.c data.c -o main }
91

You might also like