CS111 Introduction to Programming - Arrays and Strings - PDF
Document Details
Uploaded by Deleted User
MEDITERRANEAN INSTITUTE OF TECHNOLOGY
Tags
Summary
This document presents a lecture on arrays and strings in C programming. It covers the declaration, initialization, and accessing of arrays and strings in C, along with relevant examples. The lecture also includes an overview of different types of string operations.
Full Transcript
CS111 INTRODUCTION TO PROGRAMMING 11/27/2024 1 WORKING WITH ARRAYS & STRINGS Lecture 4 11/27/2024 2 Outlines Arrays Strings 11/27/2024 MEDITERRANEAN INSTIUTE OF TECHNOLOGY 3 Arrays Array is the collection...
CS111 INTRODUCTION TO PROGRAMMING 11/27/2024 1 WORKING WITH ARRAYS & STRINGS Lecture 4 11/27/2024 2 Outlines Arrays Strings 11/27/2024 MEDITERRANEAN INSTIUTE OF TECHNOLOGY 3 Arrays Array is the collection of similar data types or collection of similar entity stored in contiguous memory location. Advantage of C Array: 1) Code Optimization: Less code to the access the data. 2) Easy to traverse data: By using the for loop, we can retrieve the elements of an array easily 3) Easy to sort data: To sort the elements of array, we need a few lines of code only. 4) Random Access: We can access any element randomly using the array. Disadvantage of Array Fixed Size: Whatever size, we define at the time of declaration of array, we can't exceed the limit. 11/27/2024 MEDITERRANEAN INSTIUTE OF TECHNOLOGY 4 Arrays Declaration of an Array data-type variable-name[size/length of array]; For example: int arr; Here int is the data type, arr is the name of the array and 10 is the size of array. Index of an array starts from 0 to size-1 i.e first element of arr array will be stored at arr address and last element will occupy arr. Symbolic constant can also be used to specify the size of the array as: #define SIZE 10; 11/27/2024 MEDITERRANEAN INSTIUTE OF TECHNOLOGY 5 Arrays Initialization of an Array After an array is declared it must be initialized. Otherwise, it will contain garbage value(any random value). Syntax : data_type array_name [size] = {value1, value2, value3…}; //list of values Example int age={22,25,30,32,35}; int marks={ 67, 87, 56, 77}; //integer array initialization float area={ 23.4, 6.8, 5.5}; //float array initialization int t={ 67, 87, 56, 77,MEDITERRANEAN 11/27/2024 59}; //Compile time error INSTIUTE OF TECHNOLOGY 6 Arrays ACCESSING OF ARRAY ELEMENT: #include int main() OUTPUT: { Enter a value for arr = 12 int arr,i; Enter a value for arr =45 for(i=0;i