SlideShare une entreprise Scribd logo
1  sur  18
How to store lots of values of same type?
 We have seen many data types so far
 int, float, char, etc.
 We can use a variable to store a single value of some data type, e.g.,
 int x = 2; // variable x stores one integer value
 float x = 2.3; // variable x stores a one float value
 char x = ‘c’; // variable x stores one char value
 What if we want to store several values, all of same data type?
 Example 1: Marks of all ESC101 students in Major Quiz 1 (all floats)
 Example 2: Roll numbers of all ESC101 students (all int)
 Example 3: Final grade of all ESC101 students (all char)
1
How to store lots of values of same type?
 Consider storing Minor Quiz marks of all ESC111 students
 This is very time consuming, inelegant, and boring
 Arrays provide a better and more efficient way of doing such things
2
float marks1, marks2, marks3, .... ,marks500;
scanf(“%f”, &marks1);
scanf(“%f”, &marks2);
...
scanf(“%f”, &marks500);
Arrays
 Not a new data type but a “data structure” (a collection of variables)
 Enables storing multiple values of the same data type
 Specification/declaration of an array needs the following
 A data type (data type of values to be stored; all must be of same type)
 A name (same naming convention as variables)
 A size (how many values to be stored)
 An example of array declaration:
3
float marks[500];
Data type
Name Size
Size is an integer in
square brackets
Arrays: Basic Syntax
 Each value within the array is called “element” of the array
 Each element is accessed using a non-negative integer-valued index
 First index is 0 (index of first element)
 Last index is array size minus one (index of last element)
 Syntax to access/use each element of the array
name_of_array[index]
 For example:
 marks[0] is the first element of an array named marks
 marks[1] is the second element of array marks
 marks[499] is the last element of array marks 4
Index is an
integer in square
brackets
In some other languages
(such as Python), array
indexing starts with 1
Arrays: Basic Syntax
 Array index needs to be within limits (0 to array size - 1)
 For an array declared as marks[500]
 Index -1 is invalid (may give segmentation fault, also known as “segfault”)
 Index 510 is invalid (may give segfault)
 Index 500 is also invalid (recall that 499 is the index of last element)
 Array index need not be a constant integer,
 Can also be a variable/expression (but only int)
 Example: marks[i] or marks[2*i + 1] where i is an integer
 Never use a float/double as index
5
Arrays: Storage in memory
 A single variable (int/float/char etc) is stored in a single box in memory
 An array is stored in several consecutive boxes in memory (number of
these boxes is equal to the size of the array)
 More on storage of arrays when we study Pointers
6
int a = 2;
float b = 3.2;
a b
2 3.2
float marks[500];
marks[0] marks[1] marks[2] marks[499]
Array name is like street
name, index is like house
number
Array: Declaration and Initialization
Can be initialized at time of declaration itself
Can be partly initialized as well
However, if not initialized in same line with declaration, have
to be initialized one by one!
int a[6] = {3,7,6,2,1,0};
int a[6] = {3,7,6};
a 3 7 6 2 1 0
a 3 7 6
int a[6];
a = {3,7,6,2,1,0};
int a[6];
a[2] = 6;
Array elements are
comma separated
7
Array: Declaration and Initialization
Can be initialized at time of declaration itself
Can be partly initialized as well
Over initialization may crash
Better way to initialize is the following
Warning: uninitialized arrays contain garbage, not zeros
int a[6] = {3,7,6,2,1,0};
int a[6] = {3,7,6};
a 3 7 6 2 1 0
a 3 7 6
int a[6] = {1,2,3,4,5,6,7,8,9};
int a[] = {1,2,3,4,5,6,7,8,9};
I will figure out how
much space needed
No need to specify
the array size during
declaration
8
Array: Declaration and Initialization
 Can declare the array first and initialize its elements later
 The later initialization can be done using user-provided values (e.g.,
using scanf), or some expression, or using some fixed values
int i,tmp,a[5];
for(i=0;i<5;i++){
scanf(“%d”,&tmp);
a[i] = tmp;
}
Read a use-
provided value
Assign the read
value to the ith
element of the
array
9
Can I run the
loop as
for(i=1;i<=5;i++)?
Yes, if you use
a[i-1] = tmp; in
loop’s body
Array: Declaration and Initialization
 Can declare the array first and initialize its elements later
 The later initialization can be done using user-provided values (e.g.,
using scanf), or some expression, or using some fixed value
int i,a[5];
for(i=0;i<5;i++){
scanf(“%d”,&a[i]);
}
Directly read a user
provided value into the
ith element of the array
(the tmp variable is not
needed)
Note: &a[i] is evaluated
as &(a[i]) since [] has
higher precedence than &
A shortcut for
reading user
provided
values 10
Operator Name Symbol/Sign Associativity
Brackets, array subscript, Post
increment/decrement
(), [] ++, -- Left
Unary negation, Pre
increment/decrement, NOT
-, ++, --, ! Right
Multiplication/division/
remainder
*, /, % Left
Addition/subtraction +, - Left
Relational <, <=, >, >= Left
Relational ==, != Left
AND && Left
OR || Left
Conditional ? : Right
Assignment, Compound
assignment
=, +=, -=, *=, /=,
%=
Right
11
Array: Declaration and Initialization
 Can declare the array first and initialize its elements later
 The later initialization can be done using user-provided values (e.g.,
using scanf), or some expression, or using some fixed value
int i,a[5];
for(i=0;i<5;i++){
a[i] = i+1;
}
Assign a value of
expression i+1 to
the ith element of
the array
12
1 2 3 4 5
a[0] a[1] a[2] a[3] a[4]
Array: Declaration and Initialization
 Can declare the array first and initialize its elements later
 The later initialization can be done using user-provided values (e.g.,
using scanf), or some expression, or using some fixed value
Assign a fixed
(constant) value 10
to the ith element of
the array
int i,a[5];
for(i=0;i<5;i++){
a[i] = 10;
}
13
10 10 10 10 10
a[0] a[1] a[2] a[3] a[4]
Tracing the execution of an array based program
include <stdio.h>
int main () {
int a[5];
int i;
for (i=0; i < 5; i= i+1) {
a[i] = i+1;
}
return 0;
}
a[0] a[1] a[2] a[3] a[4]
i
Let us trace the
execution of the program.
0
Statement becomes a[0] =0+1;
Statement becomes a[1] =1+1;
Statement becomes a[2] =2+1;
1
1
2
2
3
3
Statement becomes a[3] = 3+1;
Statement becomes a[4] = 4+1;
4
4
5
5
14
Arrays: Some Example Programs
 Create an integer array of size 100
 Initialize elements with even index as 0
 Initialize elements with odd index as 1
int i,a[100];
for(i=0; i<100; i=i+1){
if(i%2==0) a[i] = 0;
else a[i] = 1;
}
Method 1
15
Arrays: Some Example Programs
 Create an integer array of size 100
 Initialize elements with even index as 0
 Initialize elements with odd index as 1
int i,a[100];
for(i=0; i<100; i=i+2){
a[i] = 0;
a[i+1] = 1;
}
Method 2,
without if-else
Incrementing the
loop counter by 2
This for loop will run
50 times. Each
iteration will assign
values to 2 elements,
one at odd index,
one at even index
16
Arrays: Some Example Programs
 Check whether a sequence of numbers is a palindrome sequence
11
Greek origin word:
palin = again,
dromos = direction
Palindrome: Forward and
Reverse gives the same
sequence
Some palindromes:
1 2 3 4 5 4 3 2 1
1 2 3 3 2 1
Some non-palindromes:
1 2 3 4 5
1 2 3 3 4 1
9 0 4 0 8
int main(){
int a[100], temp, len = 0, i, flag = 1;
while(1){
scanf("%d", &temp);
if(temp == -1)
break;
a[len++] = temp;
}
for(i = 0; i < len; i++)
if(a[i] != a[len-i-1])
flag = 0;
if(flag) printf("YES");
else printf("NO");
return 0;
}
The while(1) loop keeps reading numbers
until user enters -1, store each number as
an element of the array named a
After the while(1) loop exits, len is the
size of the array (indices are 0 to len-1)
This line does a[len] = temp;
and then increments len
a[0] a[1] a[2] a[len-1]
a[len-2]
Compares a[0] with a[len-1], then a[1]
with a[len-2], and so on. If any pair does
not match, set flag variable to 0
flag = 1 assumes that sequence is
palindrome (set 0 if later found otherwise)
Let’s specify a maximum
sequence size
Arrays: Some Example Programs
#include <stdio.h>
int main() {
char s[100];
int count = 0;
int ch;
int i;
return 0;
}
ch = getchar();
while ( ch != EOF && count < 100) {
s[count] = ch;
count = count + 1;
ch = getchar();
}
i = count-1;
while (i >=0) {
putchar(s[i]);
i=i-1;
}
/*print_in_reverse */
/*read_into_array */
/* the array of 100 char */
/* counts number of input chars read */
/* current character read */
/* index for printing array backwards */
Read until user has
entered 100 chars or
the end-of-file (EOF)
special character
has been read.
Now print the characters
in reverse order
getchar() returns a
single character
entered by the user
putchar() prints a single character
18

Contenu connexe

Similaire à INDIAN INSTITUTE OF TECHNOLOGY KANPUR ESC 111M Lec12.pptx

Similaire à INDIAN INSTITUTE OF TECHNOLOGY KANPUR ESC 111M Lec12.pptx (20)

Session 7 En
Session 7 EnSession 7 En
Session 7 En
 
arrays.pptx
arrays.pptxarrays.pptx
arrays.pptx
 
Visual Programing basic lectures 7.pptx
Visual Programing basic lectures  7.pptxVisual Programing basic lectures  7.pptx
Visual Programing basic lectures 7.pptx
 
An Introduction to Programming in Java: Arrays
An Introduction to Programming in Java: ArraysAn Introduction to Programming in Java: Arrays
An Introduction to Programming in Java: Arrays
 
Arrays
ArraysArrays
Arrays
 
Introduction to Arrays in C
Introduction to Arrays in CIntroduction to Arrays in C
Introduction to Arrays in C
 
[ITP - Lecture 15] Arrays & its Types
[ITP - Lecture 15] Arrays & its Types[ITP - Lecture 15] Arrays & its Types
[ITP - Lecture 15] Arrays & its Types
 
Arrays in programming
Arrays in programmingArrays in programming
Arrays in programming
 
Arrays
ArraysArrays
Arrays
 
Programming in c Arrays
Programming in c ArraysProgramming in c Arrays
Programming in c Arrays
 
Lecture_01.2.pptx
Lecture_01.2.pptxLecture_01.2.pptx
Lecture_01.2.pptx
 
Arrays
ArraysArrays
Arrays
 
CHAPTER 5
CHAPTER 5CHAPTER 5
CHAPTER 5
 
Arrays in C language
Arrays in C languageArrays in C language
Arrays in C language
 
About Array
About ArrayAbout Array
About Array
 
Unit ii data structure-converted
Unit  ii data structure-convertedUnit  ii data structure-converted
Unit ii data structure-converted
 
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
 
Chap 6 c++
Chap 6 c++Chap 6 c++
Chap 6 c++
 
Ch08
Ch08Ch08
Ch08
 
Fp201 unit4
Fp201 unit4Fp201 unit4
Fp201 unit4
 

Plus de AbhimanyuChaure

Plus de AbhimanyuChaure (7)

INDIAN INSTITUTE OF TECHNOLOGY KANPURESC 111M Lec13.pptx
INDIAN INSTITUTE OF TECHNOLOGY KANPURESC 111M Lec13.pptxINDIAN INSTITUTE OF TECHNOLOGY KANPURESC 111M Lec13.pptx
INDIAN INSTITUTE OF TECHNOLOGY KANPURESC 111M Lec13.pptx
 
INDIAN INSTITUTE OF TECHNOLOGY OF KANPURESC 111M Lec03.pptx
INDIAN INSTITUTE OF TECHNOLOGY OF KANPURESC 111M Lec03.pptxINDIAN INSTITUTE OF TECHNOLOGY OF KANPURESC 111M Lec03.pptx
INDIAN INSTITUTE OF TECHNOLOGY OF KANPURESC 111M Lec03.pptx
 
b5f1d7dac0b7d87e4f41a5509c1bf602e0d18aae0f9177cb406348a0edf59507_hello iitk L...
b5f1d7dac0b7d87e4f41a5509c1bf602e0d18aae0f9177cb406348a0edf59507_hello iitk L...b5f1d7dac0b7d87e4f41a5509c1bf602e0d18aae0f9177cb406348a0edf59507_hello iitk L...
b5f1d7dac0b7d87e4f41a5509c1bf602e0d18aae0f9177cb406348a0edf59507_hello iitk L...
 
915d511043d1509957e5b45ed827a5a9652f6759581a3682f5aabb6b0bccc5bd_Helloiitk Le...
915d511043d1509957e5b45ed827a5a9652f6759581a3682f5aabb6b0bccc5bd_Helloiitk Le...915d511043d1509957e5b45ed827a5a9652f6759581a3682f5aabb6b0bccc5bd_Helloiitk Le...
915d511043d1509957e5b45ed827a5a9652f6759581a3682f5aabb6b0bccc5bd_Helloiitk Le...
 
28f7f76ecd0fa8c132d87392a65507f78661379cfef5faa7ab8f733625de2723_Helloiit Lec...
28f7f76ecd0fa8c132d87392a65507f78661379cfef5faa7ab8f733625de2723_Helloiit Lec...28f7f76ecd0fa8c132d87392a65507f78661379cfef5faa7ab8f733625de2723_Helloiit Lec...
28f7f76ecd0fa8c132d87392a65507f78661379cfef5faa7ab8f733625de2723_Helloiit Lec...
 
2480b48c99ef4e3b94038d2680df02fe96bc196b029703c1929ec2575bed8eb9_Helloiitk Le...
2480b48c99ef4e3b94038d2680df02fe96bc196b029703c1929ec2575bed8eb9_Helloiitk Le...2480b48c99ef4e3b94038d2680df02fe96bc196b029703c1929ec2575bed8eb9_Helloiitk Le...
2480b48c99ef4e3b94038d2680df02fe96bc196b029703c1929ec2575bed8eb9_Helloiitk Le...
 
IITK ESC 111M Lec02.pptx .
IITK ESC 111M Lec02.pptx               .IITK ESC 111M Lec02.pptx               .
IITK ESC 111M Lec02.pptx .
 

Dernier

Teachers record management system project report..pdf
Teachers record management system project report..pdfTeachers record management system project report..pdf
Teachers record management system project report..pdf
Kamal Acharya
 
DR PROF ING GURUDUTT SAHNI WIKIPEDIA.pdf
DR PROF ING GURUDUTT SAHNI WIKIPEDIA.pdfDR PROF ING GURUDUTT SAHNI WIKIPEDIA.pdf
DR PROF ING GURUDUTT SAHNI WIKIPEDIA.pdf
DrGurudutt
 

Dernier (20)

Introduction to Heat Exchangers: Principle, Types and Applications
Introduction to Heat Exchangers: Principle, Types and ApplicationsIntroduction to Heat Exchangers: Principle, Types and Applications
Introduction to Heat Exchangers: Principle, Types and Applications
 
Introduction to Machine Learning Unit-4 Notes for II-II Mechanical Engineering
Introduction to Machine Learning Unit-4 Notes for II-II Mechanical EngineeringIntroduction to Machine Learning Unit-4 Notes for II-II Mechanical Engineering
Introduction to Machine Learning Unit-4 Notes for II-II Mechanical Engineering
 
Teachers record management system project report..pdf
Teachers record management system project report..pdfTeachers record management system project report..pdf
Teachers record management system project report..pdf
 
"United Nations Park" Site Visit Report.
"United Nations Park" Site  Visit Report."United Nations Park" Site  Visit Report.
"United Nations Park" Site Visit Report.
 
BRAKING SYSTEM IN INDIAN RAILWAY AutoCAD DRAWING
BRAKING SYSTEM IN INDIAN RAILWAY AutoCAD DRAWINGBRAKING SYSTEM IN INDIAN RAILWAY AutoCAD DRAWING
BRAKING SYSTEM IN INDIAN RAILWAY AutoCAD DRAWING
 
ANSI(ST)-III_Manufacturing-I_05052020.pdf
ANSI(ST)-III_Manufacturing-I_05052020.pdfANSI(ST)-III_Manufacturing-I_05052020.pdf
ANSI(ST)-III_Manufacturing-I_05052020.pdf
 
Diploma Engineering Drawing Qp-2024 Ece .pdf
Diploma Engineering Drawing Qp-2024 Ece .pdfDiploma Engineering Drawing Qp-2024 Ece .pdf
Diploma Engineering Drawing Qp-2024 Ece .pdf
 
Electrostatic field in a coaxial transmission line
Electrostatic field in a coaxial transmission lineElectrostatic field in a coaxial transmission line
Electrostatic field in a coaxial transmission line
 
Circuit Breaker arc phenomenon.pdf engineering
Circuit Breaker arc phenomenon.pdf engineeringCircuit Breaker arc phenomenon.pdf engineering
Circuit Breaker arc phenomenon.pdf engineering
 
RESORT MANAGEMENT AND RESERVATION SYSTEM PROJECT REPORT.pdf
RESORT MANAGEMENT AND RESERVATION SYSTEM PROJECT REPORT.pdfRESORT MANAGEMENT AND RESERVATION SYSTEM PROJECT REPORT.pdf
RESORT MANAGEMENT AND RESERVATION SYSTEM PROJECT REPORT.pdf
 
The battle for RAG, explore the pros and cons of using KnowledgeGraphs and Ve...
The battle for RAG, explore the pros and cons of using KnowledgeGraphs and Ve...The battle for RAG, explore the pros and cons of using KnowledgeGraphs and Ve...
The battle for RAG, explore the pros and cons of using KnowledgeGraphs and Ve...
 
Lesson no16 application of Induction Generator in Wind.ppsx
Lesson no16 application of Induction Generator in Wind.ppsxLesson no16 application of Induction Generator in Wind.ppsx
Lesson no16 application of Induction Generator in Wind.ppsx
 
Seismic Hazard Assessment Software in Python by Prof. Dr. Costas Sachpazis
Seismic Hazard Assessment Software in Python by Prof. Dr. Costas SachpazisSeismic Hazard Assessment Software in Python by Prof. Dr. Costas Sachpazis
Seismic Hazard Assessment Software in Python by Prof. Dr. Costas Sachpazis
 
Linux Systems Programming: Semaphores, Shared Memory, and Message Queues
Linux Systems Programming: Semaphores, Shared Memory, and Message QueuesLinux Systems Programming: Semaphores, Shared Memory, and Message Queues
Linux Systems Programming: Semaphores, Shared Memory, and Message Queues
 
DR PROF ING GURUDUTT SAHNI WIKIPEDIA.pdf
DR PROF ING GURUDUTT SAHNI WIKIPEDIA.pdfDR PROF ING GURUDUTT SAHNI WIKIPEDIA.pdf
DR PROF ING GURUDUTT SAHNI WIKIPEDIA.pdf
 
15-Minute City: A Completely New Horizon
15-Minute City: A Completely New Horizon15-Minute City: A Completely New Horizon
15-Minute City: A Completely New Horizon
 
Involute of a circle,Square, pentagon,HexagonInvolute_Engineering Drawing.pdf
Involute of a circle,Square, pentagon,HexagonInvolute_Engineering Drawing.pdfInvolute of a circle,Square, pentagon,HexagonInvolute_Engineering Drawing.pdf
Involute of a circle,Square, pentagon,HexagonInvolute_Engineering Drawing.pdf
 
How to Design and spec harmonic filter.pdf
How to Design and spec harmonic filter.pdfHow to Design and spec harmonic filter.pdf
How to Design and spec harmonic filter.pdf
 
E-Commerce Shopping using MERN Stack where different modules are present
E-Commerce Shopping using MERN Stack where different modules are presentE-Commerce Shopping using MERN Stack where different modules are present
E-Commerce Shopping using MERN Stack where different modules are present
 
Research Methodolgy & Intellectual Property Rights Series 2
Research Methodolgy & Intellectual Property Rights Series 2Research Methodolgy & Intellectual Property Rights Series 2
Research Methodolgy & Intellectual Property Rights Series 2
 

INDIAN INSTITUTE OF TECHNOLOGY KANPUR ESC 111M Lec12.pptx

  • 1. How to store lots of values of same type?  We have seen many data types so far  int, float, char, etc.  We can use a variable to store a single value of some data type, e.g.,  int x = 2; // variable x stores one integer value  float x = 2.3; // variable x stores a one float value  char x = ‘c’; // variable x stores one char value  What if we want to store several values, all of same data type?  Example 1: Marks of all ESC101 students in Major Quiz 1 (all floats)  Example 2: Roll numbers of all ESC101 students (all int)  Example 3: Final grade of all ESC101 students (all char) 1
  • 2. How to store lots of values of same type?  Consider storing Minor Quiz marks of all ESC111 students  This is very time consuming, inelegant, and boring  Arrays provide a better and more efficient way of doing such things 2 float marks1, marks2, marks3, .... ,marks500; scanf(“%f”, &marks1); scanf(“%f”, &marks2); ... scanf(“%f”, &marks500);
  • 3. Arrays  Not a new data type but a “data structure” (a collection of variables)  Enables storing multiple values of the same data type  Specification/declaration of an array needs the following  A data type (data type of values to be stored; all must be of same type)  A name (same naming convention as variables)  A size (how many values to be stored)  An example of array declaration: 3 float marks[500]; Data type Name Size Size is an integer in square brackets
  • 4. Arrays: Basic Syntax  Each value within the array is called “element” of the array  Each element is accessed using a non-negative integer-valued index  First index is 0 (index of first element)  Last index is array size minus one (index of last element)  Syntax to access/use each element of the array name_of_array[index]  For example:  marks[0] is the first element of an array named marks  marks[1] is the second element of array marks  marks[499] is the last element of array marks 4 Index is an integer in square brackets In some other languages (such as Python), array indexing starts with 1
  • 5. Arrays: Basic Syntax  Array index needs to be within limits (0 to array size - 1)  For an array declared as marks[500]  Index -1 is invalid (may give segmentation fault, also known as “segfault”)  Index 510 is invalid (may give segfault)  Index 500 is also invalid (recall that 499 is the index of last element)  Array index need not be a constant integer,  Can also be a variable/expression (but only int)  Example: marks[i] or marks[2*i + 1] where i is an integer  Never use a float/double as index 5
  • 6. Arrays: Storage in memory  A single variable (int/float/char etc) is stored in a single box in memory  An array is stored in several consecutive boxes in memory (number of these boxes is equal to the size of the array)  More on storage of arrays when we study Pointers 6 int a = 2; float b = 3.2; a b 2 3.2 float marks[500]; marks[0] marks[1] marks[2] marks[499] Array name is like street name, index is like house number
  • 7. Array: Declaration and Initialization Can be initialized at time of declaration itself Can be partly initialized as well However, if not initialized in same line with declaration, have to be initialized one by one! int a[6] = {3,7,6,2,1,0}; int a[6] = {3,7,6}; a 3 7 6 2 1 0 a 3 7 6 int a[6]; a = {3,7,6,2,1,0}; int a[6]; a[2] = 6; Array elements are comma separated 7
  • 8. Array: Declaration and Initialization Can be initialized at time of declaration itself Can be partly initialized as well Over initialization may crash Better way to initialize is the following Warning: uninitialized arrays contain garbage, not zeros int a[6] = {3,7,6,2,1,0}; int a[6] = {3,7,6}; a 3 7 6 2 1 0 a 3 7 6 int a[6] = {1,2,3,4,5,6,7,8,9}; int a[] = {1,2,3,4,5,6,7,8,9}; I will figure out how much space needed No need to specify the array size during declaration 8
  • 9. Array: Declaration and Initialization  Can declare the array first and initialize its elements later  The later initialization can be done using user-provided values (e.g., using scanf), or some expression, or using some fixed values int i,tmp,a[5]; for(i=0;i<5;i++){ scanf(“%d”,&tmp); a[i] = tmp; } Read a use- provided value Assign the read value to the ith element of the array 9 Can I run the loop as for(i=1;i<=5;i++)? Yes, if you use a[i-1] = tmp; in loop’s body
  • 10. Array: Declaration and Initialization  Can declare the array first and initialize its elements later  The later initialization can be done using user-provided values (e.g., using scanf), or some expression, or using some fixed value int i,a[5]; for(i=0;i<5;i++){ scanf(“%d”,&a[i]); } Directly read a user provided value into the ith element of the array (the tmp variable is not needed) Note: &a[i] is evaluated as &(a[i]) since [] has higher precedence than & A shortcut for reading user provided values 10
  • 11. Operator Name Symbol/Sign Associativity Brackets, array subscript, Post increment/decrement (), [] ++, -- Left Unary negation, Pre increment/decrement, NOT -, ++, --, ! Right Multiplication/division/ remainder *, /, % Left Addition/subtraction +, - Left Relational <, <=, >, >= Left Relational ==, != Left AND && Left OR || Left Conditional ? : Right Assignment, Compound assignment =, +=, -=, *=, /=, %= Right 11
  • 12. Array: Declaration and Initialization  Can declare the array first and initialize its elements later  The later initialization can be done using user-provided values (e.g., using scanf), or some expression, or using some fixed value int i,a[5]; for(i=0;i<5;i++){ a[i] = i+1; } Assign a value of expression i+1 to the ith element of the array 12 1 2 3 4 5 a[0] a[1] a[2] a[3] a[4]
  • 13. Array: Declaration and Initialization  Can declare the array first and initialize its elements later  The later initialization can be done using user-provided values (e.g., using scanf), or some expression, or using some fixed value Assign a fixed (constant) value 10 to the ith element of the array int i,a[5]; for(i=0;i<5;i++){ a[i] = 10; } 13 10 10 10 10 10 a[0] a[1] a[2] a[3] a[4]
  • 14. Tracing the execution of an array based program include <stdio.h> int main () { int a[5]; int i; for (i=0; i < 5; i= i+1) { a[i] = i+1; } return 0; } a[0] a[1] a[2] a[3] a[4] i Let us trace the execution of the program. 0 Statement becomes a[0] =0+1; Statement becomes a[1] =1+1; Statement becomes a[2] =2+1; 1 1 2 2 3 3 Statement becomes a[3] = 3+1; Statement becomes a[4] = 4+1; 4 4 5 5 14
  • 15. Arrays: Some Example Programs  Create an integer array of size 100  Initialize elements with even index as 0  Initialize elements with odd index as 1 int i,a[100]; for(i=0; i<100; i=i+1){ if(i%2==0) a[i] = 0; else a[i] = 1; } Method 1 15
  • 16. Arrays: Some Example Programs  Create an integer array of size 100  Initialize elements with even index as 0  Initialize elements with odd index as 1 int i,a[100]; for(i=0; i<100; i=i+2){ a[i] = 0; a[i+1] = 1; } Method 2, without if-else Incrementing the loop counter by 2 This for loop will run 50 times. Each iteration will assign values to 2 elements, one at odd index, one at even index 16
  • 17. Arrays: Some Example Programs  Check whether a sequence of numbers is a palindrome sequence 11 Greek origin word: palin = again, dromos = direction Palindrome: Forward and Reverse gives the same sequence Some palindromes: 1 2 3 4 5 4 3 2 1 1 2 3 3 2 1 Some non-palindromes: 1 2 3 4 5 1 2 3 3 4 1 9 0 4 0 8 int main(){ int a[100], temp, len = 0, i, flag = 1; while(1){ scanf("%d", &temp); if(temp == -1) break; a[len++] = temp; } for(i = 0; i < len; i++) if(a[i] != a[len-i-1]) flag = 0; if(flag) printf("YES"); else printf("NO"); return 0; } The while(1) loop keeps reading numbers until user enters -1, store each number as an element of the array named a After the while(1) loop exits, len is the size of the array (indices are 0 to len-1) This line does a[len] = temp; and then increments len a[0] a[1] a[2] a[len-1] a[len-2] Compares a[0] with a[len-1], then a[1] with a[len-2], and so on. If any pair does not match, set flag variable to 0 flag = 1 assumes that sequence is palindrome (set 0 if later found otherwise) Let’s specify a maximum sequence size
  • 18. Arrays: Some Example Programs #include <stdio.h> int main() { char s[100]; int count = 0; int ch; int i; return 0; } ch = getchar(); while ( ch != EOF && count < 100) { s[count] = ch; count = count + 1; ch = getchar(); } i = count-1; while (i >=0) { putchar(s[i]); i=i-1; } /*print_in_reverse */ /*read_into_array */ /* the array of 100 char */ /* counts number of input chars read */ /* current character read */ /* index for printing array backwards */ Read until user has entered 100 chars or the end-of-file (EOF) special character has been read. Now print the characters in reverse order getchar() returns a single character entered by the user putchar() prints a single character 18