SlideShare a Scribd company logo
UNIT 6
ARRAYS
Arrays
• An array is 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.
• Array is a data structure that store a number of data items as a single entity (object) .
• The individual data items are called elements and all of them have same data types.
• Array is used when multiple data items have common characteristics are required.
Ashim Lamichhane 2
• Instead of declaring,
• such as number0, number1, ..., and number99,
• We declare one array variable such as numbers and use numbers[0],
numbers[1], and ..., numbers[99] to represent individual variables.
• A specific element in an array is accessed by an index.
• All arrays consist of contiguous memory locations.
• The lowest address corresponds to the first element and the highest
address to the last element.
Ashim Lamichhane 3
How to Define an Array?
• An Array is defined as following
<storage_class> <type-of-array> <name-of-array> [<number of elements in array>];
• storage_class: it may be auto, register, static and extern. [Optional]
• type-of-array: It is the type of elements that an array stores.
E.x. ‘char’, ‘int’.
• name-of-array: This is the name that is given to array. At least the name should
be in context with what is being stored in the array.
• [number of elements]: This value in subscripts [] indicates the number of
elements the array stores.
Ashim Lamichhane 4
For example (ONE DIMENSIONAL ARRAY)
• an array of five characters can be defined as :
• char arr[5];
• to declare a 10-element array called balance of type double:
• double balance[10];
• int num[35]; /* An integer array of 35 elements */
• char ch[10]; /* An array of characters for 10 elements */
Ashim Lamichhane 5
Initializing Array
• You can initialize an array in C either one by one or using a single statement as follows −
double balance[5] = {1000.0, 2.0, 3.4, 7.0, 50.0};
• The number of values between braces { } cannot be larger than the number of elements that we declare for
the array between square brackets [ ].
• If you omit the size of the array, an array just big enough to hold the initialization is created. Therefore, if you
write −
double balance[] = {1000.0, 2.0, 3.4, 7.0, 50.0};
• Ex: balance[4] = 50.0;
• The above statement assigns the 5th element in the array with a value of 50.0.
Ashim Lamichhane 6
• All arrays have 0 as the index of their first element which is also called
the base index and the last index of an array will be total size of the
array minus 1.
• Shown below is the pictorial representation of the array we discussed
earlier:
double balance[5] = {1000.0, 2.0, 3.4, 7.0, 50.0};
Ashim Lamichhane 7
Accessing Array Elements
• An element is accessed by indexing the array name.
• This is done by placing the index of the element within square
brackets after the name of the array. For example −
double salary = balance[4];
• The above statement will take the 10th element from the array and
assign the value to salary variable.
Ashim Lamichhane 8
example
#include <stdio.h>
int main () {
int n[ 10 ]; /* n is an array of 10 integers */
int i,j; /* initialize elements of array n to 0 */
for ( i = 0; i < 10; i++ ) {
n[ i ] = i + 100; /* set element at location i to i + 100 */
}
/* output each array element's value */
for (j = 0; j < 10; j++ ) {
printf("Element[%d] = %dn", j, n[j] );
}
return 0;
}
Ashim Lamichhane 9
[IMP] WAP to sort n numbers in ascending order.
#include <stdio.h>
int main(void){
int nums[50],i,j,n,temp;
printf("How many Numbers are there?t");
scanf("%d",&n);
printf("nEnter %d numbers: n",n);
for(i=0;i<n;i++){
scanf("%d",&nums[i]);
}
for (i = 0; i < n-1; ++i){
for (j=i+1; j < n;j++) {
if(nums[i]>nums[j]){
temp=nums[i];
nums[i]=nums[j];
nums[j]=temp;
}
}
}
printf("nThe numbers in ascending order:n");
for(i=0; i<n;i++){
printf("t%d",nums[i]);
}
printf("n");
}
Ashim Lamichhane 10
Characteristics Of An Array
• The declaration of int a[5] is nothing but creation of 5 variables of
integer type in the memory.
• All the elements of an array share the same name. distinguished from
one another by element number or array index.
• Any element can be modified separately without disturbing another
element.
• Element basis operation should be carried out rather than taking as a
whole.
Ashim Lamichhane 11
Questions (Classwork)
• WAP to read 10 integers from keyboard and display entered numbers
on the screen.
• WAP that reads mark’s percentage in an examination of 10 students
and deviation percentage from average of students.
• [IMP] WAP to find the highest and second last smallest number of an
element.
Ashim Lamichhane 12
Multi Dimensional Array
• Have more than one dimensions.
• Separate pair of square brackets is required for each subscript or
dimension or index.
• Two dimensional arrays will require two pairs of square brackets;
three dimensional with three pairs and so on.
• Two dimensional is also called matrix.
Ashim Lamichhane 13
storage_class data_type array_name[dim1] [dim2] … [dimn];
• Here, dim1,dim2…dimn are positive valued integer expressions that
indicate the number of array elements associated with each
subscript.
• m*n two dimensional array can be thought as tables of values having
m rows and n columns.
• For ex int x[3][3] can be shown as follows:
Col 1 Col 2 Col 3
ROW 1 X[0][0] X[0][1] X[0][2]
ROW 2 X[1][0] X[1][1] X[1][2]
ROW 3 X[2][0] X[2][1] X[2][2]
Ashim Lamichhane 14
Declaration of two-dimensional array
• Like one dimensional array, two dimensional arrays must also be
declared before using it.
• The syntax:
[storage_class] data_type array_name[row_size][col_size];
• Example:
• int matrix[2][3]; /* matrix is 2-D array which has 2 rows and 3 columns */
• float m[10][20];
• char students[10][15];
Ashim Lamichhane 15
Initialization of 2-D array
• int marks[2][3]={ {2,4,6}, {8,10,12} }; //is equivalent to
• marks[0][0]=2; marks[0][1]=4; marks[0][2]=6;
• marks[1][0]=8; marks[1][1]=10; marks[1][2]=12;
• int marks1[ ][3]= { {2,4,6}, {8,10,12} }; // is equivalent to
• marks1[0][0]=2; marks1[0][1]=4; marks1[0][2]=6;
• marks1[1][0]=8; marks1[1][1]=10; marks1[1][2]=12;
• int marks2[2][3]={2,4,6,8,10,12};
• Int marks3[][3]={2,4,6,8,10,12};
ERRORS:
• Int marks[3][]={2,4,6,8,10,12}; int marks[ ][ ]={2,4,6,8,10};
Ashim Lamichhane 16
Accessing 2-D array elements
• In 2-D array, the first dimension specifies number of rows and second
specifies columns.
• A row is 1-D array. 2-D array contains multiple rows(i.e. 1-D arrays).
Thus 2-D array is an array of 1-D arrays.
• 2-D array is traversed row by row(i.e. every column elements in first
row are traversed first and then column elements of second row are
traversed and so on.)
• Nested loop is used to traverse the 2-D array.
Ashim Lamichhane 17
• Let us consider following 2-D array marks of size 4*3
• i.e. matrix having 4 rows and 3 columns
• The Array is traversed in the following order:
35 ->10 ->11 ->34 ->90 ->76 ->13 ->8 ->5 ->76 ->4 ->1
• i.e marks[0][0] -> marks[0][1] -> marks[0][2] -> marks[1][0] ->
marks[1][1] -> marks[1][2] -> marks[2][0] -> marks[2][1] ->
marks[2][2] -> marks[3][0] -> marks[3][1] -> marks[3][2].
35 10 11
34 90 76
13 8 5
76 4 1
Ashim Lamichhane 18
#include <stdio.h>
int main(void){
int matrix[2][3],i,j;
for(i=0;i<2;i++){
for(j=0;j<3;j++){
printf("Enter Matrix[%d][%d]: ",i,j);
scanf("%d",&matrix[i][j]);
}
}
printf("The Entered Matrxn");
for(i=0;i<2;i++){
for(j=0;j<3;j++){
printf("%dt",matrix[i][j]);
}
printf("n");
}
}
Ashim Lamichhane 19
WAP: Sum of matrix
//FOR FIRST MATRIX A
for(i=0;<m;i++){
for(j=0;j<n;j++){
scanf(“%d”,&a[i][j]);
}
}
//FOR FIRST MATRIX B
for(i=0;<m;i++){
for(j=0;j<n;j++){
scanf(“%d”,&b[i][j]);
}
}
//FOR sum
for(i=0;<m;i++){
for(j=0;j<n;j++){
sum[i][j]=a[i][j]+b[i][j];
}
}
Ashim Lamichhane 20
Passing arrays to function
• It is possible to pass the value of an array element and even an entire
array as an argument to a function.
• To pass an entire array to a function, the array name must appear by
itself, without brackets or subscripts, as an actual argument in
function call statement.
• When declaring a one-dimensional array as a formal argument, the
array name is written with a pair of empty square brackets. The size
of the array is not specified within the formal argument declaration.
Ashim Lamichhane 21
• Syntax for function call passing array as argument,
function_name(array_name)
• Syntax for function prototype which accepts array
return_type function_name(data_type array_name[]);
Or
return_type function_name(data_type *pointer_variable);
• When array is passed to a function, the values of the array elements are
not passed to the function rather the array name is interpreted as the
address of the first array element.
• The address assigned to the corresponding formal argument when the
function is called.
• The formal argument therefore becomes a pointer to the first array
element.
Ashim Lamichhane 22
#include <stdio.h>
void display(int n){
printf("%dt", n );
}
int main(void){
int nums[5]={100,23,44,3,65},i;
printf("nThe content of array is: n");
for (int i = 0; i < 5; i++){
display(nums[i]);
}
}
Ashim Lamichhane 23
WAP to illustrate passing an entire array to a function
#include <stdio.h>
void change(int a[]){
a[0]=10;a[1]=20;a[2]=30;a[3]=40;a[4]=50;
}
int main(void){
int nums[5]={100,23,44,3,65},i;
printf("nBEFORE FUNCTION CALL: n");
for (int i = 0; i < 5; i++) {
printf("t%d",nums[i]);
}
printf("n");
change(nums); /* PASSING ARRAYS NUMS TO FUNCTION */
printf("nAFTER FUNCTION CALLn");
for (int i = 0; i < 5; i++) {
printf("t%d",nums[i]);
} printf("n");
}
Ashim Lamichhane 24
Arrays and Strings
• In C programming, array of character are called strings. A string is terminated by null
character 0. For example:
Ex. "c string tutorial"
• Here, "c string tutorial" is a string. When, compiler encounters strings, it appends null
character at the end of string.
• Strings are actually one-dimensional array of characters terminated by a null character
'0'.
• If you follow the rule of array initialization then you can write the above statement as
follows −
char greeting[] = "Hello";
Ashim Lamichhane 25
c s t r i n g t u t o r i a l 0
char greeting[] = "Hello";
Following is the memory presentation of the above defined string in C −
Actually, you do not place the null character at the end of a string constant. The C compiler automatically
places the '0' at the end of the string when it initializes the array.
Ashim Lamichhane 26
INDEX 0 1 2 3 4 5
VARIABLE H e l l o 0
ADDRESS 0x23452 0x23453 0x23454 0x23455 0x23456 0x23457
Initialization of strings
• In C, string can be initialized in different number of ways.
char c[]="abcd";
OR,
char c[5]="abcd";
OR,
char c[]={'a','b','c','d','0'};
OR;
char c[5]={'a','b','c','d','0'};
Ashim Lamichhane 27
C[0] C[1] C[2] C[3] C[4]
a b c d 0
Declaration of strings
• Strings are declared in C in similar manner as arrays. Only difference is
that, strings are of char type.
char s[5];
• Strings can also be declared using pointer.
char *p
(will be discussed in future chapters)
Ashim Lamichhane 28
s[0] s[1] s[2] s[3] s[4]
• Let us try to print the above mentioned string −
#include <stdio.h>
int main () {
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '0'};
printf("Greeting message: %sn", greeting );
return 0;
}
OUTPUT:
Greeting message: Hello
Ashim Lamichhane 29
Write a C program to illustrate how to read string from terminal.
#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.
NOTE: Here, program will ignore Ritchie because, scanf() function takes only string before the white
space.
Ashim Lamichhane 30
C program to read line of text manually.
#include <stdio.h>
int main(){
char name[30],ch;
int i=0;
printf("Enter name: ");
while(ch!='n') // terminates if user hit enter
{
ch=getchar();
name[i]=ch;
i++;
}
name[i]='0'; // inserting null character at end
printf("Name: %s",name);
return 0;
}
This process to take string is tedious. There are predefined functions gets() and puts in C language to read and display string respectively.
Ashim Lamichhane 31
int main(){
char name[30];
printf("Enter name: ");
gets(name); //Function to read string from user.
printf("Name: ");
puts(name); //Function to display string.
return 0;
}
• Both, the above program has same output below:
• Output
Enter name: Tom Hanks
Name: Tom Hanks
Ashim Lamichhane 32
Passing Strings to Functions
#include <stdio.h>
void Display(char ch[]);
int main(){
char c[50];
printf("Enter string: ");
gets(c);
Display(c); // Passing string c to function.
return 0;
}
void Display(char ch[]){
printf("String Output: ");
puts(ch);
}
• Here, string c is passed from main() function to user-defined function Display(). In function
declaration, ch[] is the formal argument.
Ashim Lamichhane 33
C supports a wide range of functions that manipulate null-terminated strings −
S.N. Function & Purpose(these functions are defined in header file string.h)
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 strrev(s1);
Returns reverse of a string s1
Ashim Lamichhane 34
#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) : %sn", str3 );
/* concatenates str1 and str2 */
strcat( str1, str2);
printf("strcat( str1, str2): %sn", str1 );
/* total lenghth of str1 after concatenation */
len = strlen(str1);
printf("strlen(str1) : %dn", len );
return 0;
}
Ashim Lamichhane 35
Strcpy(str3,str1) Hello
Strcat(str1,str2) HelloWorld
Strlen(str1) 10
Please do check Google
Drive for Assignment
Ashim Lamichhane 36
Reference
• http://www.thegeekstuff.com/2011/12/c-arrays/
• http://www.tutorialspoint.com/cprogramming/c_arrays.htm
• http://c.learncodethehardway.org/book/ex10.html
• http://beginnersbook.com/2014/01/c-arrays-example/
• A Textbook Of C programming by Ram Datta Bhatta
• http://www.cprogramming.com/tutorial/c/lesson9.html
• http://www.programiz.com/c-programming/c-strings
Ashim Lamichhane 38
END
Ashim Lamichhane 39

More Related Content

What's hot (20)

PPTX
Recursive Function
Harsh Pathak
 
PPTX
String in java
Ideal Eyes Business College
 
PPTX
Sparse matrix and its representation data structure
Vardhil Patel
 
PPTX
Static Data Members and Member Functions
MOHIT AGARWAL
 
PPTX
Data Structures - Lecture 7 [Linked List]
Muhammad Hammad Waseem
 
PPT
Strings
Mitali Chugh
 
PDF
OOP Assignment 03.pdf
ARSLANMEHMOOD47
 
PPTX
Presentation on queue
Rojan Pariyar
 
PPTX
Array in Java
Ali shah
 
PPTX
Strings in Java
Abhilash Nair
 
PPTX
Data Structures - Lecture 9 [Stack & Queue using Linked List]
Muhammad Hammad Waseem
 
PPT
Class and object in C++
rprajat007
 
PPTX
Unit 4. Operators and Expression
Ashim Lamichhane
 
PPT
Data Structure and Algorithms Binary Search Tree
ManishPrajapati78
 
PPT
Data abstraction and object orientation
Hoang Nguyen
 
PPTX
linked list in Data Structure, Simple and Easy Tutorial
Afzal Badshah
 
PPTX
Java Data Types
Spotle.ai
 
PPTX
Unit 4 python -list methods
narmadhakin
 
PPTX
Sparse matrix
dincyjain
 
PPTX
Linked List - Insertion & Deletion
Afaq Mansoor Khan
 
Recursive Function
Harsh Pathak
 
Sparse matrix and its representation data structure
Vardhil Patel
 
Static Data Members and Member Functions
MOHIT AGARWAL
 
Data Structures - Lecture 7 [Linked List]
Muhammad Hammad Waseem
 
Strings
Mitali Chugh
 
OOP Assignment 03.pdf
ARSLANMEHMOOD47
 
Presentation on queue
Rojan Pariyar
 
Array in Java
Ali shah
 
Strings in Java
Abhilash Nair
 
Data Structures - Lecture 9 [Stack & Queue using Linked List]
Muhammad Hammad Waseem
 
Class and object in C++
rprajat007
 
Unit 4. Operators and Expression
Ashim Lamichhane
 
Data Structure and Algorithms Binary Search Tree
ManishPrajapati78
 
Data abstraction and object orientation
Hoang Nguyen
 
linked list in Data Structure, Simple and Easy Tutorial
Afzal Badshah
 
Java Data Types
Spotle.ai
 
Unit 4 python -list methods
narmadhakin
 
Sparse matrix
dincyjain
 
Linked List - Insertion & Deletion
Afaq Mansoor Khan
 

Viewers also liked (14)

PPTX
UNIT 10. Files and file handling in C
Ashim Lamichhane
 
PPTX
Unit 8. Pointers
Ashim Lamichhane
 
PPTX
Unit 7. Functions
Ashim Lamichhane
 
PPTX
Unit 11. Graphics
Ashim Lamichhane
 
PPT
File handling in c
Vikash Dhal
 
PPT
File handling in c
David Livingston J
 
PPTX
Unit 2. Elements of C
Ashim Lamichhane
 
PPT
File handling in 'C'
Gaurav Garg
 
PPT
File in C Programming
Sonya Akter Rupa
 
PPTX
Unit 5. Control Statement
Ashim Lamichhane
 
PPTX
Unit 9. Structure and Unions
Ashim Lamichhane
 
PPTX
Unit 3. Input and Output
Ashim Lamichhane
 
PPT
File in c
Prabhu Govind
 
PPTX
File handling in C
Kamal Acharya
 
UNIT 10. Files and file handling in C
Ashim Lamichhane
 
Unit 8. Pointers
Ashim Lamichhane
 
Unit 7. Functions
Ashim Lamichhane
 
Unit 11. Graphics
Ashim Lamichhane
 
File handling in c
Vikash Dhal
 
File handling in c
David Livingston J
 
Unit 2. Elements of C
Ashim Lamichhane
 
File handling in 'C'
Gaurav Garg
 
File in C Programming
Sonya Akter Rupa
 
Unit 5. Control Statement
Ashim Lamichhane
 
Unit 9. Structure and Unions
Ashim Lamichhane
 
Unit 3. Input and Output
Ashim Lamichhane
 
File in c
Prabhu Govind
 
File handling in C
Kamal Acharya
 
Ad

Similar to Unit 6. Arrays (20)

PPTX
Ch-11-Arrays.ppt-1.pptx eurhrbdhdbdhrhdhdh
zakiking612
 
PPTX
Array
Deep Shah
 
PPTX
Module_3_Arrays - Updated.pptx............
ChiragKankani
 
PPTX
Array 2 hina
heena94
 
PPTX
Array
Fahuda E
 
PDF
[ITP - Lecture 15] Arrays & its Types
Muhammad Hammad Waseem
 
PPT
Chapter 10.ppt
MithuBose3
 
PPT
Fp201 unit4
rohassanie
 
PPTX
Array
PralhadKhanal1
 
PDF
Homework Assignment – Array Technical DocumentWrite a technical .pdf
aroraopticals15
 
PPTX
Chapter 13.pptx
AnisZahirahAzman
 
PPT
Basics of Data structure using C describing basics concepts
shanthidl1
 
PDF
02 arrays
Rajan Gautam
 
PPTX
Arrays
shillpi29
 
PDF
Array&amp;string
chanchal ghosh
 
PPTX
Arrays
Neeru Mittal
 
PDF
Arrays-Computer programming
nmahi96
 
PDF
Arrays In C
yndaravind
 
PDF
arraysfor engineering students sdf ppt on arrays
ruvirgandhi123
 
PPTX
UNIT-5_Array in c_part1.pptx
sangeeta borde
 
Ch-11-Arrays.ppt-1.pptx eurhrbdhdbdhrhdhdh
zakiking612
 
Array
Deep Shah
 
Module_3_Arrays - Updated.pptx............
ChiragKankani
 
Array 2 hina
heena94
 
Array
Fahuda E
 
[ITP - Lecture 15] Arrays & its Types
Muhammad Hammad Waseem
 
Chapter 10.ppt
MithuBose3
 
Fp201 unit4
rohassanie
 
Homework Assignment – Array Technical DocumentWrite a technical .pdf
aroraopticals15
 
Chapter 13.pptx
AnisZahirahAzman
 
Basics of Data structure using C describing basics concepts
shanthidl1
 
02 arrays
Rajan Gautam
 
Arrays
shillpi29
 
Array&amp;string
chanchal ghosh
 
Arrays
Neeru Mittal
 
Arrays-Computer programming
nmahi96
 
Arrays In C
yndaravind
 
arraysfor engineering students sdf ppt on arrays
ruvirgandhi123
 
UNIT-5_Array in c_part1.pptx
sangeeta borde
 
Ad

More from Ashim Lamichhane (10)

PPTX
Searching
Ashim Lamichhane
 
PPTX
Sorting
Ashim Lamichhane
 
PPTX
Tree - Data Structure
Ashim Lamichhane
 
PPTX
Linked List
Ashim Lamichhane
 
PPTX
Queues
Ashim Lamichhane
 
PPTX
The Stack And Recursion
Ashim Lamichhane
 
PPTX
Algorithm big o
Ashim Lamichhane
 
PPTX
Algorithm Introduction
Ashim Lamichhane
 
PPTX
Introduction to data_structure
Ashim Lamichhane
 
PPTX
Unit 1. Problem Solving with Computer
Ashim Lamichhane
 
Searching
Ashim Lamichhane
 
Tree - Data Structure
Ashim Lamichhane
 
Linked List
Ashim Lamichhane
 
The Stack And Recursion
Ashim Lamichhane
 
Algorithm big o
Ashim Lamichhane
 
Algorithm Introduction
Ashim Lamichhane
 
Introduction to data_structure
Ashim Lamichhane
 
Unit 1. Problem Solving with Computer
Ashim Lamichhane
 

Recently uploaded (20)

PPTX
Growth and development and milestones, factors
BHUVANESHWARI BADIGER
 
PPTX
ASRB NET 2023 PREVIOUS YEAR QUESTION PAPER GENETICS AND PLANT BREEDING BY SAT...
Krashi Coaching
 
PPTX
How to Set Maximum Difference Odoo 18 POS
Celine George
 
PDF
Chapter-V-DED-Entrepreneurship: Institutions Facilitating Entrepreneurship
Dayanand Huded
 
PDF
ARAL_Orientation_Day-2-Sessions_ARAL-Readung ARAL-Mathematics ARAL-Sciencev2.pdf
JoelVilloso1
 
PPTX
grade 5 lesson matatag ENGLISH 5_Q1_PPT_WEEK4.pptx
SireQuinn
 
PPTX
BANDHA (BANDAGES) PPT.pptx ayurveda shalya tantra
rakhan78619
 
PPT
Talk on Critical Theory, Part II, Philosophy of Social Sciences
Soraj Hongladarom
 
PDF
CONCURSO DE POESIA “POETUFAS – PASSOS SUAVES PELO VERSO.pdf
Colégio Santa Teresinha
 
PDF
0725.WHITEPAPER-UNIQUEWAYSOFPROTOTYPINGANDUXNOW.pdf
Thomas GIRARD, MA, CDP
 
PPTX
How to Convert an Opportunity into a Quotation in Odoo 18 CRM
Celine George
 
PDF
CEREBRAL PALSY: NURSING MANAGEMENT .pdf
PRADEEP ABOTHU
 
PDF
The Different Types of Non-Experimental Research
Thelma Villaflores
 
PDF
ARAL-Orientation_Morning-Session_Day-11.pdf
JoelVilloso1
 
PPTX
STAFF DEVELOPMENT AND WELFARE: MANAGEMENT
PRADEEP ABOTHU
 
PPTX
MENINGITIS: NURSING MANAGEMENT, BACTERIAL MENINGITIS, VIRAL MENINGITIS.pptx
PRADEEP ABOTHU
 
PDF
Dimensions of Societal Planning in Commonism
StefanMz
 
PPSX
HEALTH ASSESSMENT (Community Health Nursing) - GNM 1st Year
Priyanshu Anand
 
PPTX
THE TAME BIRD AND THE FREE BIRD.pptxxxxx
MarcChristianNicolas
 
PPTX
HYDROCEPHALUS: NURSING MANAGEMENT .pptx
PRADEEP ABOTHU
 
Growth and development and milestones, factors
BHUVANESHWARI BADIGER
 
ASRB NET 2023 PREVIOUS YEAR QUESTION PAPER GENETICS AND PLANT BREEDING BY SAT...
Krashi Coaching
 
How to Set Maximum Difference Odoo 18 POS
Celine George
 
Chapter-V-DED-Entrepreneurship: Institutions Facilitating Entrepreneurship
Dayanand Huded
 
ARAL_Orientation_Day-2-Sessions_ARAL-Readung ARAL-Mathematics ARAL-Sciencev2.pdf
JoelVilloso1
 
grade 5 lesson matatag ENGLISH 5_Q1_PPT_WEEK4.pptx
SireQuinn
 
BANDHA (BANDAGES) PPT.pptx ayurveda shalya tantra
rakhan78619
 
Talk on Critical Theory, Part II, Philosophy of Social Sciences
Soraj Hongladarom
 
CONCURSO DE POESIA “POETUFAS – PASSOS SUAVES PELO VERSO.pdf
Colégio Santa Teresinha
 
0725.WHITEPAPER-UNIQUEWAYSOFPROTOTYPINGANDUXNOW.pdf
Thomas GIRARD, MA, CDP
 
How to Convert an Opportunity into a Quotation in Odoo 18 CRM
Celine George
 
CEREBRAL PALSY: NURSING MANAGEMENT .pdf
PRADEEP ABOTHU
 
The Different Types of Non-Experimental Research
Thelma Villaflores
 
ARAL-Orientation_Morning-Session_Day-11.pdf
JoelVilloso1
 
STAFF DEVELOPMENT AND WELFARE: MANAGEMENT
PRADEEP ABOTHU
 
MENINGITIS: NURSING MANAGEMENT, BACTERIAL MENINGITIS, VIRAL MENINGITIS.pptx
PRADEEP ABOTHU
 
Dimensions of Societal Planning in Commonism
StefanMz
 
HEALTH ASSESSMENT (Community Health Nursing) - GNM 1st Year
Priyanshu Anand
 
THE TAME BIRD AND THE FREE BIRD.pptxxxxx
MarcChristianNicolas
 
HYDROCEPHALUS: NURSING MANAGEMENT .pptx
PRADEEP ABOTHU
 

Unit 6. Arrays

  • 2. Arrays • An array is 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. • Array is a data structure that store a number of data items as a single entity (object) . • The individual data items are called elements and all of them have same data types. • Array is used when multiple data items have common characteristics are required. Ashim Lamichhane 2
  • 3. • Instead of declaring, • such as number0, number1, ..., and number99, • We declare one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent individual variables. • A specific element in an array is accessed by an index. • All arrays consist of contiguous memory locations. • The lowest address corresponds to the first element and the highest address to the last element. Ashim Lamichhane 3
  • 4. How to Define an Array? • An Array is defined as following <storage_class> <type-of-array> <name-of-array> [<number of elements in array>]; • storage_class: it may be auto, register, static and extern. [Optional] • type-of-array: It is the type of elements that an array stores. E.x. ‘char’, ‘int’. • name-of-array: This is the name that is given to array. At least the name should be in context with what is being stored in the array. • [number of elements]: This value in subscripts [] indicates the number of elements the array stores. Ashim Lamichhane 4
  • 5. For example (ONE DIMENSIONAL ARRAY) • an array of five characters can be defined as : • char arr[5]; • to declare a 10-element array called balance of type double: • double balance[10]; • int num[35]; /* An integer array of 35 elements */ • char ch[10]; /* An array of characters for 10 elements */ Ashim Lamichhane 5
  • 6. Initializing Array • You can initialize an array in C either one by one or using a single statement as follows − double balance[5] = {1000.0, 2.0, 3.4, 7.0, 50.0}; • The number of values between braces { } cannot be larger than the number of elements that we declare for the array between square brackets [ ]. • If you omit the size of the array, an array just big enough to hold the initialization is created. Therefore, if you write − double balance[] = {1000.0, 2.0, 3.4, 7.0, 50.0}; • Ex: balance[4] = 50.0; • The above statement assigns the 5th element in the array with a value of 50.0. Ashim Lamichhane 6
  • 7. • All arrays have 0 as the index of their first element which is also called the base index and the last index of an array will be total size of the array minus 1. • Shown below is the pictorial representation of the array we discussed earlier: double balance[5] = {1000.0, 2.0, 3.4, 7.0, 50.0}; Ashim Lamichhane 7
  • 8. Accessing Array Elements • An element is accessed by indexing the array name. • This is done by placing the index of the element within square brackets after the name of the array. For example − double salary = balance[4]; • The above statement will take the 10th element from the array and assign the value to salary variable. Ashim Lamichhane 8
  • 9. example #include <stdio.h> int main () { int n[ 10 ]; /* n is an array of 10 integers */ int i,j; /* initialize elements of array n to 0 */ for ( i = 0; i < 10; i++ ) { n[ i ] = i + 100; /* set element at location i to i + 100 */ } /* output each array element's value */ for (j = 0; j < 10; j++ ) { printf("Element[%d] = %dn", j, n[j] ); } return 0; } Ashim Lamichhane 9
  • 10. [IMP] WAP to sort n numbers in ascending order. #include <stdio.h> int main(void){ int nums[50],i,j,n,temp; printf("How many Numbers are there?t"); scanf("%d",&n); printf("nEnter %d numbers: n",n); for(i=0;i<n;i++){ scanf("%d",&nums[i]); } for (i = 0; i < n-1; ++i){ for (j=i+1; j < n;j++) { if(nums[i]>nums[j]){ temp=nums[i]; nums[i]=nums[j]; nums[j]=temp; } } } printf("nThe numbers in ascending order:n"); for(i=0; i<n;i++){ printf("t%d",nums[i]); } printf("n"); } Ashim Lamichhane 10
  • 11. Characteristics Of An Array • The declaration of int a[5] is nothing but creation of 5 variables of integer type in the memory. • All the elements of an array share the same name. distinguished from one another by element number or array index. • Any element can be modified separately without disturbing another element. • Element basis operation should be carried out rather than taking as a whole. Ashim Lamichhane 11
  • 12. Questions (Classwork) • WAP to read 10 integers from keyboard and display entered numbers on the screen. • WAP that reads mark’s percentage in an examination of 10 students and deviation percentage from average of students. • [IMP] WAP to find the highest and second last smallest number of an element. Ashim Lamichhane 12
  • 13. Multi Dimensional Array • Have more than one dimensions. • Separate pair of square brackets is required for each subscript or dimension or index. • Two dimensional arrays will require two pairs of square brackets; three dimensional with three pairs and so on. • Two dimensional is also called matrix. Ashim Lamichhane 13
  • 14. storage_class data_type array_name[dim1] [dim2] … [dimn]; • Here, dim1,dim2…dimn are positive valued integer expressions that indicate the number of array elements associated with each subscript. • m*n two dimensional array can be thought as tables of values having m rows and n columns. • For ex int x[3][3] can be shown as follows: Col 1 Col 2 Col 3 ROW 1 X[0][0] X[0][1] X[0][2] ROW 2 X[1][0] X[1][1] X[1][2] ROW 3 X[2][0] X[2][1] X[2][2] Ashim Lamichhane 14
  • 15. Declaration of two-dimensional array • Like one dimensional array, two dimensional arrays must also be declared before using it. • The syntax: [storage_class] data_type array_name[row_size][col_size]; • Example: • int matrix[2][3]; /* matrix is 2-D array which has 2 rows and 3 columns */ • float m[10][20]; • char students[10][15]; Ashim Lamichhane 15
  • 16. Initialization of 2-D array • int marks[2][3]={ {2,4,6}, {8,10,12} }; //is equivalent to • marks[0][0]=2; marks[0][1]=4; marks[0][2]=6; • marks[1][0]=8; marks[1][1]=10; marks[1][2]=12; • int marks1[ ][3]= { {2,4,6}, {8,10,12} }; // is equivalent to • marks1[0][0]=2; marks1[0][1]=4; marks1[0][2]=6; • marks1[1][0]=8; marks1[1][1]=10; marks1[1][2]=12; • int marks2[2][3]={2,4,6,8,10,12}; • Int marks3[][3]={2,4,6,8,10,12}; ERRORS: • Int marks[3][]={2,4,6,8,10,12}; int marks[ ][ ]={2,4,6,8,10}; Ashim Lamichhane 16
  • 17. Accessing 2-D array elements • In 2-D array, the first dimension specifies number of rows and second specifies columns. • A row is 1-D array. 2-D array contains multiple rows(i.e. 1-D arrays). Thus 2-D array is an array of 1-D arrays. • 2-D array is traversed row by row(i.e. every column elements in first row are traversed first and then column elements of second row are traversed and so on.) • Nested loop is used to traverse the 2-D array. Ashim Lamichhane 17
  • 18. • Let us consider following 2-D array marks of size 4*3 • i.e. matrix having 4 rows and 3 columns • The Array is traversed in the following order: 35 ->10 ->11 ->34 ->90 ->76 ->13 ->8 ->5 ->76 ->4 ->1 • i.e marks[0][0] -> marks[0][1] -> marks[0][2] -> marks[1][0] -> marks[1][1] -> marks[1][2] -> marks[2][0] -> marks[2][1] -> marks[2][2] -> marks[3][0] -> marks[3][1] -> marks[3][2]. 35 10 11 34 90 76 13 8 5 76 4 1 Ashim Lamichhane 18
  • 19. #include <stdio.h> int main(void){ int matrix[2][3],i,j; for(i=0;i<2;i++){ for(j=0;j<3;j++){ printf("Enter Matrix[%d][%d]: ",i,j); scanf("%d",&matrix[i][j]); } } printf("The Entered Matrxn"); for(i=0;i<2;i++){ for(j=0;j<3;j++){ printf("%dt",matrix[i][j]); } printf("n"); } } Ashim Lamichhane 19
  • 20. WAP: Sum of matrix //FOR FIRST MATRIX A for(i=0;<m;i++){ for(j=0;j<n;j++){ scanf(“%d”,&a[i][j]); } } //FOR FIRST MATRIX B for(i=0;<m;i++){ for(j=0;j<n;j++){ scanf(“%d”,&b[i][j]); } } //FOR sum for(i=0;<m;i++){ for(j=0;j<n;j++){ sum[i][j]=a[i][j]+b[i][j]; } } Ashim Lamichhane 20
  • 21. Passing arrays to function • It is possible to pass the value of an array element and even an entire array as an argument to a function. • To pass an entire array to a function, the array name must appear by itself, without brackets or subscripts, as an actual argument in function call statement. • When declaring a one-dimensional array as a formal argument, the array name is written with a pair of empty square brackets. The size of the array is not specified within the formal argument declaration. Ashim Lamichhane 21
  • 22. • Syntax for function call passing array as argument, function_name(array_name) • Syntax for function prototype which accepts array return_type function_name(data_type array_name[]); Or return_type function_name(data_type *pointer_variable); • When array is passed to a function, the values of the array elements are not passed to the function rather the array name is interpreted as the address of the first array element. • The address assigned to the corresponding formal argument when the function is called. • The formal argument therefore becomes a pointer to the first array element. Ashim Lamichhane 22
  • 23. #include <stdio.h> void display(int n){ printf("%dt", n ); } int main(void){ int nums[5]={100,23,44,3,65},i; printf("nThe content of array is: n"); for (int i = 0; i < 5; i++){ display(nums[i]); } } Ashim Lamichhane 23
  • 24. WAP to illustrate passing an entire array to a function #include <stdio.h> void change(int a[]){ a[0]=10;a[1]=20;a[2]=30;a[3]=40;a[4]=50; } int main(void){ int nums[5]={100,23,44,3,65},i; printf("nBEFORE FUNCTION CALL: n"); for (int i = 0; i < 5; i++) { printf("t%d",nums[i]); } printf("n"); change(nums); /* PASSING ARRAYS NUMS TO FUNCTION */ printf("nAFTER FUNCTION CALLn"); for (int i = 0; i < 5; i++) { printf("t%d",nums[i]); } printf("n"); } Ashim Lamichhane 24
  • 25. Arrays and Strings • In C programming, array of character are called strings. A string is terminated by null character 0. For example: Ex. "c string tutorial" • Here, "c string tutorial" is a string. When, compiler encounters strings, it appends null character at the end of string. • Strings are actually one-dimensional array of characters terminated by a null character '0'. • If you follow the rule of array initialization then you can write the above statement as follows − char greeting[] = "Hello"; Ashim Lamichhane 25 c s t r i n g t u t o r i a l 0
  • 26. char greeting[] = "Hello"; Following is the memory presentation of the above defined string in C − Actually, you do not place the null character at the end of a string constant. The C compiler automatically places the '0' at the end of the string when it initializes the array. Ashim Lamichhane 26 INDEX 0 1 2 3 4 5 VARIABLE H e l l o 0 ADDRESS 0x23452 0x23453 0x23454 0x23455 0x23456 0x23457
  • 27. Initialization of strings • In C, string can be initialized in different number of ways. char c[]="abcd"; OR, char c[5]="abcd"; OR, char c[]={'a','b','c','d','0'}; OR; char c[5]={'a','b','c','d','0'}; Ashim Lamichhane 27 C[0] C[1] C[2] C[3] C[4] a b c d 0
  • 28. Declaration of strings • Strings are declared in C in similar manner as arrays. Only difference is that, strings are of char type. char s[5]; • Strings can also be declared using pointer. char *p (will be discussed in future chapters) Ashim Lamichhane 28 s[0] s[1] s[2] s[3] s[4]
  • 29. • Let us try to print the above mentioned string − #include <stdio.h> int main () { char greeting[6] = {'H', 'e', 'l', 'l', 'o', '0'}; printf("Greeting message: %sn", greeting ); return 0; } OUTPUT: Greeting message: Hello Ashim Lamichhane 29
  • 30. Write a C program to illustrate how to read string from terminal. #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. NOTE: Here, program will ignore Ritchie because, scanf() function takes only string before the white space. Ashim Lamichhane 30
  • 31. C program to read line of text manually. #include <stdio.h> int main(){ char name[30],ch; int i=0; printf("Enter name: "); while(ch!='n') // terminates if user hit enter { ch=getchar(); name[i]=ch; i++; } name[i]='0'; // inserting null character at end printf("Name: %s",name); return 0; } This process to take string is tedious. There are predefined functions gets() and puts in C language to read and display string respectively. Ashim Lamichhane 31
  • 32. int main(){ char name[30]; printf("Enter name: "); gets(name); //Function to read string from user. printf("Name: "); puts(name); //Function to display string. return 0; } • Both, the above program has same output below: • Output Enter name: Tom Hanks Name: Tom Hanks Ashim Lamichhane 32
  • 33. Passing Strings to Functions #include <stdio.h> void Display(char ch[]); int main(){ char c[50]; printf("Enter string: "); gets(c); Display(c); // Passing string c to function. return 0; } void Display(char ch[]){ printf("String Output: "); puts(ch); } • Here, string c is passed from main() function to user-defined function Display(). In function declaration, ch[] is the formal argument. Ashim Lamichhane 33
  • 34. C supports a wide range of functions that manipulate null-terminated strings − S.N. Function & Purpose(these functions are defined in header file string.h) 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 strrev(s1); Returns reverse of a string s1 Ashim Lamichhane 34
  • 35. #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) : %sn", str3 ); /* concatenates str1 and str2 */ strcat( str1, str2); printf("strcat( str1, str2): %sn", str1 ); /* total lenghth of str1 after concatenation */ len = strlen(str1); printf("strlen(str1) : %dn", len ); return 0; } Ashim Lamichhane 35 Strcpy(str3,str1) Hello Strcat(str1,str2) HelloWorld Strlen(str1) 10
  • 36. Please do check Google Drive for Assignment Ashim Lamichhane 36
  • 37. Reference • http://www.thegeekstuff.com/2011/12/c-arrays/ • http://www.tutorialspoint.com/cprogramming/c_arrays.htm • http://c.learncodethehardway.org/book/ex10.html • http://beginnersbook.com/2014/01/c-arrays-example/ • A Textbook Of C programming by Ram Datta Bhatta • http://www.cprogramming.com/tutorial/c/lesson9.html • http://www.programiz.com/c-programming/c-strings Ashim Lamichhane 38