SlideShare ist ein Scribd-Unternehmen logo
1 von 38
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

Weitere ähnliche Inhalte

Was ist angesagt?

Was ist angesagt? (20)

linked list in data structure
linked list in data structure linked list in data structure
linked list in data structure
 
Queue - Data Structure - Notes
Queue - Data Structure - NotesQueue - Data Structure - Notes
Queue - Data Structure - Notes
 
concept of Array, 1D & 2D array
concept of Array, 1D & 2D arrayconcept of Array, 1D & 2D array
concept of Array, 1D & 2D array
 
UNIT II LINEAR DATA STRUCTURES – STACKS, QUEUES
UNIT II 	LINEAR DATA STRUCTURES – STACKS, QUEUES	UNIT II 	LINEAR DATA STRUCTURES – STACKS, QUEUES
UNIT II LINEAR DATA STRUCTURES – STACKS, QUEUES
 
Structures and Unions
Structures and UnionsStructures and Unions
Structures and Unions
 
Input and output in C++
Input and output in C++Input and output in C++
Input and output in C++
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
 
Programming in c
Programming in cProgramming in c
Programming in c
 
Symbol table in compiler Design
Symbol table in compiler DesignSymbol table in compiler Design
Symbol table in compiler Design
 
16717 functions in C++
16717 functions in C++16717 functions in C++
16717 functions in C++
 
Abstract data types
Abstract data typesAbstract data types
Abstract data types
 
Programming in c Arrays
Programming in c ArraysProgramming in c Arrays
Programming in c Arrays
 
Unit 1 introduction to data structure
Unit 1   introduction to data structureUnit 1   introduction to data structure
Unit 1 introduction to data structure
 
Stack and Queue
Stack and Queue Stack and Queue
Stack and Queue
 
Control Flow Statements
Control Flow Statements Control Flow Statements
Control Flow Statements
 
Infix to postfix conversion
Infix to postfix conversionInfix to postfix conversion
Infix to postfix conversion
 
Symbol Table
Symbol TableSymbol Table
Symbol Table
 
Character set of c
Character set of cCharacter set of c
Character set of c
 
Stacks
StacksStacks
Stacks
 
File handling in c
File handling in cFile handling in c
File handling in c
 

Andere mochten auch

Andere mochten auch (11)

UNIT 10. Files and file handling in C
UNIT 10. Files and file handling in CUNIT 10. Files and file handling in C
UNIT 10. Files and file handling in C
 
Unit 8. Pointers
Unit 8. PointersUnit 8. Pointers
Unit 8. Pointers
 
Unit 11. Graphics
Unit 11. GraphicsUnit 11. Graphics
Unit 11. Graphics
 
File handling in c
File handling in c File handling in c
File handling in c
 
Unit 2. Elements of C
Unit 2. Elements of CUnit 2. Elements of C
Unit 2. Elements of C
 
File handling in 'C'
File handling in 'C'File handling in 'C'
File handling in 'C'
 
File in C Programming
File in C ProgrammingFile in C Programming
File in C Programming
 
Unit 9. Structure and Unions
Unit 9. Structure and UnionsUnit 9. Structure and Unions
Unit 9. Structure and Unions
 
Unit 3. Input and Output
Unit 3. Input and OutputUnit 3. Input and Output
Unit 3. Input and Output
 
File in c
File in cFile in c
File in c
 
File handling in C
File handling in CFile handling in C
File handling in C
 

Ähnlich wie Unit 6. Arrays

Homework Assignment – Array Technical DocumentWrite a technical .pdf
Homework Assignment – Array Technical DocumentWrite a technical .pdfHomework Assignment – Array Technical DocumentWrite a technical .pdf
Homework Assignment – Array Technical DocumentWrite a technical .pdf
aroraopticals15
 

Ähnlich wie Unit 6. Arrays (20)

ARRAYS
ARRAYSARRAYS
ARRAYS
 
Arrays and Strings
Arrays and Strings Arrays and Strings
Arrays and Strings
 
Arrays 1D and 2D , and multi dimensional
Arrays 1D and 2D , and multi dimensional Arrays 1D and 2D , and multi dimensional
Arrays 1D and 2D , and multi dimensional
 
Algo>Arrays
Algo>ArraysAlgo>Arrays
Algo>Arrays
 
Introduction to Arrays in C
Introduction to Arrays in CIntroduction to Arrays in C
Introduction to Arrays in C
 
Arrays
ArraysArrays
Arrays
 
Array
ArrayArray
Array
 
Arrays
ArraysArrays
Arrays
 
Array and its types and it's implemented programming Final.pdf
Array and its types and it's implemented programming Final.pdfArray and its types and it's implemented programming Final.pdf
Array and its types and it's implemented programming Final.pdf
 
Programming in c arrays
Programming in c   arraysProgramming in c   arrays
Programming in c arrays
 
Array
ArrayArray
Array
 
Arrays
ArraysArrays
Arrays
 
Arrays
ArraysArrays
Arrays
 
Arrays and library functions
Arrays and library functionsArrays and library functions
Arrays and library functions
 
Homework Assignment – Array Technical DocumentWrite a technical .pdf
Homework Assignment – Array Technical DocumentWrite a technical .pdfHomework Assignment – Array Technical DocumentWrite a technical .pdf
Homework Assignment – Array Technical DocumentWrite a technical .pdf
 
Lecture 15 - Array
Lecture 15 - ArrayLecture 15 - Array
Lecture 15 - Array
 
C Programming : Arrays
C Programming : ArraysC Programming : Arrays
C Programming : Arrays
 
Array assignment
Array assignmentArray assignment
Array assignment
 
Arrays_and_Strings_in_C_Programming.pptx
Arrays_and_Strings_in_C_Programming.pptxArrays_and_Strings_in_C_Programming.pptx
Arrays_and_Strings_in_C_Programming.pptx
 
Arrays
ArraysArrays
Arrays
 

Mehr von Ashim Lamichhane

Mehr von Ashim Lamichhane (10)

Searching
SearchingSearching
Searching
 
Sorting
SortingSorting
Sorting
 
Tree - Data Structure
Tree - Data StructureTree - Data Structure
Tree - Data Structure
 
Linked List
Linked ListLinked List
Linked List
 
Queues
QueuesQueues
Queues
 
The Stack And Recursion
The Stack And RecursionThe Stack And Recursion
The Stack And Recursion
 
Algorithm big o
Algorithm big oAlgorithm big o
Algorithm big o
 
Algorithm Introduction
Algorithm IntroductionAlgorithm Introduction
Algorithm Introduction
 
Introduction to data_structure
Introduction to data_structureIntroduction to data_structure
Introduction to data_structure
 
Unit 1. Problem Solving with Computer
Unit 1. Problem Solving with Computer   Unit 1. Problem Solving with Computer
Unit 1. Problem Solving with Computer
 

Kürzlich hochgeladen

BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
SoniaTolstoy
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
QucHHunhnh
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
heathfieldcps1
 

Kürzlich hochgeladen (20)

Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdf
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room service
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 

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