Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
22 views

Cs Arrays

The document discusses arrays and strings in C programming. It covers one dimensional and two dimensional arrays, declaration and initialization of arrays, character arrays and strings, string handling functions and more.

Uploaded by

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

Cs Arrays

The document discusses arrays and strings in C programming. It covers one dimensional and two dimensional arrays, declaration and initialization of arrays, character arrays and strings, string handling functions and more.

Uploaded by

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

M.S.

Ramaiah Institute of Technology


(Autonomous Institute, Affiliated to VTU)
Department of Computer Science and Engineering

Course Name: Fundamentals of Computing


Course Code: CS16
Credits: 2:0:0
UNIT 3

Term: Odd Semester 2021

Faculty:
Mrs.Darshana A Naik
Mrs.Shilpa H
Mrs Sunitha R S

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


UNIT 3
Arrays and Matrices: One-Dimensional Array, Two-
Dimensional Arrays (Declaration and Compile Time and Run
Time Initialization). Sorting Algorithms, Search Algorithms
Character Arrays and Strings: Introduction, Declaring and
Initializing String Variables, Reading Strings from Terminal,
Writing Strings to Screen, Arithmetic Operations on
Characters, String Handling Functions, Other String Functions.

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 2


Why Arrays?

• Suppose, you need to store years of 100 cars. Will you


define 100 variables?
– int y1, y2,…, y100;

• Use the data structure Array: An array is an indexed data


structure to represent several variables having the same
data type:
Arrays
• Array is a data structure which collects related data items that
share a common array name and data type is called an array.
• Example: marks[3]
– Represents the marks of the 7 students.
– The individual values are called elements.
• Marks[0],marks[1],marks[2] are the individual elements of the array.
Properties of an Array

• An array’s data items are stored contiguously in memory.


• An array is a group of homogeneous data items that all have the
same array name and same data type.
• Arrays are static in that they remain the same size throughout
program execution.
• Each element can be accessed individually using index or subscript
One-dimensional array
• When a list of items can be given one variable name using only
one subscript and such a variable is called a one dimensional
array.
• int num[5]; Num[0]
Num[1]
Num[2]
Num[3]
Num[4]
• The subscript of an array always start with 0.
Declaration and Initialization of Arrays
Declaration:
The arrays are declaredbefore they are used in the program.
The general form of array declaration is

The type specifies the type of element that will be contained


in the array, such as int, float,or char.
size indicates the maximum number of elements that can be stored inside the array.
Declaration and Initialization of Arrays
• Example:
• 1. float weight[40];
– Declares the weight to be an array containing 40 real elements.
Any subscripts 0 to 39 are valid.
• 2. int group1[11];
– Declares the group1 as an array to contain a maximum of 10
integer constants.
Initialization of arrays
• The general form of initialization of arrays is:

• The values in the list are separated by commas.


• For example, the statement below shows
– int num[3]={2,2,2};
Initialization of arrays
• Points to remember:
– If the number of values is less than the number of elements, then only
that many elements will be initialized.
– The remaining elements will be set to zero automatically.
• float num1[5]={0.1,2.3,4.5};
• The first three elements are initialized to 0.1,2.3 and 4.5 and the
remaining two elements to zero.
Compile Time Initialization

• Arrays with the size


– int num[3]={1,2,3}
• Arrays without size
– int count[ ]= {2,2,2,2};
• Character arrays may be
initialized in a similar
manner.
– char name[ ]={‘S’,’W’,’A’,’N’}
Run time Initialization
Simple Array Programs
// Program to take 5 values from the user and store them in an array // Print the elements
stored in the array
#include <stdio.h>
int main()
{
int values[5];
printf("Enter 5 integers: "); // taking input and storing it in an array
for(int i = 0; i < 5; ++i)
{
scanf("%d", &values[i]);
}
printf("Displaying integers: "); // printing elements of an array
for(int i = 0; i < 5; ++i)
{
printf("%d\n", values[i]);
} return 0; }
Simple Array Programs
• Write and execute a C program to read a one dimensional
array of 10 floating point numbers using keyboard. Display
the smallest number and its position in the one dimensional
array.
Two Dimensional Arrays
Two dimensional arrays are declared as follows:
type array_name[row_size][coloumn_size];

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 15


Initializing Two-Dimensional Arrays
Two-dimensional arrays can be initialized by following their declaration with a list of initial values enclosed in braces.
For example
int table[2][3]={0,0,0,1,1,1}; int m[3][5]={{0},{0},{0}};
int table[2][3]={{0,0,0},{1,1,1}}; int m[3][5]={0,0};
int table[2][3]={
{0,0,0},
{1,1,1}
};
int table[2][3]={
{1,1},
{2}
};

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 16


Character Arrays and Strings:
 Introduction,
Declaring and Initializing String Variables,
Reading Strings from Terminal,
Writing Strings to Screen,
Arithmetic Operations on Characters,
String Handling Functions,
Other String Functions.
•Strings are defined as an array of characters.
•A string is a simple array with char as a data type. 'C' language does not directly support string as a data type.
Hence, to display a string in 'C', you need to make use of a character array.
•The difference between a character array and a string is the string is terminated with a special character ‘\0’.

The general syntax for declaring a variable as a string is as follows,

char string_variable_name [array_size];

char first_name[15]; //declaration of a string variable


char last_name[15];

The above example represents string variables with an array size of 15. This means that the given character array is
capable of holding 15 characters at most. The indexing of array begins from 0 hence it will store characters from a
0-14 position. The C compiler automatically adds a NULL character '\0' to the character array created.
Initialization of a string variable. Following example demonstrates the initialization of a string variable,

char first_name[15] = “RAMESH";

char first_name[15] = {‘R',‘A',‘M',‘E',‘S',‘H','\0'};

// NULL character '\0' is required at end in this declaration

'C' also allows us to initialize a string variable without defining the size of the character array. It can be done in
the following way,

char first_name[ ] = “RAMESH";


String Input: Read a String
•C provides the scanf(), gets() functions to find a line of text entered from the user.
•When we use scanf() to read, we use the "%s" format specifier without using the "&" to access the variable
address because an array name acts as a pointer.

char name[10]; char name[10];

printf("Enter your first name : \n"); printf("Enter your name: \n");


scanf("%s", name); gets(name);

The problem with the scanf function is that it never In order to read a string contains spaces, we use the
reads an entire string. It will halt the reading process gets() function. Gets ignores the whitespaces. It stops
as soon as whitespace, form feed, vertical tab, newline reading when a newline is reached (the Enter key is
or a carriage return occurs. pressed).
String Output: Print/Writing a String
•The standard printf function is used for printing or displaying a string on an output device. The format specifier
used is %s
•The puts function prints the string on an output device and moves the cursor back to the first position.

printf("%s", name);

char name[15];

gets(name); //reads a string

puts(name); //displays a string


Difference between strlen() and sizeof():
•The function strlen() is a predefined function in C language. This is declared in “string.h” header file. It is used
to get the length of array or string.

•The function sizeof() is a unary operator in C language and used to get the size of any type of data in bytes.

char str[] = "MSRIT";

printf("Length of String is %d\n", strlen(str)); // Length of String is 5


printf("Size of String is %d\n", sizeof(str)); // Length of String is 6
The string library
•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.
Sr.No. Function & Purpose
1 strcpy(s1, s2);
Copies string s2 into string s1.
2 strcat(s1, s2);
Concatenates string s2 onto the end of string s1.
3 strlen(s1);
Returns the length of string s1.
4 strcmp(s1, s2);
Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if s1>s2.

5 strchr(s1, ch);
Returns a pointer to the first occurrence of character ch in string s1.

6 strstr(s1, s2);
Returns a pointer to the first occurrence of string s2 in string s1.
#include <stdio.h>
#include <string.h>
int main ()
{
char str1[12] = "Hello";
char str2[12] = "World";
char str3[12];
int len ;

/* copy str1 into str3 */


strcpy(str3, str1);
printf("strcpy( str3, str1) : %s\n", str3 );

/* concatenates str1 and str2 */


strcat( str1, str2);
printf("strcat( str1, str2): %s\n", str1 );

/* total length of str1 after concatenation */


len = strlen(str1);
printf("strlen(str1) : %d\n", len );
return 0;

}
//string comparison
val= strcmp(string1,string2);

if(val==0)
#include <string.h> {
printf("Strings are equal\n");
char string1[15]="Hello"; }
char string2[15]=" World!"; else
{
char string3[15]; printf("Strings are not equal\n");
int val; }

//string copy

printf("\nCopied stringis:%s\n", strcpy(string3,string1));

//string1 is copied into string3

//string concatenation
/

printf("Concatenated string:%s", strcat(string1,string2));


//string length

printf("\nLength of first string:%d“, strlen(string1));


Other important library functions are:
•strncmp(str1, str2, n) : it returns 0 if the first n characters of str1 is equal to the first n characters of str2, less
than 0 if str1 < str2, and greater than 0 if str1 > str2.

•strncpy(str1, str2, n) : This function is used to copy a string from another string. Copies the first n characters
of str2 to str1

•strstr(str1, str2): it returns a pointer to the first occurrence of str2 in str1, or NULL if str2 not found.

•strncat(str1, str2, n) : Appends (concatenates) first n characters of str2 to the end of str1 and returns a
pointer to str1.
Converting a String to a Number
•int atoi(str) Stands for ASCII to integer; it converts str to the equivalent int value. 0 is returned if the first
character is not a number or no numbers are encountered.

char *string_id[10];
int ID;

printf("Enter a number: ");


gets(string_id);

ID = atoi(string_id);

printf("you enter %d ",ID);

Enter a number: 12345 you enter 12345


String Handling functions
Function Action
strcat() Concatenates two
strings
strcmp() Compares two strings

strcpy() Copies one string to


another
strlen() Finds the length of the
string
Thank you

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 30

You might also like