0% found this document useful (0 votes)
25 views58 pages

8 1D Arrays Strings

The document discusses one-dimensional arrays in C including how to declare, initialize, access, and manipulate array elements. Key points include specifying the type and size of an array, storing elements in contiguous memory locations, using indexes to access specific elements, and examples of traversing and modifying arrays using for loops.

Uploaded by

ayushd172005
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views58 pages

8 1D Arrays Strings

The document discusses one-dimensional arrays in C including how to declare, initialize, access, and manipulate array elements. Key points include specifying the type and size of an array, storing elements in contiguous memory locations, using indexes to access specific elements, and examples of traversing and modifying arrays using for loops.

Uploaded by

ayushd172005
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 58

1-Dimensional Arrays

Array
An array in C is a variable that can store multiple
values of the same data type. It is a
fixed-size collection of similar data items stored in con
tiguous memory locations
.

To declare an array in C, a programmer specifies the type


of the elements and the number of elements required by a
n array as follows: type
arrayName [arraySize].

The arraySize
must be an integer constant greater than zero and type ca
n be any valid C data type
05/23/2024 CSE 1001 Department of CSE 2
Arrays

An array is a group of related data items that share a


common name.

The array elements are placed in contiguous memory


locations.

A particular value in an array is indicated by writing an


integer number called index number or subscript in
square brackets after the array name.

The least value that an index can take in array is 0..


Arrays
Array Declaration:
data-type name [size];

where data-type is a valid data type (like int, float, char...)

name is a valid identifier

size specifies how many elements the array has to contain.


 size field is always enclosed in square brackets [ ] and
takes static values.

 For example an array salary containing 5 elements is declared


as follows int salary [5];
Arrays - One Dimensional

 A linear list of fixed number of data items of same type.


 These items are accessed using the same name using a single
subscript. E.g. roll[0], roll[1]…. or salary [1], salary [4]
 A list of items can be given one variable name using only one
subscript and such a variable is called a single-subscripted
variable or a one- dimensional array.
Arrays - 1D
Total size:

The Total memory that can be allocated to 1Darray is computed as

Total size =size *(sizeof(data_type));

where size number of elements in 1-D array

data_type basic data type.

sizeof()  is a unary operator which returns the size of data type in


bytes.
Arrays - 1D
If the values of array are 3, 2, 6, 1, 9 then these values are
stored in array arr as follows.
int main()
{
int arr[50],n; // declaration of ‘arr’
printf(" enter value of n\n“); // no of elements
scanf(“%d”, &n); // reading the limit into n
for(int i=0;i<n;i++)
{
scanf(“%d”,&arr[i]); // reading n elements
}
for(int i=0; i<n;i++) //displaying n elements
{ printf(“%d”,arr[i]);
printf(“\t”);
}
return 0;
}
Initializing one-dimensional array

int number[3] ={0,0,0}; or {0} ;


 declares the variable number as an array of size 3
and will assign 0 to each element.
int age[ ] ={16,25,32,48,52,65};
 declares the age array to contain 6 elements with
initial values 16, 25, 32, 48, 52, 65 respectively. It is
same as:
int age[6] ={16,25,32,48,52,65};
int number[5] ={4,3,1};
Initializing one-dimensional array with zeros
Initialize all the elements of an integer array ‘values’ to zero

int values[20];
Begin for loop
Initialize counter
Set limit for counter for ( int i=0; i<20; i++)
Increment counter

Initialize element in array


‘values’ values[i]=0;
Printing one-dimensional array
For example

int x[3] = {9,11,13};

printf(“%d\n”,x[0]);
Output:
printf(“%d\n”,x[1]); 9
printf(“%d\n”,x[2]); 11
13

int x[3] = {9,11,13};

for (int i = 0; i<3; i++)

printf(“%d\n”,x[i]);
Program to read n elements into an array and print it

int a[10], i, n;
printf("enter no of numbers“); Output:
enter no of elements
scanf(“%d”,&n);
3
printf(“enter n numbers \n”); enter n numbers
for(i=0;i<n;i++) 9
11
scanf(“%d\n”,&x[i]);
13
Numbers entered are:
printf(“\nNumbers entered are:\n”); 9
for(i=0;i<n;i++) 11
13
printf(“%d\n”,a[i]);
Program to add two array elements and store the
corresponding elements sum in another array
void main()
if(m==n)
{ {
int a[10], b[10], c[10],n, m, i; for(i=0;i<m;i++)
printf("enter no. of numbers in { c[i]=a[i]+b[i]; }
first array\n“);
printf(“Sum of given array
scanf(“%d”,&n); elements\n”);
for(i=0;i<n;i++)
scanf(“%d”,&a[i]); //first array for(i=0;i<n;i++)
{ printf(“%d\n”,c[i]); }
}
printf("enter no of numbers in second else
array\n“); printf("cannot add“);
scanf(“%d”,&m); }
for(i=0;i<m; i++)
scanf(“%d”,&b[i]); //second array
Displaying elements of an array in reverse order.

int a[10], n, i; Example : a[ ]={1, 2, 3, 4, 5}


Enter values
n=5
printf(“Enter values\n“);
12345
Reverse printing of array
for(i=0;i<n;i++) 5 4 3 2 1
Array before Array after
scanf(“%d”,&a[i]); a[0]=1 a[0]=1
a[1]=2 a[1]=2
printf(“\nReverse order printing a[2]=3 a[2]=3
a[3]=4 a[3]=4
of array\n”); a[4]=5 a[4]=5

for(i=n-1;i>=0;i--) // reverse loop

printf(“%d\n”,a[i]);
WAP to delete an element from an array

printf("enter no of elements”); Example : delete element at 2nd position


scanf(“%d”,&n); a[ ]={1, 2, 3, 4, 5}
printf("enter n elements \n”);
New array after deleting 2:
for(i=0;i<n;i++) a[ ]={1, 3, 4, 5}
scanf(“%d”,&a[i]);
printf("enter the position at which the element to be deleted“);
scanf(“%d”,&pos);
for(i=pos-1; i<n-1; i++)
a[i] =a[i+1]; //shift the elements to left
n = n-1;//decrement the count of no of elements
for(i=0;i<n;i++)
printf(“%d”,a[i]);
05/23/2024 CSE 1001 Department of CSE 14
Insert an element into a sorted array
Read array elements (in sorted order) & element ‘ele’ to be
inserted
//f in d in g p o sit io n Example: insert 3 into the array
a[ ] = {1, 2, 4, 5,6}
for(i=0;i<n;i++)
if (ele<a[i]) break; New array after inserting 3 :
a[ ] = {1, 2, 3, 4, 5,6}
pos = i+1; //position of insertion
for(i=n; i>=pos; i--) //shift the elements to right
a[i]=a[i-1];
a[pos-1] = ele; //ele is inserted at the specified pos.
n = n + 1; // increment the count of no of elements

05/23/2024 CSE 1001 Department of CSE 15


WAP to insert an element to an array at a given position
int a[100], n,i, pos,ele;
Example : insert 9 at 2nd position
scanf(“%d”,&n); // number of elements a[ ]={1, 2, 3, 4, 5}
printf("\nEnter the elements of array:“);
for(i=0;i<n;i++) New array after inserting 9 :
a[ ]={1, 9, 2, 3, 4, 5}
scanf(“%d”,&a[i]);
printf("\nEnter the element and position of insertion:”);
scanf(“%d %d”,&ele, &pos);
for(i=n; i>=pos; i--) //shift the elements to right
a[i]=a[i-1];
a[pos-1] = ele;//ele is inserted at the specified pos.
n = n + 1; // increment the count of no of elements
printf("\nThe array after insertion is:“);
for(i=0;i<n; i++)
printf(“%d\n”, a[i]);
05/23/2024 CSE 1001 Department of CSE 16
Syntax
1D Array:
 Syntax: type array_name[size];

 Memory Requirement:
Total size =size *(sizeof(data_type));

 Initialization:
type array-name [size]={list of values}

 Write and Read:


for(i=0;i<n;i++) for(i=0;i<n;i++)
scanf(“%d”,&a[i]); prinft(“%d\n”,a[i]);

05/23/2024 CSE 1001 Department of CSE 17


Write a program to reverse an array using only
one array

Example : a[ ]={1, 2, 3, 4, 5}
int a[20], i, j, n, temp; Enter values
n=5
printf("enter n \n“); 12345
Reversed array
scanf(“%d”, &n);
5 4 3 2 1
printf("\n Enter values for an array“); Array Reversed
array
for(i=0;i<n;i++) a[0]=1 a[0]=5
a[1]=2 a[1]=4
scanf(“%d”,&a[i]); a[2]=3 a[2]=3
a[3]=4 a[3]=2
Contd… a[4]=5 a[4]=1
Reversing an array
for(i=0, j=n-1; i<n/2; i++, j--) Example :
a[ ]={1, 2, 3, 4, 5}
{
temp=a[i];
a[i]=a[j];
a[j]=temp;

}
Output:
printf("\n Reversed array: \n“);
Enter values for an array
for(i=0;i<n;i++) n=5
12345
printf(“%d\t”,a[i]); Reversed array
5 4 3 2 1
}
Linear Search

• Finding whether a data item is present in a set of


items

→ linear search / sequential search

05/23/2024 CSE 1001 Department of CSE 20


Linear search- illustration 1

05/23/2024 CSE 1001 Department of CSE 21


Linear search- illustration 2

05/23/2024 CSE 1001 Department of CSE 22


Pseudo code for linear search

/*search procedure*/
int found=0; //setting flag
for(i=0; i<n; i++) {
Print "enter no of elements"; if(a[ i ]==key) // comparison

Input n; {
found=1;
for(i=0;i<n;i++){
pos=i+1;
Print “enter number\n"; break;

Input a[i]; // entered data items }}


if(found==1)
}
Print“data_found_in”,pos,
Print “enter the element to be "position";

searched"; otherwise
Print “data is not found“;
Input key; // data to be searched
05/23/2024 CSE 1001 Department of CSE 23
Sorting
Arrangement of data elements in a particular order

 Bubble sorting

05/23/2024 CSE 1001 Department of CSE 24


Bubble Sort- Illustration

05/23/2024 CSE 1001 Department of CSE 25


Bubble Sort- Illustration

05/23/2024 CSE 1001 Department of CSE 26


Pseudo code for Bubble Sort procedure
for(i=0;i<n;i++)
Example :
Input a[i]; // entered elements a[ ]={16, 12, 11, 67}
for(i=0;i<n-1;i++) //pass
{ for(j=0;j<n-i-1;j++) Array after sorting (ascending)
a[ ]={11, 12, 16, 67}
{ if(a[j]>a[j+1]) // comparison
{ // interchange
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}05/23/2024 CSE 1001 Department of CSE 27
C H A R A C T E R A R R AYS
STRINGS
Strings
Definition
 A string is an array of characters.
 Any group of characters defined between double quotation marks is a
constant string.
 Character strings are often used to build meaningful and readable
programs.
The common operations performed on strings are
Reading and writing strings
Combining strings together
Copying one string to another
Comparing strings to another
Extracting a portion of a string ..etc.
05/23/2024 CSE 1001 Department of CSE 29
Strings
Declaration and initialization
char string_name[size];
The size determines the number of characters in the string_name.

For example, consider the following array:


char name [20];
is an array that can store up to 20 elements of type char.
It can be represented as:

05/23/2024 CSE 1001 Department of CSE 30


Strings

The character sequences "Hello" and "Merry Christmas"


represented in an array name respectively are shown as
follows :

05/23/2024 CSE 1001 Department of CSE 31


Initialization of null-terminated character sequences
 arrays of characters or strings are ordinary arrays that
follow the same rules of arrays.

For example

To initialize an array of characters with some predetermined


sequence of characters one can initialize like any other array:

char myWord[ ] = { 'H', 'e', 'l', 'l', 'o', '\0' };

05/23/2024 CSE 1001 Department of CSE 32


Initialization of null-terminated character sequences
 Arrays of char elements have an additional methods to initialize their
values: using string literals
 “Manipal ” is a constant string literal.
For example,
char result[14] =“Manipal”;
 Double quoted (") strings are literal constants whose type is in fact a
null-terminated array of characters.
So string literals enclosed between double quotes always have a null
character ('\0') automatically appended at the end.

05/23/2024 CSE 1001 Department of CSE 33


Initialization
 Initialization:

char myWord [ ] = { 'H', 'e', 'l', 'l', 'o', '\0' };

char myWord [ ] = "Hello";

 In both cases the array of characters myword is declared with a size of 6


elements of type char:

The 5 characters that compose the word "Hello" plus a final null
character ('\0') which specifies the end of the

sequence and that,

In the second case, when using double quotes (") null character ('\0') is
appended automatically.

05/23/2024 CSE 1001 Department of CSE 34


Example
#include <stdio.h>

int main() {

char question[ ] = "Please, enter your first name: ";

char greeting[ ] = "Hello, ";

char yourname [ 80];

printf(“%s”, question);

scanf(“%s”, &yourname);

printf(“%s…. %s\n”, greeting, yourname );


Please, enter your first name: gautam
return 0;
Hello.…gautam
}
05/23/2024 CSE 1001 Department of CSE 35
Example

#include <stdio.h>

int main()

const int MAX = 80; //max characters in string

char str[MAX]; //string variable str

printf("Enter a string: \n");

scanf("%s",&str); //put string in str

printf("%s",str); //display string from str


Enter a string:
return 0;
gautam kumar
} gautam

05/23/2024 CSE 1001 Department of CSE 36


Reading Embedded Blanks

To read everything that you enter from the keyboard until the
ENTER key is pressed (including space).
Syntax:
gets(string) ;

CSE 1001 Department of CSE 05/23/2024 37


Example
#include <stdio.h>

#include<string.h>

int main()

char str[80]; //string variable str

printf(“\nEnter a string: ”);

gets(str); //put string in str or use gets(str)

printf(“ the string is \n“);

puts(str); Enter a string: Manipal University Jaipur, India


the string is
return 0; Manipal University Jaipur, India
}
05/23/2024 CSE 1001 Department of CSE 38
Count the number of characters in a string
#include <stdio.h> gets(sent);
puts(sent);

int main() while(sent[i]!='\0')

{ {

char sent[100]; count++;

int i=0, count=0; i++;


}

printf("enter sentence \n“); printf(“\n The No of characters=%d “, count);


return 0;
}

05/23/2024 CSE 1001 Department of CSE 39


Count the number of words in a sentence
#include <stdio.h>
while(sent[i]!='\0')
int main() {
if (sent[i]==' '&& sent[i+1]!=' ')
{
count++;
const int MAX = 100; i++;
}
char sent[MAX];
printf(“n %d n no. of words = " ,count);
int i=0,count=1; return 0;
}

printf("enter sentence \n“);


gets(sent);
printf("\n”);

05/23/2024 CSE 1001 Department of CSE 40


Reading multiple lines: Example
#include <stdio.h>
gets(str);
int main()
printf("You entered:\n”);
{
printf(“%s”,str);
const int MAX = 2000;
return 0;
//max characters in string
}
char str[MAX]; //string

variable str

printf("\nEnter a string:\n“);

The function will continue to accept characters until enter key is pressed.

05/23/2024 CSE 1001 Department of CSE 41


Library functions: String Handling functions (built-in)
• Used to manipulate a given string.
• These functions are part of string.h header file.

 strlen ()
 gives the length of the string. E.g. strlen(string)

 strcpy ()
 copies one string to other. E.g. strcpy(Dstr1, Sstr2)

 strcmp ()
 compares the two strings. E.g. strcmp(str1, str2)

 strcat ()
Concatinate the two strings. E.g. strcat(str1, str2)

05/23/2024 CSE 1001 Department of CSE 42


Library function: strlen()

• String length can be obtained by using the following function


n=strlen(string);

• This function counts and returns the number of characters in


a string, where n is an integer variable which receives the
value of the length of the string.

• The argument may be a string constant.


Eg: printf(“%d”,strlen(“Manipal”)); prints out 7.

05/23/2024 CSE 1001 Department of CSE 43


Copies a string using a for loop
#include <stdio.h>
#include<string.h>
int main()
{
char str1[ ] = “Manipal Institute of Technology”;
char str2[80]; //empty string
int n=strlen(str1);
for(int j=0 ; j<n; j++) //copy strlen characters
{str2[j] = str1[j]; } // from str1 to str2
str2[j] = ‘\0’; //insert NULL at end
printf(“%s”,str2); //display str2
return 0;
}
05/23/2024 CSE 1001 Department of CSE 44
Extracting a character from a string
#include <stdio.h> D E L H I

#include<string.h>
int main() sent[0] sent[1] sent[2] sent[3] sent[4]
{ Enter sentence
Delhi
char sent[100]; 5 (length of string sent)
int len; I
printf("enter string \n“); D
gets(sent);
len=strlen(sent);
printf(“%d\n”,len);
printf(“%c\n”,sent[len-1]);
printf(“%c\n”,sent[0]); }

05/23/2024 CSE 1001 Department of CSE 45


To encrypt and decrypt a string
#include <stdio.h> for(i=0;sent[i]!=‘\0’;i++)

#include<string.h> sent[i]=sent[i]+1;
int main() printf(“ the encrypted string is \n”);
{ puts(sent);
const int MAX = 100;
for(i=0;sent[i]!=‘\0’;i++)
char sent[MAX];
sent[i]=sent[i]-1;
int len,I;
printf(“ the decrypted string is \n”);
printf("enter sentence \n“);
puts(sent);
gets(sent);
}

05/23/2024 CSE 1001 Department of CSE 46


Library function: strcpy()
Copying a String the EASY WAY using
strcpy(destination, source)
 The strcpy function works almost like a string assignment operator and
assigns the contents of source to destination.

destination may be a character array variable or a string constant.

e.g., strcpy(city, ”DELHI”);

will assign the string “DELHI” to the string variable city.

Similarly, the statement strcpy(city1, city2);

will assign the contents of the string variable city2 to the string variable
city1.

The size of the array city1 should be large enough to receive the
contents of city2.
05/23/2024 CSE 1001 Department of CSE 47
strcpy(): Example
#include <stdio.h>

int main()

char str1[ ] = “Tiger, tiger, burning bright\n”

“In the forests of the night”;

const int MAX = 80; //size of str2 buffer

char str2[MAX]; //empty string

strcpy(str2, str1); //copy str1 to str2

printf(“%s”,str2);//display str2

}
05/23/2024 CSE 1001 Department of CSE 48
Library function: strcmp()

 The strcmp function compares two strings identified by the


arguments and has a value 0 if they are equal.
 If they are not, it has the numeric difference between the first non
matching characters in the strings.
strcmp(string1, string2);
string1 and string2 may be string variables or string constants.
e.g., strcmp(“their”, ”there”); will return a value of –9 which is the
numeric difference between ASCII “i” and ASCII “r”. That is, “i” minus
“r” with respect to ASCII code is –9.
If the value is negative, string1 is alphabetically above string2.

05/23/2024 CSE 1001 Department of CSE 49


Library function: strcat()
The strcat function joins two strings together.

It takes the following form:


strcat(string1, string2);
string1 and string2 are character arrays.
 When the function strcat is excuted, string2 is
appended to string1.
 It does so by removing the null character at the end
of string1 and placing string2 from there.
 The string at string2 remains unchanged.

05/23/2024 CSE 1001 Department of CSE 50


Concatenation of 2 strings
#include <stdio.h>
#include <string.h>
int main()
{ char s1[40], s2[50];
printf("\nEnter the first string“);
gets(s1);
printf("\nEnter the second string“);
gets(s2);
strcat(s1, s2);
printf("\nConcatenated string is“);
printf(“%s”,s1);
return 0; }
05/23/2024 CSE 1001 Department of CSE 51
Reversing a string

int main() for(i=0;i<n;i++)


{ {
char str[70]; temp=str[i];
char temp; str[i]=str[n-i-1];
int i, n=0; str[n-i-1]=temp;
printf("\nEnter the string:“); }
gets(str); printf("\nReversed string is:“);
//find the string length puts(str);
n=strlen(str); return 0;
}

05/23/2024 CSE 1001 Department of CSE 52


Check whether a string is Palindrome or not
for(i=0;i<n/2;i++)
int main() {
{
if(str[i]!=str[n-i-1])
char str[30];
{ flag=0;
int i, j, n, flag=1;
break; }
printf("\nEnter the string:“);
}
gets(str);
if(flag==1)
//find the string length
printf("\nIts a Palindrome“);
n=strlen(str);
else
printf("\nNot a Palindrome“);
return 0;
}
05/23/2024 CSE 1001 Department of CSE 53
Change all lower case letters into uppercase in a
sentence

int main() for(i=0;i<n;i++)


{ {
char string[30]; if(string[i]>=97 && string[i]<=122)
int i,n=0; string[i]=string[i]-32;
printf("\nEnter the string“); }
gets(string);
puts(string);
for(i=0;string[i]!='\0';i++) getch();
n++; return 0;
}
05/23/2024 CSE 1001 Department of CSE 54
Strings Bubble Sort

for(i=0;i<no-1;i++)
for(j=i+1;j<no;j++)
int main()
{
{ if(strcmp(string[i],string[j])>0)
{
char string[30][30],temp[30];
strcpy(temp,string[i]);
int no, i, j;
cout<<"\nEnter the no of strings:"; strcpy(string[i],string[j]);
strcpy(string[j],temp);
cin>>no; }
cout<<"\nEnter the strings:"; }

for(i=0;i<no; i++) cout<<"\nThe sorted array is:";


gets(string[i]); for(i=0;i<no;i++)
puts(string[i]);
return 0;
}

05/23/2024 CSE 1001 Department of CSE 55


Finding Substring in Main String

Main string: cc aa bb
Sub-String : aa

Enter main string: cc aa bb


Enter sub-string : aa
Substring aa is found at positions 3

56
Finding Substring in Main String
int main()
{
char str1[80],str2[80];
int i,j,len=0;

cout<<"Enter the main string :\n";


gets(str1);

cout<<"Enter sub string :\n";


gets(str2);

//finding length of substring


for(i=0;str2[i]!='\0'; i++)
len++;

57
Finding Substring in Main String
for(i=0,j=0; str1[i]!='\0‘ && str2[j]!='\0'; i++)
if(str1[i]==str2[j])
j++;
else
j=0;

if(j==len)
cout<<"Substring\t"<<str2<< "\tfound;
else
cout<<"Substring not found";

58

You might also like