C-Arrays & Strings and Functions
C-Arrays & Strings and Functions
C Arrays
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];
int main()
{
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};
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;
}
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
int main()
{
return 0;
}
Output
Element at arr[2]: 35
Element at arr[4]: 55
Element at arr[0]: 15
#include <stdio.h>
int main() {
int myNumbers[] = {25, 50, 75, 100};
myNumbers[0] = 33;
printf("%d", myNumbers[0]);
return 0;
}
You can loop through the array elements with the for loop.
Example
#include <stdio.h>
int main() {
int myNumbers[] = {25, 50, 75, 100};
int i;
return 0;
}
Output:
25
50
75
100
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];
return 0;
}
#include <stdio.h>
int main() {
int n;
return 0;
}
1. data_type array_name[rows][columns];
Consider the following example.
1. int twodimen[4][3];
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
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:
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.
t e m p s t r i n g \0
String Declaration
char temp[5];
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
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.
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];
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
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:
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
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
——- ———————————
Functions in c
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
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
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
Types of Functions in C
1. Library Function
Example:
// C program to implement
// the above approach
#include <math.h>
#include <stdio.h>
int main()
{
double Number;
Number = 49;
#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);
// 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
o Automatic
o External
o Static
o Register
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
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:
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:
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
Output
0
Recursion
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
#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;
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
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