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

Unit 4

The document discusses various concepts related to arrays and strings in C programming language including one dimensional and two dimensional arrays, their declaration, initialization and examples of different patterns that can be created using arrays.

Uploaded by

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

Unit 4

The document discusses various concepts related to arrays and strings in C programming language including one dimensional and two dimensional arrays, their declaration, initialization and examples of different patterns that can be created using arrays.

Uploaded by

mananpatel143414
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

UNIT 4 Array & String

PREPARED BY
PROF. VISHVA UPADHYAY
AHMEDABAD INSTITUTE OF TECHNOLOGY PPS(3110003)

Concepts of array
What is Array?
● An array is defined as the collection of similar types of data items stored at contiguous memory locations. Arrays are the
derived data type in C programming language which can store the primitive type of data such as int, char, double, float, etc.
● It also has the capability to store the collection of derived data types, such as pointers, structure, etc.
● The array is the simplest data structure where each data element can be randomly accessed by using its index number.
● C array is beneficial if you have to store similar elements. For example, if we want to store the marks of a student in 6 subjects,
then we don't need to define different variables for the marks in the different subjects. Instead of that, we can define an array
which can store the marks in each subject at the contiguous memory locations.

Properties of Array
● Each element of an array is of the same data type and carries the same size, i.e., int = 4 bytes.
● Elements of the array are stored at contiguous memory locations where the first element is stored at the smallest memory
location.
● Elements of the array can be randomly accessed since we can calculate the address of each element of the array with the given
base address and the size of the data element.
Advantage of C Array
● Code Optimization: Less code to access the data.
● Ease of traversing: By using the for loop, we can retrieve the elements of an array easily.
● Ease of sorting: To sort the elements of the array, we need a few lines of code only.
● Random Access: We can access any element randomly using the array.
Disadvantage of C Array
● Fixed Size: Whatever size we define at the time of declaration of the array, we can't exceed the limit. So, it doesn't grow the
size dynamically like LinkedList which we will learn later.

One dimensional array:


● We can visualize a one-dimensional array in C as a single row to store the elements. All the elements are stored at contiguous
memory locations.

2
AHMEDABAD INSTITUTE OF TECHNOLOGY PPS(3110003)

Declaration of one dimensional array


● data_type array_name[array_size];
● Now, let us see the example to declare the array.
● int marks[5];
● Here, int is the data_type, marks are the array_name, and 5 is the array_size.

Initialization of one dimensional array


● The simplest way to initialize an array is by using the index of each element. We can initialize each element of the array by
using the index.
Example :
marks[0]=80;//initialization of array
marks[1]=60;
marks[2]=70;
marks[3]=85;
marks[4]=75;

C Program for initializing one dimensional array


#include<stdio.h>
int main()
{
int i=0;
int marks[5];
//declaration of array

marks[0]=80;//initialization of array
marks[1]=60;
marks[2]=70;
marks[3]=85;
marks[4]=75;

3
AHMEDABAD INSTITUTE OF TECHNOLOGY PPS(3110003)

//traversal of array
for(i=0;i<5;i++)
{
printf("%d \n",marks[i]);
}
//end of for loop
return 0;
}
Output
80
60
70
85
75

Declaration with Initialization of one dimensional array


● We can initialize the c array at the time of declaration
int marks[5={20,30,40,50,60}; ]
● In such a case, there is no requirement to define the size.
int marks[]={20,30,40,50,60};

C Program for Declaration of array with initialization of one dimensional array


#include<stdio.h>
int main()
{
int i=0;
int marks[5]={20,30,40,50,60};
//declaration and initialization of array

4
AHMEDABAD INSTITUTE OF TECHNOLOGY PPS(3110003)

//traversal of array
for(i=0;i<5;i++){
printf("%d \n",marks[i]);
}
return 0;
}
Output
20
30
40
50
60

C Program to display the values of array entered by user for one dimensional array
#include <stdio.h>
int main()
{
int num[5];
printf("\n Enter array elements: ");

for (int i = 0; i < 5; i++) {


scanf("%d", &num[i]);
}

printf(" Accessing array elements after dynamic Initialization: ");

for (int i = 0; i < 5; i++) {


printf("%d ", num[i]);

5
AHMEDABAD INSTITUTE OF TECHNOLOGY PPS(3110003)

return 0;
}

Two dimensional array


● 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.

Declaration of two dimensional Array in C


● data_type array_name[rows][columns];
int a[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.
● int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};

Example of Two dimensional array


#include<stdio.h>
int main()
{
int i=0,j=0;

int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
//traversing 2D array

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

6
AHMEDABAD INSTITUTE OF TECHNOLOGY PPS(3110003)

for(j=0;j<3;j++)
{

printf("arr[%d] [%d] = %d \n",i,j,arr[i][j]);

}//end of j
}//end of i
return 0;
}
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

Pattern Examples in C

Example 1: Half Pyramid of *


*
**

7
AHMEDABAD INSTITUTE OF TECHNOLOGY PPS(3110003)

***
****
*****

C Program

#include <stdio.h>
int main()
{
int i, j, rows;
printf("Enter the number of rows: ");
scanf("%d", &rows);

for (i = 1; i <= rows; ++i)


{
for (j = 1; j <= i; ++j)
{
printf("* ");
}
printf("\n");
}
return 0;
}

Example 2: Half Pyramid of Numbers


1
12
123

8
AHMEDABAD INSTITUTE OF TECHNOLOGY PPS(3110003)

1234
12345

C Program
#include <stdio.h>
int main()
{
int i, j, rows;
printf("Enter the number of rows: ");
scanf("%d", &rows);

for (i = 1; i <= rows; ++i)


{
for (j = 1; j <= i; ++j)
{
printf("%d ", j);
}
printf("\n");
}
return 0;
}

Example 3: Half Pyramid of Alphabets


A
BB
CCC
DDDD
EEEEE

9
AHMEDABAD INSTITUTE OF TECHNOLOGY PPS(3110003)

C Program
#include <stdio.h>
int main()
{
int i, j;
char input, alphabet = 'A';
printf("Enter an uppercase character you want to print in the last row: ");
scanf("%c", &input);
for (i = 1; i <= (input - 'A' + 1); ++i)
{
for (j = 1; j <= i; ++j)
{
printf("%c ", alphabet);
}
++alphabet;
printf("\n");
}
return 0;
}

Example 4: Inverted half pyramid of *


*****
****
***
**
*

C Program
#include <stdio.h>

10
AHMEDABAD INSTITUTE OF TECHNOLOGY PPS(3110003)

int main() {
int i, j, rows;
printf("Enter the number of rows: ");
scanf("%d", &rows);
for (i = rows; i >= 1; --i)
{
for (j = 1; j <= i; ++j)
{
printf("* ");
}
printf("\n");
}
return 0;
}

Example 5: Inverted half pyramid of numbers


12345
1234
123
12
1

C Program
#include <stdio.h>
int main() {
int i, j, rows;
printf("Enter the number of rows: ");
scanf("%d", &rows);

11
AHMEDABAD INSTITUTE OF TECHNOLOGY PPS(3110003)

for (i = rows; i >= 1; --i)


{
for (j = 1; j <= i; ++j)
{
printf("%d ", j);
}
printf("\n");
}
return 0;
}

Example 6: Full Pyramid of *


*
***
*****
*******
*********

C Program
#include <stdio.h>
int main()
{
int i, space, rows, k = 0;
printf("Enter the number of rows: ");
scanf("%d", &rows);
for (i = 1; i <= rows; ++i, k = 0)
{
for (space = 1; space <= rows - i; ++space) {
printf(" ");

12
AHMEDABAD INSTITUTE OF TECHNOLOGY PPS(3110003)

}
while (k != 2 * i - 1)
{
printf("* ");
++k;
}
printf("\n");
}
return 0;
}

Example 7: Full Pyramid of Numbers


1
232
34543
4567654
567898765

C Program
#include <stdio.h>
int main()
{
int i, space, rows, k = 0, count = 0, count1 = 0;
printf("Enter the number of rows: ");
scanf("%d", &rows);

for (i = 1; i <= rows; ++i)


{
for (space = 1; space <= rows - i; ++space)

13
AHMEDABAD INSTITUTE OF TECHNOLOGY PPS(3110003)

{
printf(" ");
++count;
}
while (k != 2 * i - 1)
{
if (count <= rows - 1)
{
printf("%d ", i + k);
++count;
} else {
++count1;
printf("%d ", (i + k - 2 * count1));
}
++k;
}
count1 = count = k = 0;
printf("\n");
}
return 0;
}

Example 8: Inverted full pyramid of *


*********
*******
*****
***
*

14
AHMEDABAD INSTITUTE OF TECHNOLOGY PPS(3110003)

C Program
#include <stdio.h>
int main()
{
int rows, i, j, space;
printf("Enter the number of rows: ");
scanf("%d", &rows);

for (i = rows; i >= 1; --i)


{
for (space = 0; space < rows - i; ++space)
printf(" ");
for (j = i; j <= 2 * i - 1; ++j)
printf("* ");
for (j = 0; j < i - 1; ++j)
printf("* ");
printf("\n");
}
return 0;
}

Example 9: Pascal's Triangle


1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1

15
AHMEDABAD INSTITUTE OF TECHNOLOGY PPS(3110003)

C Program
#include <stdio.h>
int main()
{
int rows, val = 1, space, i, j;
printf("Enter the number of rows: ");
scanf("%d", &rows);

for (i = 0; i < rows; i++)


{
for (space = 1; space <= rows - i; space++)
printf(" ");
for (j = 0; j <= i; j++)
{
if (j == 0 || i == 0)
val = 1;
else
val = val * (i - j + 1) / j;
printf("%4d", val);
}
printf("\n");
}
return 0;
}

Example 10: Floyd's Triangle.


1
23
456

16
AHMEDABAD INSTITUTE OF TECHNOLOGY PPS(3110003)

7 8 9 10

C Program
#include <stdio.h>
int main()
{
int rows, i, j, number = 1;
printf("Enter the number of rows: ");
scanf("%d", &rows);

for (i = 1; i <= rows; i++)


{
for (j = 1; j <= i; ++j)
{
printf("%d ", number);
++number;
}
printf("\n");
}
return 0;
}

C Program for matrix addition in 2-d array


#include<stdio.h>
void main()
{
int a[3][3], b[3][3], c[3][3];
int i,j;

17
AHMEDABAD INSTITUTE OF TECHNOLOGY PPS(3110003)

printf("\nEnter Matrix1: \n");


for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
scanf("%d", &a[i][j]);
}
}
printf("\nEnter Matrix2: \n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
scanf("%d", &b[i][j]);
}
}
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
c[i][j] = a[i][j] + b[i][j];
}
}
printf("\nMatrix Addition: \n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("%d\t", c[i][j]);

18
AHMEDABAD INSTITUTE OF TECHNOLOGY PPS(3110003)

}
printf("\n");
}
}

Output :
Enter Matrix1:
123
456
789

Enter Matrix2:
11 12 13
14 15 16
17 18 19

Matrix Addition:
12 14 16
18 20 22
24 26 28
C Program for matrix multiplication in 2-d array

#include<stdio.h>
#include<stdlib.h>
int main(){
int a[10][10],b[10][10],mul[10][10],r,c,i,j,k;
printf("enter the number of row=");
scanf("%d",&r);
printf("enter the number of column=");

19
AHMEDABAD INSTITUTE OF TECHNOLOGY PPS(3110003)

scanf("%d",&c);
printf("enter the first matrix element=\n");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("enter the second matrix element=\n");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
scanf("%d",&b[i][j]);
}
}

printf("multiply of the matrix=\n");


for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
mul[i][j]=0;
for(k=0;k<c;k++)
{
mul[i][j]+=a[i][k]*b[k][j];
}
}

20
AHMEDABAD INSTITUTE OF TECHNOLOGY PPS(3110003)

}
//for printing result
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
printf("%d\t",mul[i][j]);
}
printf("\n");
}
return 0;
}
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

String in C

21
AHMEDABAD INSTITUTE OF TECHNOLOGY PPS(3110003)

● The string can be defined as the one-dimensional array of characters terminated by a null ('\0').
● The character array or the string is used to manipulate text such as words or sentences. Each character in the array occupies
one byte of memory, and the last character must always be 0.
● The termination character ('\0') is important in a string since it is the only way to identify where the string ends.
● When we define a string as char s[10], the character s[10] is implicitly initialized with the null in the memory.
● The difference between a character array and a string is the string is terminated with a special character ‘\0’.

Declaration of strings:
● char str_name[size];
Example :
char s[5];
char str[200];
Initializing a String:
char c[] = "abcd";

char c[50] = "abcd";


char c[] = {'a', 'b', 'c', 'd', '\0'};
char c[5] = {'a', 'b', 'c', 'd', '\0'};

Using String in the program

#include <stdio.h>
int main()
{
char z[100] = "I am learning C programming language.";
printf("%s", z); // %s is format specifier
return 0;
}

22
AHMEDABAD INSTITUTE OF TECHNOLOGY PPS(3110003)

Output:
I am learning C programming language.

difference between scanf and gets

scanf()
● It is used to read the input(character, string, numeric data) from the standard input(keyboard).
● It is used to read the input until it encounters a whitespace, newline or End Of File(EOF).
For example see the following code

// C program to see how scanf()


// stops reading input after whitespaces

#include <stdio.h>
int main()
{
char str[20];
printf("enter something\n");
scanf("%s", str);
printf("you entered: %s\n", str);

return 0;
}

Here the input will be provided by the user and output will be as follows:
Input: Computer science
Output: Computer

23
AHMEDABAD INSTITUTE OF TECHNOLOGY PPS(3110003)

gets
● It is used to read input from the standard input(keyboard).
● It is used to read the input until it encounters a newline or End Of File(EOF).

// C program to show how gets()


// takes whitespace as a string.

#include <stdio.h>
int main()
{
char str[20];
printf("enter something\n");
gets(str);
printf("you entered : %s\n", str);
return 0;
}

Here input will be provided by user as follows


Input: Computer science
Output: Computer science

scanf() gets()

when scanf() is used to read when gets() is used to read input it stops reading
string input it stops reading when input when it encounters newline or End Of File. It
it encounters whitespace, newline does not stop reading the input on encountering
or End Of File whitespace as it considers whitespace as a string.

24
AHMEDABAD INSTITUTE OF TECHNOLOGY PPS(3110003)

It is used to read input of any


It is used only for string input.
datatype

Its syntax is -: Its syntax is -:


scanf(const char *format, …) char *gets(char *str)

It takes one parameter that is the pointer to an array


It is fast to take input.
of chars

Format specifiers are used inside


Its return value is str on success else NULL
scanf to take input.

Difference between printf and puts()

printf() puts()

It is used to display all types of data It is used to display only string data and
and messages. messages.

It requires a format specifier to display It does not require a format specifier to display
formatted data. string.

It can display multiple data at a time by It is used to display only one string at a time.
multiple format specifiers in one printf(
).

Syntax: Syntax:
● puts(variable);

25
AHMEDABAD INSTITUTE OF TECHNOLOGY PPS(3110003)

● printf(“list of format specifier or


message”, list of variables);

String In-built Function in c


Function Description

strlen(string_name) returns the length of the string name.

strcpy(destination, source) copies the contents of source string to destination string.

strcat(first_string, concats or joins first string with second string. The result of the string
second_string) is stored in the first string.

strcmp(first_string, compares the first string with the second string. If both strings are the
second_string) same, it returns 0.

strrev(string) returns reverse string.

strlwr(string) returns string characters in lowercase.

strupr(string) returns string characters in uppercase.

Strlen()
#include<stdio.h>
#include <string.h>
int main(){
char ch[20]={'c', 'o', 'm', 'p', 'u', 't', 'e', 'r','\0'};

26
AHMEDABAD INSTITUTE OF TECHNOLOGY PPS(3110003)

printf("Length of string is: %d",strlen(ch));


return 0;
}
Output:
Length of string is: 8
Strcpy()
#include<stdio.h>
#include <string.h>
int main(){
char ch[20]={'c', 'o', 'm', 'p', 'u', 't', 'e', 'r','\0'};
char ch2[20];
strcpy(ch2,ch);
printf("Value of second string is: %s",ch2);
return 0;
}
Output:
Value of second string is: computer

Strcat()
#include<stdio.h>
#include <string.h>
int main(){
char ch[10]={'h', 'e', 'l', 'l', 'o', '\0'};
char ch2[10]={'c', '\0'};
strcat(ch,ch2);
printf("Value of first string is: %s",ch);
return 0;
}
Output:

27
AHMEDABAD INSTITUTE OF TECHNOLOGY PPS(3110003)

Value of first string is: helloc

Strcmp()
#include<stdio.h>
#include <string.h>
int main(){
char str1[20],str2[20];
printf("Enter 1st string: ");
gets(str1);//reads string from console
printf("Enter 2nd string: ");
gets(str2);
if(strcmp(str1,str2)==0)
printf("Strings are equal");
else
printf("Strings are not equal");
return 0;
}
Output:
Enter 1st string: hello
Enter 2nd string: hello
Strings are equal

Strrev()
#include<stdio.h>
#include <string.h>
int main(){
char str[20];
printf("Enter string: ");
gets(str);//reads string from console

28
AHMEDABAD INSTITUTE OF TECHNOLOGY PPS(3110003)

printf("String is: %s",str);


printf("\nReverse String is: %s",strrev(str));
return 0;
}
Output:
Enter string:computer
String is:computer
Reverse String is:retupmoc

Strlwr()
#include<stdio.h>
#include <string.h>
int main(){
char str[20];
printf("Enter string: ");
gets(str);//reads string from console
printf("String is: %s",str);
printf("\nLower String is: %s",strlwr(str));
return 0;
}
Output:
Enter string: COMPUTER
String is: COMPUTER
Lower String is: computer

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

29
AHMEDABAD INSTITUTE OF TECHNOLOGY PPS(3110003)

char str[20];
printf("Enter string: ");
gets(str);//reads string from console
printf("String is: %s",str);
printf("\nUpper String is: %s",strupr(str));
return 0;
}
Output:
Enter string: computer
String is: computer
Upper String is: COMPUTER

30

You might also like