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

unit 4 fpl

Uploaded by

uzair63210
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)
239 views

unit 4 fpl

Uploaded by

uzair63210
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
You are on page 1/ 25

FPL Unit-IV DIT,

Pimpri

Dr. D. Y. PATIL INSTITUTE OF TECHNOLOGY, PIMPRI, PUNE-


18
Department of First Year Engineering
Fundamentals of Programming Languages
Unit- 4: ARRAYS

Syllabus:
Arrays: One Dimensional Arrays, Declaration of One-dimensional Arrays,
Initialization of One- dimensional Arrays, Two –dimensional Arrays, Initialization of
Two- dimensional Arrays.
Character Arrays and Strings: Declaration and Initialization String Variables,
Reading Strings from Terminal, Writing Strings to Screen, Putting Strings Together,
Comparison of Two Strings, Introduction to String handling Functions

Introduction
Arrays in C are a kind of data structure that can store a fixed-size sequential collection
of elements of the same data type. Arrays are used to store a collection of data, but it is
often more useful to think of an array as a collection of variables of the same type.
Examples:
 List of employees in an organization
 List of products and their cost sold by a store
 Score of class of the students
 List of customers and their address

Types of Arrays in C
There are two array types in C based on the number of dimensions.

 One-dimensional Arrays (1-D Array)

 Multi-Dimensional Array (2-D Array,3-D Array)

Here is an explanation of both array types in C:

1. One-dimensional Arrays in C
Also known as 1-D arrays or vectors, the one-dimensional arrays in C language have
just one dimension. They are represented by a single row or column.

Declaration of 1-D Arrays

type variable_name [size];

1
FPL Unit-IV DIT,
Pimpri

eg: float height[30];


char name[40];

Fig: 1D-Array
Initialization of One-Dimensional Arrays
After an array is declared, its elements must be initialized. An array can be initialized
at either of the following stages:
 At compile time
 At run time
Compile Time Initialization
When an array is declared, it can be initialized. This is also referred to as initialization
at build time.
When an array is declared, its elements can be initialized in the same manner as
regular variables. Initializing an array often has the following form or syntax:
type array_name[size]={list of values};
Example:

 //integer array initialization


int rollnumbers[4]={ 2, 5, 6, 7};
 //float array initialization
float area[5]={ 23.4, 6.8, 5.5,7.3,2.4 };
 //character array initialization
char name[9]={ 'T', 'u', 't', 'o', 'r', 'i', 'a', 'l', '\0' };

C Program to illustrate Compile-Time Initialization:

#include <stdio.h>
int main(){
int nums[3]={0,1,2};
printf(" Compile-Time Initialization Example:\n");
2
FPL Unit-IV DIT,
Pimpri

printf(" %d ",nums[0]);
printf("%d ",nums[1]);
printf("%d ",nums[2]);
}
Output:
012

Run Time Compilation


Using runtime initialization user can get a chance of accepting or entering different
values during different runs of program. An array can also be initialized at runtime
using scanf() function.
Runtime initialization is also known as dynamic-initialization. Array elements are
initialized at the runtime after successfully compiling the program.

Example:

scanf("%d", &nums[0]); //initializing 0th index element at runtime dynamically

C Program to illustrate Run-Time Initialization:


#include < stdio.h >
int main() {
int nums[5];
printf("\n Run-Time Initialization Example:\n");
printf("\n Enter array elements: ");
for (int i = 0; i < 5; i++) {
scanf("%d", & nums[i]);
}
printf(" Accessing array elements after dynamic Initialization: ");
for (int i = 0; i < 5; i++) {
printf("%d ", nums[i]);
}
return 0;
}

Input
Run-Time Initialization Example:
Enter array elements: 10 20 30 40 50
Output:
Accessing array elements after dynamic Initialization: 10 20 30 40 50

3
FPL Unit-IV DIT,
Pimpri

2. Multi-dimensional Arrays in C
Dimension of an array refers to a particular direction in which array elements can be
varied. An array with a single dimension is known as a one dimensional array. An
array that has a dimension greater than one, is known as a multidimensional array.

 Two-Dimensional Arrays in C

Two Dimensional Arrays can be thought of as an array of arrays, or as a matrix


consisting of rows and columns. A 2D array is also known as a matrix (a table of rows
and columns).
To create a 2D array of integers, take a look at the following example:
int matrix[2][3] = { {1, 4, 2}, {3, 6, 8} };

Following is an example of a 2D array:

This array has 2 rows and 3 columns.


Two dimensional array in C, will follow zero-based indexing, like all other arrays in
C.
They have two dimensions and can be visualized in rows and columns organized in a
two-dimensional plane. 2-D arrays are declared as follows:

type array_name [row_size] [column_size];


Initialization of Two Dimensional Arrays using Initializer List
Initializer list have two methods to declare the two dimensional array in C.

First Method
In the first method we can write all the elements together as shown in the below
example.
int a[4][3] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};

Second Method
This method is comparatively better as we have clearly specified the elements in each
row. Look at the example shown below.
int a[4][3] = {{0, 1, 2}, {3, 4, 5}, {6, 7, 8}, {9, 10, 11}};
In the above example we have nested brackets which shows the element of each row
individually.

Initialization of Two Dimensional Array in C using Loop


Declare the array as normal after that we can initialize them with the help of loops.

Example of two-dimensional array in C


4
FPL Unit-IV DIT,
Pimpri

Let’s understand this better with the help of an example.


int a[m][n];

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


for(int j = 0; j < n; j++){
x[i][j] = i * j + 1;
}
}
In the above example we have declared the array with of size m x n and we have
initialized it by using loops.

 Three-Dimensional Arrays in C
3-D arrays have three dimensions and can be visualized as a collection of 2-D arrays
organized one on the other to create a third dimension.
Syntax of 3-D Array

array_name [size1] [size2] [size3];

Array Practice Programs


Array is a collection of homogenous data, arranged in sequential format.

1D Array Programs

These programs involves only a single array variable.

1. Program to print an array


2. Program to print an array in reverse order
3. Program to calculate sum of an array
4. Program to calculate average of an array
5. Program to find the largest element of an array
6. Program to find the smallest element of an array

Program to print an Array


Algorithm
Step-by-step procedure of this program −

START
Step 1 → Take an array A and define its values
Step 2 → Loop for each value of A
Step 3 → Display A[n] where n is the value of current iteration
STOP

5
FPL Unit-IV DIT,
Pimpri

Source Code
#include <stdio.h>
int main() {
int array[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
int i;

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


printf("%d ", array[i]);
return 0;
}

The output is like this −

1234567890

Program to print reverse array

Algorithm
Step-by-step procedure of this program −
START
Step 1 → Take an array A and define its values
Step 2 → Loop for each value of A in reverse order
Step 3 → Display A[n] where n is the value of current iteration
STOP

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

The output is like this −

0987654321

Program to calculate sum of array

6
FPL Unit-IV DIT,
Pimpri

Algorithm
Step-by-step procedure of this program −

START
Step 1 → Take an array A and define its values
Step 2 → Loop for each value of A
Step 3 → Add each element to 'sum' variable
Step 4 → After the loop finishes, display 'sum'
STOP

Source Code
#include <stdio.h>
int main() {
int array[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
int sum, i;
sum = 0;
for(i = 9; i >= 0; i--) {
sum = sum + array[i];
}
printf("Sum of array is %d.", sum);
return 0;
}

The output should look like this −

Sum of array is 45.

Program to print array in C


Algorithm
Step-by-step procedure of this program −

START
Step 1 → Take an array A and define its values
Step 2 → Loop for each value of A
Step 3 → Display A[n] where n is the value of current iteration
STOP

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

7
FPL Unit-IV DIT,
Pimpri

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


int i;

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


printf("%d ", array[i]);
return 0;
}

The output is look like this −

1234567890

Program to calculate average of array


Algorithm
Step-by-step procedure of this program −

START
Step 1 → Take an array A and define its values
Step 2 → Loop for each value of A
Step 3 → Add each element to 'sum' variable
Step 4 → After loop finishes, divide sum with number of array elements
Step 5 → Store that result to avg variable and display.
STOP

Source Code
#include <stdio.h>
int main() {
int array[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
int sum, i;
float avg;

sum = avg = 0;

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


sum = sum + array[i];
}
avg = (float)sum / loop;
printf("Average of array values is %.2f", avg);
return 0;
}

The output is like this −


8
FPL Unit-IV DIT,
Pimpri

Average of array values is 4.50

Program to find largest element in array

Algorithm
Step-by-step procedure of this program −
START
Step 1 → Take an array A and define its values
Step 2 → Declare largest as integer
Step 3 → Set 'largest' to 0
Step 4 → Loop for each value of A
Step 5 → If A[n] > largest, Assign A[n] to largest
Step 6 → After loop finishes, Display largest as largest element of array
STOP

Source Code
#include <stdio.h>
int main() {
int array[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
int i, largest;

largest = array[0];

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


if( largest < array[i] )
largest = array[i];
}
printf("Largest element of array is %d", largest);
return 0;
}

The output is like this −

Largest element of array is 9

Program to find smallest element in array


Algorithm
Step-by-step procedure of this program −

START
9
FPL Unit-IV DIT,
Pimpri

Step 1 → Take an array A and define its values


Step 2 → Declare smallest as integer
Step 3 → Set smallest to 0
Step 4 → Loop for each value of A
Step 5 → If A[n] < smallest, Assign A[n] to smallest
Step 6 → After loop finishes, Display smallest as smallest element of array
STOP

Source Code
#include <stdio.h>
int main() {
int array[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
int i, smallest;

smallest = array[0];

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


if( smallest > array[i])
smallest = array[i];
}
printf("Smallest element of array is %d", smallest);
return 0;
}

The output is like this −

Smallest element of array is 0

2D Array Programs
Creating a Matrix in C Programming Language
1. Using an Array

#include <stdio.h>
int main() {
int matrix[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
printf("Matrix created using an array:\n");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
10
FPL Unit-IV DIT,
Pimpri

}
return 0;
}

Output
Matrix created using an array:
123
456
789

Example: Addition of two matrices of size 3x3:


#include <stdio.h>
int main() {
int a[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int b[3][3] = {{9, 8, 7}, {6, 5, 4}, {3, 2, 1}};
int c[3][3];
int i, j;
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
c[i][j] = a[i][j] + b[i][j];
}
}
printf("Result of addition: \n");
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
printf("%d ", c[i][j]);
}
printf("\n");
}
return 0;
}

Output

Result of addition:
10 10 10
10 10 10
10 10 10

11
FPL Unit-IV DIT,
Pimpri

Example: Multiplication of two matrices


#include<stdio.h>
int main()
{
int a[5][5],b[5][5],m[5][5];
int i,j,r,c,t,k;
printf("\nEnter No of Rows : ");
scanf("%d",&r);
printf("\nEnter No of Columns : ");
scanf("%d",&c);
printf("\nEnter A Matrix : ");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
scanf("%d",&a[i][j]);
}
}
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
printf("\t%d",a[i][j]);
}
printf("\n");
}
printf("\nEnter B Matrix : ");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
scanf("%d",&b[i][j]);
}
}
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
printf("\t%d",b[i][j]);
}
printf("\n");
}
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
12
FPL Unit-IV DIT,
Pimpri

t=0;
for(k=0;k<c;k++)
{
t+=(a[i][k]*b[k][j]);
}
m[i][j]=t;
}
}
printf("\nResult Matrix : \n");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
printf("\t%d",m[i][j]);
}
printf("\n");
}
return 0;
}

Output
Enter No of Rows: 2
Enter No of Columns: 2
Enter A Matrix: 2
3
4
5

2 3
4 5

Enter B Matrix: 5
6
7
8

5 6
7 8
Result Matrix:
31 36
55 64

Character Array and String in C

13
FPL Unit-IV DIT,
Pimpri

What is Character Array in C?


 A Character array is a derived data type in C that is used to store a collection of
characters or strings.
 Each character in a character array has an index that shows the position of the
character in the string.
 The first character will be indexed 0 and the successive characters are indexed
1, 2, 3 etc...
 The null character \0 is used to find the end of characters in the array and is
always stored in the index after the last character or in the last index.
Consider a string "character", it is indexed as the following image in a character array.

Syntax
There are many syntaxes for creating a character array in c. The most basic syntax is,
char name[size];

 The name depicts the name of the character array and size is the length of the
character array.
 The size can be greater than the length of the string but cannot be lesser. If it is
lesser then the full string can't be stored and if it is greater the remaining spaces
are just left unused.

Initialization of Character Array in C


There are different ways to initialize a character array in c. Let us understand them
with examples.
Using {} Curly Braces
 We can use {} brackets to initialize a character array by specifying the
characters in the array.
 The advantage of using this method is we don't have to specify the length of
the array as the compiler can find it for us.
Let us see a example where we initialize an array using {} and print it.

#include <stdio.h>
#include<string.h>
int main(){
//initialization
char char_array[] = {'c', 'h', 'a', 'r', '$','*'};
14
FPL Unit-IV DIT,
Pimpri

int a=puts(char_array); //print array


if(a>0){
printf("printed successfully\n");
}
printf("length of character array = %d",strlen(char_array));
//prints length of the character array.
return 0;
}

Output
char$*
printed successfully
length of character array = 6

What is the Use of Char Array in C?


 A string is stored and represented using a character array.
 Every string operation such as copying two strings or concatenating two strings
is done only using the character array.
 We can individually access every character in an array using the character
array.
 Writing and reading from files also use character arrays.

Importance of Char Array


 Character array is used to store and manipulate characters.
 File systems and text editors use character arrays to manipulate strings.
 Character array is used in language processing software and speech-to-text
software.
 It is used in DNA matching and genome matching as pattern matching can be
easily done using characters.

String
String is a sequence of characters that are treated as a single data item and terminated
by a null character '\0'. Remember that the C language does not support strings as a
data type. A string is actually a one-dimensional array of characters in C language.
These are often used to create meaningful and readable programs.

For example: The string "home" contains 5 characters including the '\0' character
which is automatically added by the compiler at the end of the string.

15
FPL Unit-IV DIT,
Pimpri

Declaring and Initializing a string variables:

How to declare a string?

char s[5];

How to initialize strings?

String Input and Output:

 %s format specifier to read a string input from the terminal.


 But scanf() function, terminates its input on the first white space it encounters.

16
FPL Unit-IV DIT,
Pimpri

 The gets() function can also be used to read character string with white
spaces

char str[20];
printf("Enter a string");
scanf("%[^\n]", &str);
printf("%s", str);

Read String from the user


 Use the scanf () function to read a string.
 The scanf () function reads the sequence of characters until it
encounters whitespace (space, newline, tab, etc.).

Example 1: scanf () to read a string

#include <stdio.h>
int main()
{
char name[20];
printf("Enter name: ");
scanf("%s", name);
printf("Your name is %s.", name);
return 0;
}

Output

Enter name: Dennis Ritchie


Your name is Dennis

Example 2: Reading a line of text from the user.


The C language offers a function fgets () that can read an entire line of string,
including the whitespaces.

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

17
FPL Unit-IV DIT,
Pimpri

char name[20];

printf("Enter your name: ");


//read string
scanf("%s", name)
//display string
printf("Your name is %s.", name);

return 0;
}

String Handling Functions


C language supports a large number of string handling functions that can be used to
carry out many of the string manipulations. These functions are packaged in
the string.h library.
Hence, we must include string.h header file in your programs to use these functions.
The following are the most commonly used string handling functions.

In C programming language, several string functions can be used to manipulate


strings. To use them, you must include the <string.h> header file in your program.
Here are some of the commonly used string functions in C:
 strlen(): This function is used to find the length of a string. It takes a string
as input and returns the number of characters in the string (excluding the null
character).

18
FPL Unit-IV DIT,
Pimpri

 strcpy(): This function is used to copy one string to another. It takes two
arguments, the first argument is the destination string where the source string
will be copied and the second argument is the source string.
 strcat(): This function is used to concatenate two strings. It takes two
arguments, the first argument is the destination string where the source string
will be appended and the second argument is the source string.
 strcmp(): This function is used to compare two strings. It takes two
arguments, the first argument is the first string and the second argument is the
second string. It returns an integer value that indicates the result of the
comparison.
 strrev(): This function reverses a given string. It is a built-in function that is
defined in the string.h header file. The function takes a string as input and
modifies the original string by reversing it.

Example: strlen() function

#include <stdio.h>
#include <string.h>
int main()
{
char a[20]="Program";
char b[20]={'P','r','o','g','r','a','m','\0'};

// using the %zu format specifier to print size_t


printf("Length of string a = %zu \n",strlen(a));
printf("Length of string b = %zu \n",strlen(b));

return 0;
}

Output

Length of string a = 7
Length of string b = 7

Note that the strlen() function doesn't count the null character \0 while calculating the
length.

19
FPL Unit-IV DIT,
Pimpri

strcat() function in C:

Syntax of strcat() Function in C


strcat(dest,src);

The strcat function in C programming language takes two parameters:

 destination: This is a pointer to the string where the concatenated string is to be


stored. It should have enough memory allocated to store the concatenated string. The
destination string is modified by the function.

 source: This is a pointer to the string that is to be concatenated. It is the string that will
be appended to the destination string. The source string is not modified by the
function. It is specified as a constant pointer to indicate that the function will not
modify the source string.

Example: strcat() Function

Example 1: Putting Strings together/Concatenating two strings


#include <stdio.h>
#include <string.h>
int main() {
char str1[50] = "Hello, ";
const char str2[] = "learners!";

strcat(str1, str2); // Concatenate str2 to str1

printf("%s", str1); // Output: "Hello, world!"


return 0;
}

20
FPL Unit-IV DIT,
Pimpri

Output

Example 2: Concatenating multiple strings


#include <stdio.h>
#include <string.h>

int main() {
char str1[50] = "Hello, ";
const char str2[] = "how are you";
const char str3[] = "?";

strcat(str1, str2); // Concatenate str2 to str1


strcat(str1, str3); // Concatenate str3 to str1

printf("%s", str1); // Output: "Hello, world!"


return 0;
}
Output

strcpy() function:

Example: strcpy() function


#include<stdio.h>
#include<string.h>

int main()
{
char s1[50], s2[50];

21
FPL Unit-IV DIT,
Pimpri

strcpy(s1, "StudyTonight");
strcpy(s2, s1);

printf("%s\n", s2);
return(0);
}

strrev() function:

Example: strrev()Function
#include <stdio.h>

int main()
{
char s1[50];
printf("Enter your string: ");
gets(s1);
printf("\nYour reverse string is: %s",strrev(s1));
return(0);
}

Programs on String:

22
FPL Unit-IV DIT,
Pimpri

Find the Frequency of a Character

#include <stdio.h>
int main() {
char str[1000], ch;
int count = 0;

printf("Enter a string: ");


fgets(str, sizeof(str), stdin);

printf("Enter a character to find its frequency: ");


scanf("%c", &ch);

for (int i = 0; str[i] != '\0'; ++i) {


if (ch == str[i])
++count;
}

printf("Frequency of %c = %d", ch, count);


return 0;
}

Output
Enter a string: This website is awesome.
Enter a character to find its frequency: e
Frequency of e = 4

Program to Swap strings


#include<stdio.h>
void swap(char *str1, char *str2)
{
char *temp = str1;
str1 = str2;
str2 = temp;
}

int main()
{
char *str1 = "science";
char *str2 = "technology";
swap(str1, str2);
printf("str1 is %s, str2 is %s", str1, str2);
getchar();
23
FPL Unit-IV DIT,
Pimpri

return 0;
}

Program to find Palindrome String in C


// C implementation to check if a given
// string is palindrome or not
#include <stdio.h>
#include <string.h>
#include <stdbool.h>

bool isPalindrome(char str[], int l, int h)


{
// if the string size is 0 or 1
// it is a palindrome
if (l >= h)
return true;

// if both the terminal characters


// not matching, not palindrome
if (str[l] != str[h])
return false;

// call the smaller sub-problem


return isPalindrome(str, l + 1, h - 1);
}

int main()
{
char str[] = { "abbba" };

// Start from first and


// last character of str
int l = 0;
int h = strlen(str) - 1;

bool ans = isPalindrome(str, l, h);


if (ans) {
printf("%s is a palindrome\n", str);
}
else {
printf("%s is not a palindrome\n", str);
}

return 0;

24
FPL Unit-IV DIT,
Pimpri

Output
abbba is a palindrome

Question Bank
1) What is an Array in C Programming?
2) How to create an Array?
3) What are the properties of an array?
4) Advantages and disadvantages of Array?
5) Can we change the size of an array at run time?
6) What is the default value of Array?
7) What is the two-dimensional array?
8) What is need of multidimensional array in c?
9) Write a program to sum values of given array.
10) Write a program to insert an element and in the specific position in the array?
11) What is a Character Array?
12) How to declare and initialize a character array?
13) What is a string in C programming?
14) How to declare a string in C?
15) What are the string functions? List them and explain with example.
16) How to compare the strings in C?
17) Program to reverse words in a given string.

25

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy