0% found this document useful (0 votes)
15 views

C lecture 3.1

The document provides a comprehensive overview of arrays in C programming, including their types (1D and 2D), declaration, initialization, and memory allocation. It also covers strings, their declaration, and various string manipulation functions available in the C standard library. Additionally, it includes example programs for practical applications of arrays and strings.

Uploaded by

devlina.karmakar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

C lecture 3.1

The document provides a comprehensive overview of arrays in C programming, including their types (1D and 2D), declaration, initialization, and memory allocation. It also covers strings, their declaration, and various string manipulation functions available in the C standard library. Additionally, it includes example programs for practical applications of arrays and strings.

Uploaded by

devlina.karmakar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

Array: An array is a group (or collection) of same data types.

For example an int array holds the elements of int types


while a float array holds the elements of float types.

Necessity of array: Consider a scenario where you need to find out the average of 100 integer numbers entered by
user. In C, you have two ways to do this: 1) Define 100 variables with int data type and then perform 100 scanf()
operations to store the entered values in the variables and then at last calculate the average of them. 2) Have a single
integer array to store all the values, loop the array to store all the entered values in array and later calculate the
average.
Obviously the second solution is better, it is convenient to store same data types in one single variable and later access
them using array index.

Example: int student[10]; represents the collection of 10 students, while the complete set of values is referred to as
an array, the individual values are called elements. Arrays can be of any variable type. A particular value is indicated
by writing a number called index number or subscript in brackets after the array name.
Declaration of array:
int num[35]; /* An integer array of 35 elements */
char ch[10]; /* An array of characters for 10 elements */
Similarly an array can be of any data type such as double, float, short etc.
We can use array subscript (or index) to access any element stored in array. Subscript starts with 0, which
means arr[0] represents the first element in the array . In general student[n-1] can be used to access nth element of an
array. where n is any integer number.
1D Array: a list of items can be given one variable name using only one subscript and such a variable is called ingle
subscripted variable or one-dimensional array. To calculate the average of n numbers, 1D array is used, its subscript
can begin with number 0.
Memory allocation: let, 5 numbers need to be represented:{35,10,24,60,7}, in memory their location be like:

35 10 24 60 7

num[0] num[1] num[ 2] num[3] num[4]


num[] is the array name.
Initialization of array:
Syntax: static int number[3]={15,14,32};
static float num[3]={1.5,-20.4,15.75};
Example of 1D array:
#include<stdio.h>
int main()
{
int arr[5], i;
for(i = 0; i < 5; i++)
{
printf("Enter a[%d]: ", i);
scanf("%d", &arr[i]);
}
printf("\nPrinting elements of the array: \n\n");
for(i = 0; i < 5; i++)
{
printf("%d ", arr[i]);
}
return 0;
}
WAP to take positive & negative numbers in an array, then print the sum of positive & negative numbers
separately.
WAP to take 7 elements in an array and calculate their sum.
WAP to find the maximum and minimum element in an array.
WAP to calculate the sum of Fibonacci series using 1D array.
WAP to check prime numbers in an array.
WAP to calculate sum and product of all elements in an 1D array.
WAP to reverse all the elements in array.
2D array:
An array of arrays is known as 2D array. The two dimensional (2D) array in C programming is also known as matrix. A matrix can be represented as a table
of rows and columns.
Initialization of 2D array: There are two ways to initialize a two Dimensional arrays during declaration.
int disp[2][4] = {
{10, 11, 12, 13},
{14, 15, 16, 17}
}; or
int disp[2][4] = { 10, 11, 12, 13, 14, 15, 16, 17};

For 2D array, we must always specify the second dimension even if we are specifying elements during the declaration.
/* Valid declaration*/
int abc[2][2] = {1, 2, 3 ,4 }
/* Valid declaration*/
int abc[][2] = {1, 2, 3 ,4 }
/* Invalid declaration – you must specify second dimension*/
int abc[][] = {1, 2, 3 ,4 }
/* Invalid because of the same reason mentioned above*
/ int abc[2][] = {1, 2, 3 ,4 }
Example: 2D array memory representation:
#include<stdio.h>
int main()
{
/* 2D array declaration*/
int abc[5][4];
/*Counter variables for the loop*/
int i, j;
for(i=0; i<5; i++)
{
for(j=0;j<4;j++)
{
printf("Enter value for abc[%d][%d]:", i, j);
scanf("%d", &abc[i][j]);
}
}
return 0;
}
Multidimensional array: C programming language allows multidimensional arrays. Here is the general form of a
multidimensional array declaration −
type name[size1][size2]...[sizeN];
For example: int threedim[5][10][4];

WAP to calculate sum of 2 number of 2D array.


WAP to calculate Sum of even and odd of Two Dimensional Array.
WAP to find out transpose of a matrix.
WAP to print a matrix diagonally.
String:
A String in C is nothing but a collection of characters in a linear sequence. 'C' always treats a string a single data even though
it contains whitespaces. A single character is defined using single quote representation. A string is represented using double
quote marks.
Example: "Welcome to the world of programming!“
'C' provides standard library <string.h> that contains many functions which can be used to perform complicated operations
easily on Strings in C.
Declaration of string in C:
A C String is a simple array with char as a data type. 'C' language does not directly support string as a data type.
The general syntax for declaring a variable as a String in C is as follows:
char string_variable_name [array_size];
The classic Declaration of strings can be done as follow:
char string_name[string_length] = "string";
The size of an array must be defined while declaring a C String variable because it is used to calculate how many characters are
going to be stored inside the string variable in C.
char first_name[15]; //declaration of a string variable
char last_name[15]; // The indexing of array begins from 0 hence it will store characters from a 0-14 position.
Example:
#include <stdio.h>
int main()
{
char name[10];
int age;
printf("Enter your first name and age: \n");
scanf("%s %d", name, &age);
printf("You entered: %s %d",name,age);
}
In order to read a string contains spaces, we use the gets() function. Gets ignores the whitespaces. It stops reading when a newline is reached
#include <stdio.h>
int main()
{
char full_name[25];
printf("Enter your full name: ");
gets(full_name);
printf("My full name is %s ",full_name);
return 0;
}
fputs() function: The fputs() needs the name of the string and a pointer to where you want to display the text. We use stdout which refers to the standard output in order
to print to the screen.
For example:
#include <stdio.h>
int main()
{
char town[40];
printf("Enter your town: ");
gets(town);
fputs(town, stdout);
return 0;
}
puts function: The puts function is used to Print string in C on an output device and moving the cursor back to the first position.
#include <stdio.h>
int main()
{
char name[15];
gets(name); //reads a string
puts(name); //displays a string
return 0;
}
String Functions: The standard 'C' library provides various functions to manipulate the strings within a program.
These functions are also called as string handlers. All these handlers are present inside <string.h> header file.

Function Purpose

strlen() This function is used for finding a length of a


string. It returns how many characters are
present in a string excluding the NULL
character.

strcat(str1, str2) This function is used for combining two strings


together to form a single string. It Appends or
concatenates str2 to the end of str1 and returns a
pointer to str1.

strcmp(str1, str2) This function is used to compare two strings


with each other. It returns 0 if str1 is equal to
str2, less than 0 if str1 < str2, and greater than 0
if str1 > str2.
strcpy(str1,str2) This function is used to copy two strings with
each other.
strlen() function:
The strlen() function in C is used to calculate the length of a string.
Example:
int main()
{
int len1, len2; //initializing the strings
char string1[] = "Hello";
char string2[] = {'c','o','m','p','u','t','e','r','\0'}; //calculating the length of the two strings
len1 = strlen(string1);
len2 = strlen(string2); //displaying the values
printf("Length of string1 is: %d \n", len1);
printf("Length of string2 is: %d \n", len2);
return 0;
}
Strcpy() function: it is used to copy one string to another.
Example:
#include<stdio.h>
#include<string.h>
int main ()
{
char str1[]="Hello!";
char str2[] = “welcome";
char str3[40];
char str4[40];
char str5[] = “WOW";
strcpy(str2, str1);
strcpy(str3, "Copy successful");
strcpy(str4, str5);
printf ("str1: %s\nstr2: %s\nstr3: %s\nstr4:
%s\n", str1, str2, str3, str4);
return 0;
}
Strcmp() function: this is used to compare between two strings.
Example:
#include <stdio.h>
#include <string.h>
int main()
{
char str1[] = "abcd", str2[] = "abCd", str3[] = "abcd";
int result; // comparing strings str1 and str2
result = strcmp(str1, str2);
printf("strcmp(str1, str2) = %d\n", result); // comparing strings str1 and str3
result = strcmp(str1, str3);
printf("strcmp(str1, str3) = %d\n", result);
return 0;
}
strcat() funtion: it merges two strings.
Example:
#include <stdio.h>
#include <string.h>
int main ()
{
char src[50], dest[50];
strcpy(src, "This is source");
strcpy(dest, "This is destination");
strcat(dest, src);
printf("Final destination string : |%s|", dest);
return 0;
}

You might also like