Nothing Special   »   [go: up one dir, main page]

C-Arrays & Strings and Functions

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 33

Arrays

C Arrays


Array in C is one of the most used data structures in C programming. It is a


simple and fast way of storing multiple values under a single name. In this
article, we will study the different aspects of array in C language such as array
declaration, definition, initialization, types of arrays, array syntax, advantages
and disadvantages, and many more.
What is Array in C?
An array in C is a fixed-size collection of similar data items stored in contiguous
memory locations. It can be used to store the collection of primitive data types
such as int, char, float, etc., and also derived and user-defined data types such
as pointers, structures, etc.

C Array Declaration
In C, we have to declare the array like any other variable before using it. We can
declare an array by specifying its name, the type of its elements, and the size of
its dimensions. When we declare an array in C, the compiler allocates the
memory block of the specified size to the array name.
Syntax of Array Declaration
data_type array_name [size];
or
data_type array_name [size1] [size2]...[sizeN];

where N is the number of dimensions.


The C arrays are static in nature, i.e., they are allocated memory at the compile
time.
Example of Array Declaration

// C Program to illustrate the array declaration


#include <stdio.h>

int main()
{

// declaring array of integers


int arr_int[5];
// declaring array of characters
char arr_char[5];

return 0;
}

C Array Initialization
Initialization in C is the process to assign some initial value to the variable. When
the array is declared or allocated memory, the elements of the array contain
some garbage value. So, we need to initialize the array to some meaningful
value. There are multiple ways in which we can initialize an array in C.
1. Array Initialization with Declaration
In this method, we initialize the array along with its declaration. We use an
initializer list to initialize multiple elements of the array. An initializer list is the
list of values enclosed within braces { } separated b a comma.
data_type array_name [size] = {value1, value2, ... valueN};

2. Array Initialization with Declaration without Size


If we initialize an array using an initializer list, we can skip declaring the size of
the array as the compiler can automatically deduce the size of the array in these
cases. The size of the array in these cases is equal to the number of elements
present in the initializer list as the compiler can automatically deduce the size of
the array.
data_type array_name[] = {1,2,3,4,5};

The size of the above arrays is 5 which is automatically deduced by the compiler.
3. Array Initialization after Declaration (Using Loops)
We initialize the array after the declaration by assigning the initial value to each
element individually. We can use for loop, while loop, or do-while loop to assign
the value to each element of the array.
for (int i = 0; i < N; i++) {
array_name[i] = valuei;
}

Example of Array Initialization in C


C

// C Program to demonstrate array initialization


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

// array initialization using initialier list


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

// array initialization using initializer list without


// specifying size
int arr1[] = { 1, 2, 3, 4, 5 };

// array initialization using for loop


float arr2[5];
for (int i = 0; i < 5; i++) {
arr2[i] = (float)i * 2.1;
}
return 0;
}

Access Array Elements


We can access any element of an array in C using the array subscript
operator [ ] and the index value i of the element.
array_name [index];

One thing to note is that the indexing in the array always starts with 0, i.e.,
the first element is at index 0 and the last element is at N – 1 where N is the
number of elements in the array.
Example of Accessing Array Elements using Array Subscript Operator
C

// C Program to illustrate element access using array


// subscript
#include <stdio.h>

int main()
{

// array declaration and initialization


int arr[5] = { 15, 25, 35, 45, 55 };

// accessing element at index 2 i.e 3rd element


printf("Element at arr[2]: %d\n", arr[2]);

// accessing element at index 4 i.e last element


printf("Element at arr[4]: %d\n", arr[4]);

// accessing element at index 0 i.e first element


printf("Element at arr[0]: %d", arr[0]);

return 0;
}

Output
Element at arr[2]: 35
Element at arr[4]: 55
Element at arr[0]: 15

Change an Array Element

To change the value of a specific element, refer to the index number:


Example
myNumbers[0] = 33;

#include <stdio.h>

int main() {
int myNumbers[] = {25, 50, 75, 100};
myNumbers[0] = 33;
printf("%d", myNumbers[0]);

return 0;
}

Loop Through an Array

You can loop through the array elements with the for loop.

The following example outputs all elements in the myNumbers array:

Example
#include <stdio.h>

int main() {
int myNumbers[] = {25, 50, 75, 100};
int i;

for (i = 0; i < 4; i++) {


printf("%d\n", myNumbers[i]);
}

return 0;
}
Output:
25
50
75
100

C Program to find MIN and Max element in an array


#include <stdio.h>
int main() {
int n;
printf("Enter the number of elements in the array: ");
scanf("%d", &n);

if (n <= 0) {
printf("Invalid array size. Please enter a positive integer.\n");
return 1;
}
int arr[n];
printf("Enter the elements of the array:\n");
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
int min = arr[0];
int max = arr[0];

for (int i = 1; i < n; i++) {


if (arr[i] < min) {
min = arr[i];
}
if (arr[i] > max) {
max = arr[i];
}
}

printf("Minimum element: %d\n", min);


printf("Maximum element: %d\n", max);

return 0;
}

C Program for reverse of an array elements

#include <stdio.h>

int main() {
int n;

printf("Enter the number of elements in the array: ");


scanf("%d", &n);
if (n <= 0) {
printf("Invalid array size. Please enter a positive integer.\n");
return 1;
}
int arr[n];

printf("Enter the elements of the array:\n");


for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}

// Reverse the array elements


int temp;
for (int i = 0; i < n / 2; i++) {
temp = arr[i];
arr[i] = arr[n - i - 1];
arr[n - i - 1] = temp;
}

printf("Reversed array elements:\n");


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

return 0;
}

Two Dimensional Array in C

The two-dimensional array can be defined as an array of arrays. The 2D array is


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

Declaration of two dimensional Array in C

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

1. data_type array_name[rows][columns];
Consider the following example.

1. int twodimen[4][3];

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

Initialization of 2D Array in C

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

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

Output

arr[0][0] = 1
arr[0][1] = 2
arr[0][2] = 3
arr[1][0] = 2
arr[1][1] = 3
arr[1][2] = 4
arr[2][0] = 3
arr[2][1] = 4
arr[2][2] = 5
arr[3][0] = 4
arr[3][1] = 5
arr[3][2] = 6
C 2D array example: Storing elements in a matrix and printing it.
1. #include <stdio.h>
2. void main ()
3. {
4. int arr[3][3],i,j;
5. for (i=0;i<3;i++)
6. {
7. for (j=0;j<3;j++)
8. {
9. printf("Enter a[%d][%d]: ",i,j);
10. scanf("%d",&arr[i][j]);
11. }
12. }
13. printf("\n printing the elements ....\n");
14. for(i=0;i<3;i++)
15. {
16. printf("\n");
17. for (j=0;j<3;j++)
18. {
19. printf("%d\t",arr[i][j]);
20. }
21. }
22.}

Output

Enter a[0][0]: 56
Enter a[0][1]: 10
Enter a[0][2]: 30
Enter a[1][0]: 34
Enter a[1][1]: 21
Enter a[1][2]: 34

Enter a[2][0]: 45
Enter a[2][1]: 56
Enter a[2][2]: 78

printing the elements ....

56 10 30
34 21 34
45 56 78
C Program for Matrix multiplication

1. #include<stdio.h>
2. #include<stdlib.h>
3. int main(){
4. int a[10][10],b[10][10],mul[10][10],r,c,i,j,k;
5. system("cls");
6. printf("enter the number of row=");
7. scanf("%d",&r);
8. printf("enter the number of column=");
9. scanf("%d",&c);
10.printf("enter the first matrix element=\n");
11.for(i=0;i<r;i++)
12.{
13.for(j=0;j<c;j++)
14.{
15.scanf("%d",&a[i][j]);
16.}
17.}
18.printf("enter the second matrix element=\n");
19.for(i=0;i<r;i++)
20.{
21.for(j=0;j<c;j++)
22.{
23.scanf("%d",&b[i][j]);
24.}
25.}
26.
27.printf("multiply of the matrix=\n");
28.for(i=0;i<r;i++)
29.{
30.for(j=0;j<c;j++)
31.{
32.mul[i][j]=0;
33.for(k=0;k<c;k++)
34.{
35.mul[i][j]+=a[i][k]*b[k][j];
36.}
37.}
38.}
39.//for printing result
40.for(i=0;i<r;i++)
41.{
42.for(j=0;j<c;j++)
43.{
44.printf("%d\t",mul[i][j]);
45.}
46.printf("\n");
47.}
48.return 0;
49.}

Output:

enter the number of row=3


enter the number of column=3
enter the first matrix element=
111
222
333
enter the second matrix element=
111
222
333
multiply of the matrix=
666
12 12 12
18 18 18

Strings in c

Strings in C language are an array of characters ended with null characters (‘\
0’). The null character at the end of a string indicates its end and the strings
are always enclosed by double quotes. In C language characters are enclosed
by single quotes. Some examples of both of them are shown below.

String functions are usually used to manipulate the strings.

Example or Representation of C Characters and Strings

 char string[10] = { ‘s’,’d’,’f’,’d’,’t’,’j’,’a’,’\0’ };


 char string[10]=” fresher”;
 char string[]=” fresher”;
There is a minor difference between the declarations of the strings in both of
the above statements. Like when we declare char as string[10], 10 bytes of
memory space gets allocated to hold the 10 values of string, while when we
declare it like string[] then memory gets allocated at the time of execution of
the program.
To find the length of any string, manual programming can be done but it could
be a time-consuming task, rather one can use the string functions directly to
save time and effort.

String Declaration and Initialization

In C programming, the strings can be declared in two ways as shown above. In


C programming, a string is a sequence of characters that are terminated with a
null or ‘\0’ character. An example of the same is given below:

char temp[]=” temp string”;

When a string of character is declared of char type that is enclosed in a double


quotation mark, then \0 is automatically appended at the end of the string.
For example –

char temp[]=” temp string”;

t e m p s t r i n g \0

String Declaration

A string in language C is declared in the following manner:

char temp[5];

s[0] s[1] s[2] s[3] s[4]

In this way, we can initialize a string of length 5.

To declare a string in C, a data array should be used because C does not


support string as a data type. While declaring a C string, the size of a variable
must be defined for it to calculate the number of characters going to be stored
inside the string variable in C.
String Initialization

String initialization can be done in many ways and some of them are given
below:
char t[]=” temp string”;
char t[10]=” temp string”;
char t[]={‘t’,’e’,’m’, ‘d’,’\0’};
char t[5]={‘t’,’e’,’m’, ‘d’,’\0’};

T e m p \0

t[0] t[1] t[2] t[3] t[4]

In the above type of declaration, we can only store the strings that have only
four characters. While if you want to store five characters in such string or
array, then you may need the character array of more length.

C language allows initialisation of string variables without defining the string


array. It can be done in the following way –

char color_name [ ] = “BLUE”;

Assigning Values to Strings

Arrays and strings do not support the assignment operators. Once the strings
are declared you cannot assign the values to string-type variables. For
example in C language we cannot write and assign the values in the following
way:

char t[100];

t=” temp value”;

Strings are copied by value, not reference. String assignment happens using
the =operator followed by the copied actual bytes from the operand up
source. The new type string variable can be created by assigning it an
expression of the type string.
List of some Common String Handling Functions in C

Function Description

strlen() Can compute the length of the string

Strcpy() Can copy the content of a string to another

Strcat() Is used to concatenate or join two strings

Strcmp() Can compare two strings

Strlwr() Can convert the string to lowercase

Strupr() Is used to convert the letters of string to uppercase

Strrev() Is used to reverse the string

When you have to use any of the string handling functions in your program,
the functions are not limited only to these many. There are many other string
functions as well. So, let’s discuss them:

1) puts() and gets()

The two popular functions of string header file gets and puts are used to take
the input from the user and display the string respectively.To understand
briefly the working of the string handling functions in c of puts and gets, the
gets() function, allows the ensure to enter characters followed by enter key.
And it also enables the user to add spaced separated strings. Whereas, the
puts() function is also one of the types of strings in C, is used for writing a line
for the output screen. It is similar to the printf() function
Both of these functions are defined in string.h file. Let’s see one example of
these functions:
#include main()
Int main()
{
char temp[20];
printf(“Enter your Name”);
gets(temp);
printf(“My Name is: ”);
puts(temp);
return 0;
}

2) strcat()
For the cases when one string has to be appended at the end of another
string, this function is being used. Function strcat can append a copy of the
source string at the end of the destination string. The strcat() is one of the
string operations in c which concatenates two strings, meaning it joins the
character strings end-to-end. In the strcat() operation, the destination string’s
null character will be overwritten by the source string’s first character, and the
previous null character would now be added at the end of the new destination
string which is a result of stcrat() operation.
The user has to pass two arguments that are described below:
i) src
ii) dest
Here at the place of “src” string is specified, while at the place of ‘dest’ the
destination string in which we have to append the source string is specified.
Example
#include<string.h>
int main()
{
char src[20]= “ before”;
char dest[20]= “after ”;
strcat(dest, src);
puts(dest);
return 0;
}
The output will be: after before
3) Function strlen()
One more function of string header file that can be directly used for the
strings is strlen(). You can use the function strlen(), the string function in C,
when you have to find out the length of any string. The strlen() string
functions in c basically calculate the length of a given string. However, one can
also write a program manually to find out the length of any string, but the use
of this direct function can save your time and the example is given below:
#include<stdio.h>
int main()
{
int length;
char s[20] = “We are Here”;
length=strlen(s);
printf(“\Length of the string is = %d \n”, length);
return 0;
}
Length of the string is = 11

4) Function strcpy()
If you have to copy the content of one string to another string, then this
function is being used. Even the null characters are copied in the process.
Syntax of the function is strcpy(dest,source). The function can copy the
content of one string to another. One example of the function is given below:
#include<string.h>
int main()
{
char src[20]= “ Destination”;
char dest[20]= “”;
printf(“\n source string is = %s”, src);
printf(“\n destination string is = %s”, dest);
strcpy(dest, src);
printf (“\ntarget string after strcpy() = %s”, dest);
return 0;
}
Output
Source string is = Destination
Target string is =
Target string after strcpy() = Destination
5) Function strcmp()
To compare two strings to know whether they are same or not we can use
strcmp() function.This string functions in c, compares two strings. While
comparing the strings takes two parameters into account namely –
1. str1
2. str2
On comparing the return value be determined basis the strings setup as
shown below.
The function returns a definite value that may be either 0, >0, or <0. In this
function, the two values passed are treated as case sensitive means ‘A’ and ‘a’
are treated as different letters. The values returned by the function are used
as:
i) 0 is returned when two strings are the same
ii) If str1<str2 then a negative value is returned
iii) If str1>str2 then a positive value is returned
Example:
#include<stdio.h>
#include<string.h>
int main()
{
char str1[]=”copy”;
char str2[]=”Trophy”;
int I,j,k;
i=strcmp(str1, “copy”);
j=strcmp(str1, str2);
k-strcmp(str1, “f”);
printf(“\n %d %d %d”,I,j,k);
return 0;
}
Output: 0 -1 1

6) Functions strlwr() / strupr()


#include<stdio.h>
#include<string.h>
int main()
{
char str[]=”CONVERT me To the Lower Case”;
printf(“%s\n”, strlwr(str));
return 0;
}
Output: convert me to the lower case

7) Function strrev()
If you want to reverse any string without writing any huge or extensive
program manually, then you can use this function. The rev in the strrev()
stands for reverse and it is used to reverse the given string. Function strrev() is
used to reverse the content of the string. Strrev function is used to check the
nature of the string, whether the given string is a palindrome or not. Several
other uses and applications are also present in the string reverse function.
One of its uses is given below:
#include<stdio.h>
#include<string.h>
int main()
{
char temp[20]=”Reverse”;
printf(“String before reversing is : %s\n”, temp);
printf(“String after strrev() :%s”, strrev(temp));
return 0;
}
Some more String Handling Functions with Purpose:

As we said earlier that there exist more string functions in C. Some other
commonly used functions for string handling in C are:

Function Purpose

strchr() It returns a pointer to the first occurrence of char in str1

strdup() It can duplicate the string

strset() Sets all characters of a string to the given character

strrchr() Used to locate the occurrence of a first pointing character

——- ———————————
Functions in c

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 Declaration

Note: A function in C must always be declared globally before calling it.

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 Definition in C

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.

Working of function in C

// C program to show function


// call and definition
#include <stdio.h>
int sum(int a, int b)
{
return a + b;
}
int main()
{

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.

Function Arguments

Function Arguments (also known as Function Parameters) are the 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
To know more about function Arguments and Return values refer to the article

How Does C Function Work?


Working of the C function can be broken into the following steps as mentioned
below:
1. Declaring a function: Declaring a function is a step where we declare a
function. Here we define the return types and parameters of the function.
2. Defining a function:
3. Calling the function: Calling the function is a step where we call the
function by passing the arguments in the function.
4. Executing the function: Executing the function is a step where we can run
all the statements inside the function to get the final result.
5. Returning a value: Returning a value is the step where the calculated value
after the execution of the function is returned. Exiting the function is the
final step where all the allocated memory to the variables, functions, etc is
destroyed before giving full control to the main function.
Types of Functions
There are two types of functions in C:
1. Library Functions
2. User Defined Functions

Types of Functions in C

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>
int main()
{
double Number;
Number = 49;

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

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 or Call by value mechanism
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;
}
Output
Before swap Value of var1 and var2 is: 3, 2
After swap Value of var1 and var2 is: 3, 2

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

Storage Classes in C

Storage classes in C are used to determine the lifetime, visibility, memory


location, and initial value of a variable. There are four types of storage classes in
C

o Automatic
o External
o Static
o Register

Storage Storage Default Scop Lifetime


Classes Place Value e

auto RAM Garbage Local Within function


Value

extern RAM Zero Global Till the end of the main program
Maybe declared anywhere in the
program

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

register Register Garbage Local Within the function


Value
Automatic

o Automatic variables are allocated memory automatically at runtime.


o The visibility of the automatic variables is limited to the block in which
they are defined.

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

Example 1
1. #include <stdio.h>
2. int main()
3. {
4. int a; //auto
5. char b;
6. float c;
7. printf("%d %c %f",a,b,c); // printing initial default value of automatic variables a,
b, and c.
8. return 0;
9. }

Output:

garbage garbage garbage

Example 2
1. #include <stdio.h>
2. int main()
3. {
4. int a = 10,i;
5. printf("%d ",++a);
6. {
7. int a = 20;
8. for (i=0;i<3;i++)
9. {
10.printf("%d ",a); // 20 will be printed 3 times since it is the local value of a
11.}
12.}
13.printf("%d ",a); // 11 will be printed since the scope of a = 20 is ended.
14.}

Output:

11 20 20 20 11

Static

o The variables defined as static specifier can hold their value between the
multiple function calls.
o Static local variables are visible only to the function or the block in which
they are defined.
o A same static variable can be declared many times but can be assigned at
only one time.
o Default initial value of the static integral variable is 0 otherwise null.
o The visibility of the static global variable is limited to the file in which it
has declared.
o The keyword used to define static variable is static.

Example 1
1. #include<stdio.h>
2. static char c;
3. static int i;
4. static float f;
5. static char s[100];
6. void main ()
7. {
8. printf("%d %d %f %s",c,i,f); // the initial default value of c, i, and f will be printed.

9. }

Output:

0 0 0.000000 (null)
Example 2
1. #include<stdio.h>
2. void sum()
3. {
4. static int a = 10;
5. static int b = 24;
6. printf("%d %d \n",a,b);
7. a++;
8. b++;
9. }
10.void main()
11.{
12.int i;
13.for(i = 0; i< 3; i++)
14.{
15.sum(); // The static variables holds their value between multiple function calls.
16.}
17.}

Output:

10 24
11 25
12 26

Register

o The variables defined as the register is allocated the memory into the CPU
registers depending upon the size of the memory remaining in the CPU.
o We can not dereference the register variables, i.e., we can not use
&operator for the register variable.
o The access time of the register variables is faster than the automatic
variables.
o The initial default value of the register local variables is 0.
o The register keyword is used for the variable which should be stored in
the CPU register. However, it is compiler?s choice whether or not; the
variables can be stored in the register.
o We can store pointers into the register, i.e., a register can store the
address of a variable.
o Static variables can not be stored into the register since we can not use
more than one storage specifier for the same variable.

Example 1
1. #include <stdio.h>
2. int main()
3. {
4. register int a; // variable a is allocated memory in the CPU register. The initial de
fault value of a is 0.
5. printf("%d",a);
6. }

Output:

0
Example 2
1. #include <stdio.h>
2. int main()
3. {
4. register int a = 0;
5. printf("%u",&a); // This will give a compile time error since we can not access th
e address of a register variable.
6. }

Output:

main.c:5:5: error: address of register variable ?a? requested


printf("%u",&a);
^~~~~~

External

o The external storage class is used to tell the compiler that the variable
defined as extern is declared with an external linkage elsewhere in the
program.
o The variables declared as extern are not allocated any memory. It is only
declaration and intended to specify that the variable is declared
elsewhere in the program.
o The default initial value of external integral type is 0 otherwise null.
o We can only initialize the extern variable globally, i.e., we can not initialize
the external variable within any block or method.
o An external variable can be declared many times but can be initialized at
only once.
o If a variable is declared as external then the compiler searches for that
variable to be initialized somewhere in the program which may be extern
or static. If it is not, then the compiler will show an error.

Example 1
1. #include <stdio.h>
2. int main()
3. {
4. extern int a;
5. printf("%d",a);
6. }

Output

main.c:(.text+0x6): undefined reference to `a'


collect2: error: ld returned 1 exit status
Example 2
1. #include <stdio.h>
2. int a;
3. int main()
4. {
5. extern int a; // variable a is defined globally, the memory will not be allocated to
a
6. printf("%d",a);
7. }

Output

0
Recursion

Recursion is the technique of making a function call itself. This technique


provides a way to break complicated problems down into simple problems
which are easier to solve.

Recursion may be a bit difficult to understand. The best way to figure out how it
works is to experiment with it.
Recursion Example
Adding two numbers together is easy to do, but adding a range of numbers is
more complicated. In the following example, recursion is used to add a range of
numbers together by breaking it down into the simple task of adding two
numbers:
Example
#include <stdio.h>
int sum(int k);
int main()
{
int result = sum(10);
printf("%d", result);
return 0;
}

int sum(int k) {
if (k > 0) {
return k + sum(k - 1);
} else {
return 0;
}
}
Output:
55
Number Factorial

The following example calculates the factorial of a given number using a


recursive function

#include <stdio.h>

int fibonacci(int i)
{

if(i == 0)
{
return 0;
}

if(i == 1)
{
return 1;
}
return fibonacci(i-1) + fibonacci(i-2);
}

int main() {

int i;

for (i = 0; i < 10; i++) {


printf("%d\t\n", fibonacci(i));
}

return 0;
}
When the above code is compiled and executed, it produces the following result

0
1
1
2
3
5
8
13
21
34
Factorial Program using recursion in C

Let's see the factorial program in c using recursion.

1. #include<stdio.h>
2.
3. long factorial(int n)
4. {
5. if (n == 0)
6. return 1;
7. else
8. return(n * factorial(n-1));
9. }
10.
11.void main()
12.{
13. int number;
14. long fact;
15. printf("Enter a number: ");
16. scanf("%d", &number);
17.
18. fact = factorial(number);
19. printf("Factorial of %d is %ld\n", number, fact);
20. return 0;
21.}

Output:

Enter a number: 6
Factorial of 5 is: 720

You might also like