SlideShare a Scribd company logo
1 of 73
Download to read offline
Programming Fundamentals
Arrays and Strings
Lecture Outline
• Arrays
• Initializing arrays
• Multidimensional arrays
• Arrays as arguments to functions
• Strings
• String functions
Arrays
In C programming, one of the frequently problem
is to handle similar types of data. For example: if
the user wants to store marks of 500 students,
this can be done by creating 500 variables
individually but, this is rather tedious and
impracticable. These types of problem can be
handled in C programming using arrays.
Arrays
• Array is a sequence of data item of homogeneous values
(same type) referred to by a common name. Marks of 500
students, number of chairs in university, salaries of 300
employees or ages of 250 students are few examples of
collection of data elements having the same data type.
• The
values in an array can be
of any type like int, float, double, char etc.
scores
: 85 92576880
name
: ‘C’ ‘Y’‘D’
‘E’
79
‘L’
Declaring Arrays
• Syntax: data_type array_name
[constant];
• Note declaration from our example
Tells how many elements set aside
Declaring Arrays
• Example specifies an array…
– each element is an integer
– there is space for 100 elements
– they are numbered 0 through 99. Note: Index starts at 0
98 99
Accessing Individual Components
• Use the name of the array
• Followed by an integer expression inside the
square brackets [ ]
scores : 85 79 92 57 68 80 . . .
0 1 2 3 4 5
scores : 85 79 92 57 68 80 . . .
0 1 2 3 4 5 98 99
Index can be: max = scores[0]; - constant for (x
= 0; x < 100; x++)
- variable if (scores[x] > max) - expression
max = scores[x];
MUST be an integer
Arrays: Example
#include<stdio.h>
#include<conio.h>
int main()
{ age[0]
int age[3], j;
age[0] = 25; age[1] age[1] = 30; age[2] = 35;
for (j=0; j<3; j++) age[2] printf(“%dn”,
age[j]); getch(); }
Arrays:
Example
#include<stdio.h>
#include<stdio.h>
#include<conio.h>
25
30
35
#include<conio.h>
int main() int main()
{
{
int age[3], j; int age[3], i, j;
age[0] = 25; for (i = 0; i<3; i++) {
age[1] = 30; printf(“Enter ages n”);
age[2] = 35; scanf(“%d”, &age[i]) ; }
for (j=0; j<3; j++) for (j=0; j<3; j++)
printf(“%dn”, age[j]); printf(“%dn”, age[j]);
getch(); } getch(); }
Out of Bounds Index
• What happens if … float age [3];
age [5] = 123.456;
• C++ does NOT check for index out of range
• Possible to walk off into “far reaches” of memory
-- clobbers ...
– other variable locations
– .exe code
– the operating system (??)
Arrays: Example Garbage
#include<stdio.h>
#include<conio.h>
int main()
{
int age[3], j;
age[0] = 25;
age[1] = 30;
age[2] = 35;
age[3] = 50;
for (j=0; j<=3; j++)
printf(“%dn”, age[j]); getch(); }
Arrays: Class Exercise
Write a C++ program
using arrays that
accepts five (05)
integers and then
prints them in reverse
order.
#include<stdio.h>
#include<conio.h>
int main()
{ int age[5], i,
j;
printf(“Enter numbers: n”);
for (i = 0; i<5; i++) {
scanf(“%d”, &age[i]) ; }
for (j=4; j>=0; j--)
printf(“%dn”, age[j]);
getch(); }
Initializing Arrays in Declarations
• Possible to declare the size & initialize int
results [5] = {14, 6, 23, 8, 12 }
• Possible to omit size at declaration
– Compiler figures out size of array
float prices [ ] = { 2.41, 85.06, 19.95, 3.91
}
Arrays Initialization: Example
#include<stdio.h>
#include<conio.h>
int main()
{
int age[3] = {25, 30, 35};
int j;
for (j=0; j<3; j++)
printf(“%dn”, age[j]);
getch(); }
#include<stdio.h>
#include<conio.h>
int main() Empty
brackets
{ can take any size int j;
int age[ ] = {25, 30, 35};
for (j=0; j<3; j++)
printf(“%dn”, age[j]);
getch(); }
Multidimensional Arrays
2-Dimensional Arrays
• A collection of a fixed number of components
arranged in two dimensions
– All components are of the same type
• The syntax for declaring a two-dimensional array
is:
dataType arrayName[intexp1][intexp2];
where intexp1 and intexp2 are expressions yielding
positive integer values; e.g., double sales[10][5]
2-Dimensional Arrays
• The two expressions intexp1 and intexp2 specify the
number of rows and the number of columns,
respectively, in the array
• Two-dimensional arrays are sometimes called matrices or
tables
2-Dimensional Arrays
double sales[10][5];
2-Dimensional Arrays
• The syntax to access a component of a
twodimensional array is:
arrayName[indexexp1][indexexp2]
where indexexp1 and indexexp2 are
expressions yielding nonnegative integer values
• indexexp1 specifies the row position and
indexexp2 specifies the column position
sales[2][3] = 35.60;
2-Dimensional Arrays
35.60
2-Dimensional Arrays Accessing
• Accessing all of the elements of a two-dimensional array
requires two loops: one for the row, and one for the
column.
• Since two-dimensional arrays are typically accessed row
by row, generally the row index is used as the outer loop.
for (nRow = 0; nRow < nNumRows; nRow++)
for (nCol = 0; nCol < nNumCols; nCol++)
cout << anArray[nRow][nCol];
2 DIM. Arrays: Example
#include<stdio.h>
#include<conio.h>
int main()
{
double sales[2][3];
//complete program by
//printing the values
which look like this:
sales[0][0] = 2.3;
sales[0][1] = 3.5;
sales[0][2] = 4.2;
sales[1][0] = 5.6;
sales[1][1] = 6.7;
sales[1][2] = 7.8;
2 DIM. Arrays: Example
#include<stdio.h>
#include<conio.h>
int main()
{ int i,
j;
double sales[2][3];
sales[0][0] = 2.3;
sales[0][1] = 3.5;
sales[0][2] = 4.2;
for(i=0; i<2; i++)
{
for(j=0; j<3; j++)
{
printf(“%d”, sales[i][j]);
}
printf(“n”);
} getch();
}
sales[1][0] = 5.6; sales[1][1] =
6.7; sales[1][2] = 7.8;
2-Dimensional
Arrays Initialization
• Like one-dimensional arrays
– Two-dimensional arrays can be initialized when they are
declared
• To initialize a two-dimensional array when it is declared
1) Elements of each row are enclosed within braces and
separated by commas
2) All rows are enclosed within braces
3) For number arrays, if all components of a row are not
specified, the unspecified components are initialized to
zero
2-Dimensional Arrays Initialization
• Example:
int anArray[3][5] =
{
{ 1, 2, 3, 4, 5, }, // row 0 { 6, 7, 8, 9, 10, }, //
row 1 { 11, 12, 13, 14, 15 } // row 2
};
2 DIM. Arrays: Example
#include<stdio.h>
#include<conio.h>
int main()
{ int i, j;
int matrix[2][2] = {
{2,3,}, //row0
{5,7} //row1
};
printf(“n Resultant: n“);
for(i = 0; i < 2; i++)
{
for(j = 0; j < 2; j++)
{
printf(" %d”, matrix[i][j]);
}
printf("n“);
}
getch();
}
2 DIM. Arrays: Class Exercise
Write a C program using 2 DIM. array that
gets 2x2 matrix input from the user and then
prints the resultant matrix. The output should
look like this:
2 DIM. Arrays: Exercise Solution
#include<stdio.h>
#include<conio.h>
int main()
{
int matrix[2][2], i, j;
for(i = 0; i < 2; i++)
{
for(j = 0; j < 2; j++)
{
printf(“n Enter values for [ %d %d ] = ”) ;
scanf(“%d”, &matrix [i] [j]);
}
}
printf("n Resultant: n“);
for(i = 0; i < 2; i++)
{
for(j = 0; j < 2; j++)
{
printf(“ %d ”, matrix [i] [j]) ;
}
printf("n“);
}
getch(); }
2 DIM. Arrays: Class Exercise
Write a C program
using 2 DIM. array that
gets two 2x2 matrices as
an input from the user
and then prints the sum
of entered matrices. The
output should look like
this:
2 DIM. Arrays: Exercise
Solution
int main()
{
int mat1[2][2]; int
mat2[2][2]; int mat[2][2];
//resultant int i, j, k, l;
printf("n 1st Matrix: n n“);
for(i=0; i<2; i++)
{
for(j=0; j<2; j++)
{
scanf(“%d”, &mat1[i][j]);
}
}
printf("n 2nd Matrix: n n“);
for(i=0; i<2; i++)
{
for(j=0; j<2; j++)
{
scanf(“%d”, &mat2[i][j]);
}
}
printf("n Resultant: n“);
for(k=0; k<2; k++)
{
for(l=0; l<2; l++)
{
mat[k][l]=(mat1[k][l] + mat2[k][l]);
printf(“ %d ”, mat[k][l]);
}
printf("n“);
}
getch();
}
2 DIM. Arrays: Assignment
1) Write a C program using arrays that
produces the multiplication of two 2x2
matrices.
2) Write a C program using arrays that gives
the following output:
Multidimensional Arrays
• A collection of a fixed number of elements (called
components) arranged in n dimensions (n >= 1)
• Also called an n-dimensional array
• General syntax of declaring an n-dimensional array is:
dataType arrayName[intExp1][intExp2]...[intExpn];
where intExp1, intExp2, … are constant expressions
yielding positive integer values
Example: 3-Dimensional array:
int table[3][2][4];
Initializing 3-Dimensional Array
Initializing 3-Dimensional Array
Assignment
Write a program of your own choice that
makes use of arrays of more than 2
dimensions.
Arrays as Parameters
• This is one task that CAN be done to the WHOLE array
• C always passes arrays by reference
for (index = 0; index < how_many; index++)
{ printf (“Enter score %d ”, index);
scanf (“%d”, &list[index]); }
printf (“Enter how many students”);
scanf (“%d”, &num_students); }
Arrays as Parameters
• The name of the array is a pointer constant
• The address of the array is passed to the function
• Size of the
array also
passed to
control loop
for (index = 0; index < how_many; index++)
{ printf (“Enter score %d ”, index);
scanf }“%d”, &list[index]);(
printf (“Enter how many students”);
scanf (“%d”, &num_students); }
Arrays as Parameters
• Note the empty brackets in parameter list
– A number can be placed here but it will be ignored
for (index = 0; index < how_many; index++)
{ printf (“Enter score %d ”, index);
scanf ( }“%d”, &list[index]);
printf (“Enter how many students”);
scanf (“%d”, &num_students); }
Passing Arrays to Functions
#include<stdio.h>
#include<conio.h>
int sum(int list[], int listSize)
{
int index, sum = 0; for(index=0;
index<listSize; index++) sum =
sum + list[index]; return sum; }
int main()
{ int myArray[] = {2, 3, 5};
printf( "The sum is: %d ”, sum(myArray, 3));
getch(); }
Home Work
Write a program of that sorts the numbers
you type in. The array may be able to get
input until you enter 0. Sample output:
C-String OR Character-Arrays
• We have learned that the elements of an array
can be just about anything int, char, double etc.
• Consider an array whose elements are all
characters
• Such type of an array is called a C-String
• In C language, a string is not a formal data type as
it is in some languages (e.g., Pascal and Basic).
Instead, String is an array of type Char.
C-Strings OR Character Arrays
• Character array: An array whose components are
of type char
• String: A sequence of zero or more characters
enclosed in double quote marks (e.g., “hello”)
• Internally (by the compiler) C-stings are
terminated with null (‘0’) in memory
» (the last character in a string is the null-character
String constant
String constant
String constant
String constant
String variables
String variables
String variables
String variables
Declaration of C-Strings
• Similar to declaration of any array
char name[30]; // no
initialization
char title [20] = "Le Grande Fromage";
// initialized at declaration
// with a string char chList [10] =
{'a', 'b', 'c', 'd'};
// initialized with list of char
// values
Initializing Strings
• When a character array is declared, it is legal to use
the assignment operator to initialize
• Note : use of the “ = “ operator is legal only for char
array initialization
• But : aggregate array assignment is NOT
C-Strings: Example-1
#include<stdio.h>
#include<conio.h>
int main()
{
const int MAX = 80; //maximum characters in a
string char str[MAX]; //string variable str printf(
“Enter a string n”); scanf(“%s”, str); //put string in
str
greeting = “don’t do it;
printf(“You entered: %s”, str); //display string from str
getch();
}
String I/O function
• In dealing with string input, scanf() has a
limitation that it does not accept multi-word
strings separated by spaces.
• For example, run the previous program by
providing input string as “hello world”
String I/O function
Note
Reading Embedded Blanks
#include<stdio.h>
#include<conio.h>
int main()
{
const int MAX = 80; //maximum characters in a
string char str[MAX]; //string variable str puts(
“Enter a string n”); gets(str); //put string in str
printf(“You entered: %s”, str); //display string from str
getch();
}
Home Work
Write a program of that reads and prints multiple
text lines.
String functions •
Functions provided in #include <cstring>
Working With Strings
• C-strings are compared character by character using the
collating sequence of the system
• If we are using the ASCII character set
Used instead of assignment
Used for comparisons
1) The string "Air" is smaller than the string "Boat"
2) The string "Air" is smaller than the string "An"
3) The string "Bill" is smaller than the string
"Billy"
4) The string "Hello" is smaller than "hello"
strcpy() function
Example
strcmp() function
String functions
String functions
Working With Strings
String functions

More Related Content

What's hot

Templates in C++
Templates in C++Templates in C++
Templates in C++
Tech_MX
 
C Prog - Functions
C Prog - FunctionsC Prog - Functions
C Prog - Functions
vinay arora
 
C aptitude scribd
C aptitude scribdC aptitude scribd
C aptitude scribd
Amit Kapoor
 

What's hot (20)

USER DEFINE FUNCTIONS IN PYTHON[WITH PARAMETERS]
USER DEFINE FUNCTIONS IN PYTHON[WITH PARAMETERS]USER DEFINE FUNCTIONS IN PYTHON[WITH PARAMETERS]
USER DEFINE FUNCTIONS IN PYTHON[WITH PARAMETERS]
 
C tech questions
C tech questionsC tech questions
C tech questions
 
Functions in C
Functions in CFunctions in C
Functions in C
 
Functions in c
Functions in cFunctions in c
Functions in c
 
Embedded C - Day 2
Embedded C - Day 2Embedded C - Day 2
Embedded C - Day 2
 
Function & Recursion in C
Function & Recursion in CFunction & Recursion in C
Function & Recursion in C
 
An imperative study of c
An imperative study of cAn imperative study of c
An imperative study of c
 
Templates in C++
Templates in C++Templates in C++
Templates in C++
 
Data struture lab
Data struture labData struture lab
Data struture lab
 
C Prog - Functions
C Prog - FunctionsC Prog - Functions
C Prog - Functions
 
Decision making and branching
Decision making and branchingDecision making and branching
Decision making and branching
 
OPERATOR IN PYTHON-PART1
OPERATOR IN PYTHON-PART1OPERATOR IN PYTHON-PART1
OPERATOR IN PYTHON-PART1
 
46630497 fun-pointer-1
46630497 fun-pointer-146630497 fun-pointer-1
46630497 fun-pointer-1
 
Functions
FunctionsFunctions
Functions
 
C Prog - Array
C Prog - ArrayC Prog - Array
C Prog - Array
 
Expressions using operator in c
Expressions using operator in cExpressions using operator in c
Expressions using operator in c
 
CBSE Class XI Programming in C++
CBSE Class XI Programming in C++CBSE Class XI Programming in C++
CBSE Class XI Programming in C++
 
C program
C programC program
C program
 
C aptitude scribd
C aptitude scribdC aptitude scribd
C aptitude scribd
 
C++ Functions
C++ FunctionsC++ Functions
C++ Functions
 

Similar to Programming Fundamentals Arrays and Strings

Array.pptx
Array.pptxArray.pptx

Similar to Programming Fundamentals Arrays and Strings (20)

Array,MULTI ARRAY, IN C
Array,MULTI ARRAY, IN CArray,MULTI ARRAY, IN C
Array,MULTI ARRAY, IN C
 
COM1407: Arrays
COM1407: ArraysCOM1407: Arrays
COM1407: Arrays
 
VIT351 Software Development VI Unit2
VIT351 Software Development VI Unit2VIT351 Software Development VI Unit2
VIT351 Software Development VI Unit2
 
Array
ArrayArray
Array
 
array
arrayarray
array
 
Array
ArrayArray
Array
 
Arrays
ArraysArrays
Arrays
 
Arrays and function basic c programming notes
Arrays and function basic c programming notesArrays and function basic c programming notes
Arrays and function basic c programming notes
 
L5 array
L5 arrayL5 array
L5 array
 
Arrays basics
Arrays basicsArrays basics
Arrays basics
 
Structured data type
Structured data typeStructured data type
Structured data type
 
Array.pptx
Array.pptxArray.pptx
Array.pptx
 
Array BPK 2
Array BPK 2Array BPK 2
Array BPK 2
 
array2d.ppt
array2d.pptarray2d.ppt
array2d.ppt
 
Session 4
Session 4Session 4
Session 4
 
DSC program.pdf
DSC program.pdfDSC program.pdf
DSC program.pdf
 
Chapter 6 arrays part-1
Chapter 6   arrays part-1Chapter 6   arrays part-1
Chapter 6 arrays part-1
 
Abir ppt3
Abir ppt3Abir ppt3
Abir ppt3
 
20.1 Java working with abstraction
20.1 Java working with abstraction20.1 Java working with abstraction
20.1 Java working with abstraction
 
Unit 3 arrays and_string
Unit 3 arrays and_stringUnit 3 arrays and_string
Unit 3 arrays and_string
 

More from imtiazalijoono

More from imtiazalijoono (20)

Embedded systems io programming
Embedded systems   io programmingEmbedded systems   io programming
Embedded systems io programming
 
Embedded systems tools & peripherals
Embedded systems   tools & peripheralsEmbedded systems   tools & peripherals
Embedded systems tools & peripherals
 
Importance of reading and its types.
Importance of reading and its types.Importance of reading and its types.
Importance of reading and its types.
 
Negative amplifiers and its types Positive feedback and Negative feedback
Negative amplifiers and its types Positive feedback  and Negative feedbackNegative amplifiers and its types Positive feedback  and Negative feedback
Negative amplifiers and its types Positive feedback and Negative feedback
 
Multistage amplifiers and Name of coupling Name of multistage amplifier
Multistage amplifiers and Name of coupling Name of multistage amplifierMultistage amplifiers and Name of coupling Name of multistage amplifier
Multistage amplifiers and Name of coupling Name of multistage amplifier
 
Loop Introduction for Loop while Loop do while Loop Nested Loops Values of...
Loop Introduction for Loop  while Loop do while Loop  Nested Loops  Values of...Loop Introduction for Loop  while Loop do while Loop  Nested Loops  Values of...
Loop Introduction for Loop while Loop do while Loop Nested Loops Values of...
 
Programming Fundamentals and basic knowledge
Programming Fundamentals and basic knowledge Programming Fundamentals and basic knowledge
Programming Fundamentals and basic knowledge
 
Programming Fundamentals Functions in C and types
Programming Fundamentals  Functions in C  and typesProgramming Fundamentals  Functions in C  and types
Programming Fundamentals Functions in C and types
 
Software Development Software development process
Software Development Software development processSoftware Development Software development process
Software Development Software development process
 
C Building Blocks
C Building Blocks C Building Blocks
C Building Blocks
 
Programming Fundamentals and Programming Languages Concepts Translators
Programming Fundamentals and Programming Languages Concepts TranslatorsProgramming Fundamentals and Programming Languages Concepts Translators
Programming Fundamentals and Programming Languages Concepts Translators
 
Programming Fundamentals and Programming Languages Concepts
Programming Fundamentals and Programming Languages ConceptsProgramming Fundamentals and Programming Languages Concepts
Programming Fundamentals and Programming Languages Concepts
 
Programming Global variable
Programming Global variableProgramming Global variable
Programming Global variable
 
Array Introduction One-dimensional array Multidimensional array
Array Introduction One-dimensional array Multidimensional arrayArray Introduction One-dimensional array Multidimensional array
Array Introduction One-dimensional array Multidimensional array
 
NTRODUCTION TO COMPUTER PROGRAMMING Loop as repetitive statement,
NTRODUCTION TO COMPUTER PROGRAMMING Loop as repetitive statement,NTRODUCTION TO COMPUTER PROGRAMMING Loop as repetitive statement,
NTRODUCTION TO COMPUTER PROGRAMMING Loop as repetitive statement,
 
Arithmetic and Arithmetic assignment operators
Arithmetic and Arithmetic assignment operatorsArithmetic and Arithmetic assignment operators
Arithmetic and Arithmetic assignment operators
 
INTRODUCTION TO COMPUTER PROGRAMMING
INTRODUCTION TO COMPUTER PROGRAMMINGINTRODUCTION TO COMPUTER PROGRAMMING
INTRODUCTION TO COMPUTER PROGRAMMING
 
COMPUTER PROGRAMMING
COMPUTER PROGRAMMINGCOMPUTER PROGRAMMING
COMPUTER PROGRAMMING
 
COMPUTER PROGRAMMING
COMPUTER PROGRAMMINGCOMPUTER PROGRAMMING
COMPUTER PROGRAMMING
 
FIELD EFFECT TRANSISTERS (FET)
FIELD EFFECT TRANSISTERS (FET)FIELD EFFECT TRANSISTERS (FET)
FIELD EFFECT TRANSISTERS (FET)
 

Recently uploaded

會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
中 央社
 
Neurulation and the formation of the neural tube
Neurulation and the formation of the neural tubeNeurulation and the formation of the neural tube
Neurulation and the formation of the neural tube
SaadHumayun7
 
The basics of sentences session 4pptx.pptx
The basics of sentences session 4pptx.pptxThe basics of sentences session 4pptx.pptx
The basics of sentences session 4pptx.pptx
heathfieldcps1
 

Recently uploaded (20)

Matatag-Curriculum and the 21st Century Skills Presentation.pptx
Matatag-Curriculum and the 21st Century Skills Presentation.pptxMatatag-Curriculum and the 21st Century Skills Presentation.pptx
Matatag-Curriculum and the 21st Century Skills Presentation.pptx
 
size separation d pharm 1st year pharmaceutics
size separation d pharm 1st year pharmaceuticssize separation d pharm 1st year pharmaceutics
size separation d pharm 1st year pharmaceutics
 
philosophy and it's principles based on the life
philosophy and it's principles based on the lifephilosophy and it's principles based on the life
philosophy and it's principles based on the life
 
Operations Management - Book1.p - Dr. Abdulfatah A. Salem
Operations Management - Book1.p  - Dr. Abdulfatah A. SalemOperations Management - Book1.p  - Dr. Abdulfatah A. Salem
Operations Management - Book1.p - Dr. Abdulfatah A. Salem
 
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
 
B.ed spl. HI pdusu exam paper-2023-24.pdf
B.ed spl. HI pdusu exam paper-2023-24.pdfB.ed spl. HI pdusu exam paper-2023-24.pdf
B.ed spl. HI pdusu exam paper-2023-24.pdf
 
MichaelStarkes_UncutGemsProjectSummary.pdf
MichaelStarkes_UncutGemsProjectSummary.pdfMichaelStarkes_UncutGemsProjectSummary.pdf
MichaelStarkes_UncutGemsProjectSummary.pdf
 
Neurulation and the formation of the neural tube
Neurulation and the formation of the neural tubeNeurulation and the formation of the neural tube
Neurulation and the formation of the neural tube
 
Dementia (Alzheimer & vasular dementia).
Dementia (Alzheimer & vasular dementia).Dementia (Alzheimer & vasular dementia).
Dementia (Alzheimer & vasular dementia).
 
Post Exam Fun(da) Intra UEM General Quiz 2024 - Prelims q&a.pdf
Post Exam Fun(da) Intra UEM General Quiz 2024 - Prelims q&a.pdfPost Exam Fun(da) Intra UEM General Quiz 2024 - Prelims q&a.pdf
Post Exam Fun(da) Intra UEM General Quiz 2024 - Prelims q&a.pdf
 
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT VẬT LÝ 2024 - TỪ CÁC TRƯỜNG, TRƯ...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT VẬT LÝ 2024 - TỪ CÁC TRƯỜNG, TRƯ...TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT VẬT LÝ 2024 - TỪ CÁC TRƯỜNG, TRƯ...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT VẬT LÝ 2024 - TỪ CÁC TRƯỜNG, TRƯ...
 
Word Stress rules esl .pptx
Word Stress rules esl               .pptxWord Stress rules esl               .pptx
Word Stress rules esl .pptx
 
Basic_QTL_Marker-assisted_Selection_Sourabh.ppt
Basic_QTL_Marker-assisted_Selection_Sourabh.pptBasic_QTL_Marker-assisted_Selection_Sourabh.ppt
Basic_QTL_Marker-assisted_Selection_Sourabh.ppt
 
Morse OER Some Benefits and Challenges.pptx
Morse OER Some Benefits and Challenges.pptxMorse OER Some Benefits and Challenges.pptx
Morse OER Some Benefits and Challenges.pptx
 
Basic Civil Engg Notes_Chapter-6_Environment Pollution & Engineering
Basic Civil Engg Notes_Chapter-6_Environment Pollution & EngineeringBasic Civil Engg Notes_Chapter-6_Environment Pollution & Engineering
Basic Civil Engg Notes_Chapter-6_Environment Pollution & Engineering
 
Keeping Your Information Safe with Centralized Security Services
Keeping Your Information Safe with Centralized Security ServicesKeeping Your Information Safe with Centralized Security Services
Keeping Your Information Safe with Centralized Security Services
 
[GDSC YCCE] Build with AI Online Presentation
[GDSC YCCE] Build with AI Online Presentation[GDSC YCCE] Build with AI Online Presentation
[GDSC YCCE] Build with AI Online Presentation
 
The basics of sentences session 4pptx.pptx
The basics of sentences session 4pptx.pptxThe basics of sentences session 4pptx.pptx
The basics of sentences session 4pptx.pptx
 
....................Muslim-Law notes.pdf
....................Muslim-Law notes.pdf....................Muslim-Law notes.pdf
....................Muslim-Law notes.pdf
 
Research Methods in Psychology | Cambridge AS Level | Cambridge Assessment In...
Research Methods in Psychology | Cambridge AS Level | Cambridge Assessment In...Research Methods in Psychology | Cambridge AS Level | Cambridge Assessment In...
Research Methods in Psychology | Cambridge AS Level | Cambridge Assessment In...
 

Programming Fundamentals Arrays and Strings

  • 2. Lecture Outline • Arrays • Initializing arrays • Multidimensional arrays • Arrays as arguments to functions • Strings • String functions
  • 3. Arrays In C programming, one of the frequently problem is to handle similar types of data. For example: if the user wants to store marks of 500 students, this can be done by creating 500 variables individually but, this is rather tedious and impracticable. These types of problem can be handled in C programming using arrays.
  • 4. Arrays • Array is a sequence of data item of homogeneous values (same type) referred to by a common name. Marks of 500 students, number of chairs in university, salaries of 300 employees or ages of 250 students are few examples of collection of data elements having the same data type. • The values in an array can be of any type like int, float, double, char etc. scores : 85 92576880 name : ‘C’ ‘Y’‘D’ ‘E’ 79 ‘L’
  • 5. Declaring Arrays • Syntax: data_type array_name [constant]; • Note declaration from our example Tells how many elements set aside
  • 6. Declaring Arrays • Example specifies an array… – each element is an integer – there is space for 100 elements – they are numbered 0 through 99. Note: Index starts at 0
  • 7. 98 99 Accessing Individual Components • Use the name of the array • Followed by an integer expression inside the square brackets [ ] scores : 85 79 92 57 68 80 . . . 0 1 2 3 4 5
  • 8. scores : 85 79 92 57 68 80 . . . 0 1 2 3 4 5 98 99 Index can be: max = scores[0]; - constant for (x = 0; x < 100; x++) - variable if (scores[x] > max) - expression max = scores[x]; MUST be an integer Arrays: Example #include<stdio.h> #include<conio.h>
  • 9. int main() { age[0] int age[3], j; age[0] = 25; age[1] age[1] = 30; age[2] = 35; for (j=0; j<3; j++) age[2] printf(“%dn”, age[j]); getch(); } Arrays: Example #include<stdio.h> #include<stdio.h> #include<conio.h> 25 30 35
  • 10. #include<conio.h> int main() int main() { { int age[3], j; int age[3], i, j; age[0] = 25; for (i = 0; i<3; i++) { age[1] = 30; printf(“Enter ages n”); age[2] = 35; scanf(“%d”, &age[i]) ; } for (j=0; j<3; j++) for (j=0; j<3; j++) printf(“%dn”, age[j]); printf(“%dn”, age[j]); getch(); } getch(); }
  • 11. Out of Bounds Index • What happens if … float age [3]; age [5] = 123.456; • C++ does NOT check for index out of range • Possible to walk off into “far reaches” of memory -- clobbers ... – other variable locations – .exe code – the operating system (??)
  • 12. Arrays: Example Garbage #include<stdio.h> #include<conio.h> int main() { int age[3], j; age[0] = 25; age[1] = 30; age[2] = 35; age[3] = 50; for (j=0; j<=3; j++) printf(“%dn”, age[j]); getch(); }
  • 13. Arrays: Class Exercise Write a C++ program using arrays that accepts five (05) integers and then prints them in reverse order. #include<stdio.h> #include<conio.h> int main() { int age[5], i, j; printf(“Enter numbers: n”); for (i = 0; i<5; i++) { scanf(“%d”, &age[i]) ; }
  • 14. for (j=4; j>=0; j--) printf(“%dn”, age[j]); getch(); } Initializing Arrays in Declarations • Possible to declare the size & initialize int results [5] = {14, 6, 23, 8, 12 } • Possible to omit size at declaration
  • 15. – Compiler figures out size of array float prices [ ] = { 2.41, 85.06, 19.95, 3.91 } Arrays Initialization: Example #include<stdio.h> #include<conio.h> int main() { int age[3] = {25, 30, 35}; int j; for (j=0; j<3; j++) printf(“%dn”, age[j]); getch(); }
  • 16. #include<stdio.h> #include<conio.h> int main() Empty brackets { can take any size int j; int age[ ] = {25, 30, 35}; for (j=0; j<3; j++) printf(“%dn”, age[j]); getch(); }
  • 18. 2-Dimensional Arrays • A collection of a fixed number of components arranged in two dimensions – All components are of the same type • The syntax for declaring a two-dimensional array is: dataType arrayName[intexp1][intexp2]; where intexp1 and intexp2 are expressions yielding positive integer values; e.g., double sales[10][5]
  • 19. 2-Dimensional Arrays • The two expressions intexp1 and intexp2 specify the number of rows and the number of columns, respectively, in the array • Two-dimensional arrays are sometimes called matrices or tables
  • 21. 2-Dimensional Arrays • The syntax to access a component of a twodimensional array is: arrayName[indexexp1][indexexp2] where indexexp1 and indexexp2 are expressions yielding nonnegative integer values • indexexp1 specifies the row position and indexexp2 specifies the column position sales[2][3] = 35.60;
  • 23. 2-Dimensional Arrays Accessing • Accessing all of the elements of a two-dimensional array requires two loops: one for the row, and one for the column. • Since two-dimensional arrays are typically accessed row by row, generally the row index is used as the outer loop. for (nRow = 0; nRow < nNumRows; nRow++) for (nCol = 0; nCol < nNumCols; nCol++) cout << anArray[nRow][nCol];
  • 24. 2 DIM. Arrays: Example #include<stdio.h> #include<conio.h> int main() { double sales[2][3]; //complete program by //printing the values which look like this: sales[0][0] = 2.3; sales[0][1] = 3.5; sales[0][2] = 4.2; sales[1][0] = 5.6; sales[1][1] = 6.7;
  • 25. sales[1][2] = 7.8; 2 DIM. Arrays: Example #include<stdio.h> #include<conio.h> int main() { int i, j; double sales[2][3]; sales[0][0] = 2.3; sales[0][1] = 3.5; sales[0][2] = 4.2; for(i=0; i<2; i++) { for(j=0; j<3; j++) { printf(“%d”, sales[i][j]); } printf(“n”); } getch(); }
  • 26. sales[1][0] = 5.6; sales[1][1] = 6.7; sales[1][2] = 7.8; 2-Dimensional Arrays Initialization • Like one-dimensional arrays – Two-dimensional arrays can be initialized when they are declared • To initialize a two-dimensional array when it is declared 1) Elements of each row are enclosed within braces and separated by commas 2) All rows are enclosed within braces
  • 27. 3) For number arrays, if all components of a row are not specified, the unspecified components are initialized to zero 2-Dimensional Arrays Initialization • Example: int anArray[3][5] = { { 1, 2, 3, 4, 5, }, // row 0 { 6, 7, 8, 9, 10, }, // row 1 { 11, 12, 13, 14, 15 } // row 2 };
  • 28. 2 DIM. Arrays: Example #include<stdio.h> #include<conio.h> int main() { int i, j; int matrix[2][2] = { {2,3,}, //row0 {5,7} //row1 }; printf(“n Resultant: n“); for(i = 0; i < 2; i++) { for(j = 0; j < 2; j++) { printf(" %d”, matrix[i][j]); } printf("n“); } getch(); }
  • 29. 2 DIM. Arrays: Class Exercise Write a C program using 2 DIM. array that gets 2x2 matrix input from the user and then prints the resultant matrix. The output should look like this:
  • 30. 2 DIM. Arrays: Exercise Solution #include<stdio.h> #include<conio.h> int main() { int matrix[2][2], i, j; for(i = 0; i < 2; i++) { for(j = 0; j < 2; j++)
  • 31. { printf(“n Enter values for [ %d %d ] = ”) ; scanf(“%d”, &matrix [i] [j]); } } printf("n Resultant: n“); for(i = 0; i < 2; i++) { for(j = 0; j < 2; j++) { printf(“ %d ”, matrix [i] [j]) ; } printf("n“); } getch(); }
  • 32. 2 DIM. Arrays: Class Exercise
  • 33. Write a C program using 2 DIM. array that gets two 2x2 matrices as an input from the user and then prints the sum of entered matrices. The output should look like this:
  • 34. 2 DIM. Arrays: Exercise Solution int main() { int mat1[2][2]; int mat2[2][2]; int mat[2][2]; //resultant int i, j, k, l; printf("n 1st Matrix: n n“); for(i=0; i<2; i++) { for(j=0; j<2; j++) { scanf(“%d”, &mat1[i][j]); } } printf("n 2nd Matrix: n n“); for(i=0; i<2; i++) { for(j=0; j<2; j++) { scanf(“%d”, &mat2[i][j]);
  • 35. } } printf("n Resultant: n“); for(k=0; k<2; k++) { for(l=0; l<2; l++) { mat[k][l]=(mat1[k][l] + mat2[k][l]); printf(“ %d ”, mat[k][l]); } printf("n“); } getch(); } 2 DIM. Arrays: Assignment 1) Write a C program using arrays that produces the multiplication of two 2x2 matrices.
  • 36. 2) Write a C program using arrays that gives the following output: Multidimensional Arrays • A collection of a fixed number of elements (called components) arranged in n dimensions (n >= 1) • Also called an n-dimensional array
  • 37. • General syntax of declaring an n-dimensional array is: dataType arrayName[intExp1][intExp2]...[intExpn]; where intExp1, intExp2, … are constant expressions yielding positive integer values Example: 3-Dimensional array: int table[3][2][4];
  • 39. Initializing 3-Dimensional Array Assignment Write a program of your own choice that makes use of arrays of more than 2 dimensions.
  • 40. Arrays as Parameters • This is one task that CAN be done to the WHOLE array • C always passes arrays by reference for (index = 0; index < how_many; index++) { printf (“Enter score %d ”, index); scanf (“%d”, &list[index]); } printf (“Enter how many students”); scanf (“%d”, &num_students); }
  • 41. Arrays as Parameters • The name of the array is a pointer constant • The address of the array is passed to the function • Size of the array also passed to control loop for (index = 0; index < how_many; index++) { printf (“Enter score %d ”, index); scanf }“%d”, &list[index]);( printf (“Enter how many students”); scanf (“%d”, &num_students); }
  • 42. Arrays as Parameters • Note the empty brackets in parameter list – A number can be placed here but it will be ignored for (index = 0; index < how_many; index++) { printf (“Enter score %d ”, index); scanf ( }“%d”, &list[index]); printf (“Enter how many students”); scanf (“%d”, &num_students); }
  • 43. Passing Arrays to Functions #include<stdio.h> #include<conio.h> int sum(int list[], int listSize) { int index, sum = 0; for(index=0; index<listSize; index++) sum = sum + list[index]; return sum; } int main() { int myArray[] = {2, 3, 5}; printf( "The sum is: %d ”, sum(myArray, 3)); getch(); }
  • 44. Home Work Write a program of that sorts the numbers you type in. The array may be able to get input until you enter 0. Sample output:
  • 45.
  • 46. C-String OR Character-Arrays • We have learned that the elements of an array can be just about anything int, char, double etc. • Consider an array whose elements are all characters • Such type of an array is called a C-String • In C language, a string is not a formal data type as it is in some languages (e.g., Pascal and Basic). Instead, String is an array of type Char.
  • 47. C-Strings OR Character Arrays • Character array: An array whose components are of type char • String: A sequence of zero or more characters enclosed in double quote marks (e.g., “hello”) • Internally (by the compiler) C-stings are terminated with null (‘0’) in memory » (the last character in a string is the null-character
  • 56. Declaration of C-Strings • Similar to declaration of any array char name[30]; // no initialization char title [20] = "Le Grande Fromage"; // initialized at declaration // with a string char chList [10] = {'a', 'b', 'c', 'd'}; // initialized with list of char // values
  • 57. Initializing Strings • When a character array is declared, it is legal to use the assignment operator to initialize • Note : use of the “ = “ operator is legal only for char array initialization • But : aggregate array assignment is NOT
  • 58. C-Strings: Example-1 #include<stdio.h> #include<conio.h> int main() { const int MAX = 80; //maximum characters in a string char str[MAX]; //string variable str printf( “Enter a string n”); scanf(“%s”, str); //put string in str greeting = “don’t do it;
  • 59. printf(“You entered: %s”, str); //display string from str getch(); } String I/O function • In dealing with string input, scanf() has a limitation that it does not accept multi-word strings separated by spaces. • For example, run the previous program by providing input string as “hello world”
  • 62. int main() { const int MAX = 80; //maximum characters in a string char str[MAX]; //string variable str puts( “Enter a string n”); gets(str); //put string in str printf(“You entered: %s”, str); //display string from str getch(); } Home Work Write a program of that reads and prints multiple text lines.
  • 63. String functions • Functions provided in #include <cstring>
  • 64. Working With Strings • C-strings are compared character by character using the collating sequence of the system • If we are using the ASCII character set Used instead of assignment Used for comparisons
  • 65. 1) The string "Air" is smaller than the string "Boat" 2) The string "Air" is smaller than the string "An" 3) The string "Bill" is smaller than the string "Billy" 4) The string "Hello" is smaller than "hello"
  • 72.