SlideShare a Scribd company logo
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:
Programming Fundamentals   Arrays and Strings
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
Programming Fundamentals   Arrays and Strings
String functions

More Related Content

What's hot (20)

Strings in C language
Strings in C languageStrings in C language
Strings in C language
P M Patil
 
Pointers
PointersPointers
Pointers
Prof. Dr. K. Adisesha
 
File handling in Python
File handling in PythonFile handling in Python
File handling in Python
Megha V
 
This pointer
This pointerThis pointer
This pointer
Kamal Acharya
 
Conditional operators
Conditional operatorsConditional operators
Conditional operators
BU
 
Python programming : List and tuples
Python programming : List and tuplesPython programming : List and tuples
Python programming : List and tuples
Emertxe Information Technologies Pvt Ltd
 
Python programming : Strings
Python programming : StringsPython programming : Strings
Python programming : Strings
Emertxe Information Technologies Pvt Ltd
 
Command Line Arguments in C#
Command Line Arguments in C#Command Line Arguments in C#
Command Line Arguments in C#
Ali Hassan
 
Python programming : Files
Python programming : FilesPython programming : Files
Python programming : Files
Emertxe Information Technologies Pvt Ltd
 
Manipulation strings in c++
Manipulation strings in c++Manipulation strings in c++
Manipulation strings in c++
SeethaDinesh
 
Java practical(baca sem v)
Java practical(baca sem v)Java practical(baca sem v)
Java practical(baca sem v)
mehul patel
 
Variadic functions
Variadic functionsVariadic functions
Variadic functions
Koganti Ravikumar
 
Exception handling and templates
Exception handling and templatesException handling and templates
Exception handling and templates
farhan amjad
 
Array and functions
Array and functionsArray and functions
Array and functions
Sun Technlogies
 
Introduction to array and string
Introduction to array and stringIntroduction to array and string
Introduction to array and string
MuntasirMuhit
 
Strings IN C
Strings IN CStrings IN C
Strings IN C
yndaravind
 
Java program structure
Java program structureJava program structure
Java program structure
shalinikarunakaran1
 
Function in c program
Function in c programFunction in c program
Function in c program
umesh patil
 
Java Strings
Java StringsJava Strings
Java Strings
RaBiya Chaudhry
 
Array
ArrayArray
Array
PRN USM
 

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
naveed jamali
 
Array
ArrayArray
Array
Anil Dutt
 
Array
ArrayArray
Array
PralhadKhanal1
 
Arrays
ArraysArrays
Arrays
RaziyasultanaShaik
 
array ppt of c programing language for exam
array ppt of c programing language for examarray ppt of c programing language for exam
array ppt of c programing language for exam
shimishtrivedi
 
array-191103180006.pdf
array-191103180006.pdfarray-191103180006.pdf
array-191103180006.pdf
HEMAHEMS5
 
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
imtiazalijoono
 
Array
ArrayArray
Array
hjasjhd
 
C (PPS)Programming for problem solving.pptx
C (PPS)Programming for problem solving.pptxC (PPS)Programming for problem solving.pptx
C (PPS)Programming for problem solving.pptx
rohinitalekar1
 
Unit4pptx__2024_11_ 11_10_16_09.pptx
Unit4pptx__2024_11_      11_10_16_09.pptxUnit4pptx__2024_11_      11_10_16_09.pptx
Unit4pptx__2024_11_ 11_10_16_09.pptx
GImpact
 
Arrays & Strings
Arrays & StringsArrays & Strings
Arrays & Strings
Munazza-Mah-Jabeen
 
COM1407: Arrays
COM1407: ArraysCOM1407: Arrays
COM1407: Arrays
Hemantha Kulathilake
 
Chapter 13.pptx
Chapter 13.pptxChapter 13.pptx
Chapter 13.pptx
AnisZahirahAzman
 
Unit 3
Unit 3 Unit 3
Unit 3
GOWSIKRAJAP
 
Multidimensional array in C
Multidimensional array in CMultidimensional array in C
Multidimensional array in C
Smit Parikh
 
presentation_arrays_1443553113_140676.ppt
presentation_arrays_1443553113_140676.pptpresentation_arrays_1443553113_140676.ppt
presentation_arrays_1443553113_140676.ppt
NamakkalPasanga
 
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
ajajkhan16
 
Unit 3
Unit 3 Unit 3
Unit 3
GOWSIKRAJAP
 
Module_3_Arrays - Updated.pptx............
Module_3_Arrays - Updated.pptx............Module_3_Arrays - Updated.pptx............
Module_3_Arrays - Updated.pptx............
ChiragKankani
 
Programming in c Arrays
Programming in c ArraysProgramming in c Arrays
Programming in c Arrays
janani thirupathi
 
Array,MULTI ARRAY, IN C
Array,MULTI ARRAY, IN CArray,MULTI ARRAY, IN C
Array,MULTI ARRAY, IN C
naveed jamali
 
array ppt of c programing language for exam
array ppt of c programing language for examarray ppt of c programing language for exam
array ppt of c programing language for exam
shimishtrivedi
 
array-191103180006.pdf
array-191103180006.pdfarray-191103180006.pdf
array-191103180006.pdf
HEMAHEMS5
 
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
imtiazalijoono
 
C (PPS)Programming for problem solving.pptx
C (PPS)Programming for problem solving.pptxC (PPS)Programming for problem solving.pptx
C (PPS)Programming for problem solving.pptx
rohinitalekar1
 
Unit4pptx__2024_11_ 11_10_16_09.pptx
Unit4pptx__2024_11_      11_10_16_09.pptxUnit4pptx__2024_11_      11_10_16_09.pptx
Unit4pptx__2024_11_ 11_10_16_09.pptx
GImpact
 
Multidimensional array in C
Multidimensional array in CMultidimensional array in C
Multidimensional array in C
Smit Parikh
 
presentation_arrays_1443553113_140676.ppt
presentation_arrays_1443553113_140676.pptpresentation_arrays_1443553113_140676.ppt
presentation_arrays_1443553113_140676.ppt
NamakkalPasanga
 
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
ajajkhan16
 
Module_3_Arrays - Updated.pptx............
Module_3_Arrays - Updated.pptx............Module_3_Arrays - Updated.pptx............
Module_3_Arrays - Updated.pptx............
ChiragKankani
 
Ad

More from imtiazalijoono (20)

Embedded systems io programming
Embedded systems   io programmingEmbedded systems   io programming
Embedded systems io programming
imtiazalijoono
 
Embedded systems tools & peripherals
Embedded systems   tools & peripheralsEmbedded systems   tools & peripherals
Embedded systems tools & peripherals
imtiazalijoono
 
Importance of reading and its types.
Importance of reading and its types.Importance of reading and its types.
Importance of reading and its types.
imtiazalijoono
 
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
imtiazalijoono
 
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
imtiazalijoono
 
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...
imtiazalijoono
 
Programming Fundamentals and basic knowledge
Programming Fundamentals and basic knowledge Programming Fundamentals and basic knowledge
Programming Fundamentals and basic knowledge
imtiazalijoono
 
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
imtiazalijoono
 
Software Development Software development process
Software Development Software development processSoftware Development Software development process
Software Development Software development process
imtiazalijoono
 
Programming Fundamentals Decisions
Programming Fundamentals  Decisions Programming Fundamentals  Decisions
Programming Fundamentals Decisions
imtiazalijoono
 
C Building Blocks
C Building Blocks C Building Blocks
C Building Blocks
imtiazalijoono
 
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
imtiazalijoono
 
Programming Fundamentals and Programming Languages Concepts
Programming Fundamentals and Programming Languages ConceptsProgramming Fundamentals and Programming Languages Concepts
Programming Fundamentals and Programming Languages Concepts
imtiazalijoono
 
Programming Global variable
Programming Global variableProgramming Global variable
Programming Global variable
imtiazalijoono
 
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,
imtiazalijoono
 
Arithmetic and Arithmetic assignment operators
Arithmetic and Arithmetic assignment operatorsArithmetic and Arithmetic assignment operators
Arithmetic and Arithmetic assignment operators
imtiazalijoono
 
INTRODUCTION TO COMPUTER PROGRAMMING
INTRODUCTION TO COMPUTER PROGRAMMINGINTRODUCTION TO COMPUTER PROGRAMMING
INTRODUCTION TO COMPUTER PROGRAMMING
imtiazalijoono
 
COMPUTER PROGRAMMING
COMPUTER PROGRAMMINGCOMPUTER PROGRAMMING
COMPUTER PROGRAMMING
imtiazalijoono
 
COMPUTER PROGRAMMING
COMPUTER PROGRAMMINGCOMPUTER PROGRAMMING
COMPUTER PROGRAMMING
imtiazalijoono
 
FIELD EFFECT TRANSISTERS (FET)
FIELD EFFECT TRANSISTERS (FET)FIELD EFFECT TRANSISTERS (FET)
FIELD EFFECT TRANSISTERS (FET)
imtiazalijoono
 
Embedded systems io programming
Embedded systems   io programmingEmbedded systems   io programming
Embedded systems io programming
imtiazalijoono
 
Embedded systems tools & peripherals
Embedded systems   tools & peripheralsEmbedded systems   tools & peripherals
Embedded systems tools & peripherals
imtiazalijoono
 
Importance of reading and its types.
Importance of reading and its types.Importance of reading and its types.
Importance of reading and its types.
imtiazalijoono
 
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
imtiazalijoono
 
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
imtiazalijoono
 
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...
imtiazalijoono
 
Programming Fundamentals and basic knowledge
Programming Fundamentals and basic knowledge Programming Fundamentals and basic knowledge
Programming Fundamentals and basic knowledge
imtiazalijoono
 
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
imtiazalijoono
 
Software Development Software development process
Software Development Software development processSoftware Development Software development process
Software Development Software development process
imtiazalijoono
 
Programming Fundamentals Decisions
Programming Fundamentals  Decisions Programming Fundamentals  Decisions
Programming Fundamentals Decisions
imtiazalijoono
 
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
imtiazalijoono
 
Programming Fundamentals and Programming Languages Concepts
Programming Fundamentals and Programming Languages ConceptsProgramming Fundamentals and Programming Languages Concepts
Programming Fundamentals and Programming Languages Concepts
imtiazalijoono
 
Programming Global variable
Programming Global variableProgramming Global variable
Programming Global variable
imtiazalijoono
 
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,
imtiazalijoono
 
Arithmetic and Arithmetic assignment operators
Arithmetic and Arithmetic assignment operatorsArithmetic and Arithmetic assignment operators
Arithmetic and Arithmetic assignment operators
imtiazalijoono
 
INTRODUCTION TO COMPUTER PROGRAMMING
INTRODUCTION TO COMPUTER PROGRAMMINGINTRODUCTION TO COMPUTER PROGRAMMING
INTRODUCTION TO COMPUTER PROGRAMMING
imtiazalijoono
 
FIELD EFFECT TRANSISTERS (FET)
FIELD EFFECT TRANSISTERS (FET)FIELD EFFECT TRANSISTERS (FET)
FIELD EFFECT TRANSISTERS (FET)
imtiazalijoono
 
Ad

Recently uploaded (20)

Parenting Teens: Supporting Trust, resilience and independence
Parenting Teens: Supporting Trust, resilience and independenceParenting Teens: Supporting Trust, resilience and independence
Parenting Teens: Supporting Trust, resilience and independence
Pooky Knightsmith
 
How to Configure Vendor Management in Lunch App of Odoo 18
How to Configure Vendor Management in Lunch App of Odoo 18How to Configure Vendor Management in Lunch App of Odoo 18
How to Configure Vendor Management in Lunch App of Odoo 18
Celine George
 
How to Create Quotation Templates Sequence in Odoo 18 Sales
How to Create Quotation Templates Sequence in Odoo 18 SalesHow to Create Quotation Templates Sequence in Odoo 18 Sales
How to Create Quotation Templates Sequence in Odoo 18 Sales
Celine George
 
EUPHORIA GENERAL QUIZ FINALS | QUIZ CLUB OF PSGCAS | 21 MARCH 2025
EUPHORIA GENERAL QUIZ FINALS | QUIZ CLUB OF PSGCAS | 21 MARCH 2025EUPHORIA GENERAL QUIZ FINALS | QUIZ CLUB OF PSGCAS | 21 MARCH 2025
EUPHORIA GENERAL QUIZ FINALS | QUIZ CLUB OF PSGCAS | 21 MARCH 2025
Quiz Club of PSG College of Arts & Science
 
Pests of Rice: Damage, Identification, Life history, and Management.pptx
Pests of Rice: Damage, Identification, Life history, and Management.pptxPests of Rice: Damage, Identification, Life history, and Management.pptx
Pests of Rice: Damage, Identification, Life history, and Management.pptx
Arshad Shaikh
 
Exploring Ocean Floor Features for Middle School
Exploring Ocean Floor Features for Middle SchoolExploring Ocean Floor Features for Middle School
Exploring Ocean Floor Features for Middle School
Marie
 
How to Manage Maintenance Request in Odoo 18
How to Manage Maintenance Request in Odoo 18How to Manage Maintenance Request in Odoo 18
How to Manage Maintenance Request in Odoo 18
Celine George
 
Artificial intelligence Presented by JM.
Artificial intelligence Presented by JM.Artificial intelligence Presented by JM.
Artificial intelligence Presented by JM.
jmansha170
 
Optimization technique in pharmaceutical product development.pptx
Optimization technique in pharmaceutical product development.pptxOptimization technique in pharmaceutical product development.pptx
Optimization technique in pharmaceutical product development.pptx
UrmiPrajapati3
 
Rose Cultivation Practices by Kushal Lamichhane.pdf
Rose Cultivation Practices by Kushal Lamichhane.pdfRose Cultivation Practices by Kushal Lamichhane.pdf
Rose Cultivation Practices by Kushal Lamichhane.pdf
kushallamichhame
 
Trends Spotting Strategic foresight for tomorrow’s education systems - Debora...
Trends Spotting Strategic foresight for tomorrow’s education systems - Debora...Trends Spotting Strategic foresight for tomorrow’s education systems - Debora...
Trends Spotting Strategic foresight for tomorrow’s education systems - Debora...
EduSkills OECD
 
Module 4 Presentation - Enhancing Competencies and Engagement Strategies in Y...
Module 4 Presentation - Enhancing Competencies and Engagement Strategies in Y...Module 4 Presentation - Enhancing Competencies and Engagement Strategies in Y...
Module 4 Presentation - Enhancing Competencies and Engagement Strategies in Y...
GeorgeDiamandis11
 
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptxDiptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Arshad Shaikh
 
SEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptx
SEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptxSEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptx
SEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptx
PoojaSen20
 
TV Shows and web-series quiz | QUIZ CLUB OF PSGCAS | 13TH MARCH 2025
TV Shows and web-series quiz | QUIZ CLUB OF PSGCAS | 13TH MARCH 2025TV Shows and web-series quiz | QUIZ CLUB OF PSGCAS | 13TH MARCH 2025
TV Shows and web-series quiz | QUIZ CLUB OF PSGCAS | 13TH MARCH 2025
Quiz Club of PSG College of Arts & Science
 
Final Sketch Designs for poster production.pptx
Final Sketch Designs for poster production.pptxFinal Sketch Designs for poster production.pptx
Final Sketch Designs for poster production.pptx
bobby205207
 
Unit 3 Poster Sketches with annotations.pptx
Unit 3 Poster Sketches with annotations.pptxUnit 3 Poster Sketches with annotations.pptx
Unit 3 Poster Sketches with annotations.pptx
bobby205207
 
Basic English for Communication - Dr Hj Euis Eti Rohaeti Mpd
Basic English for Communication - Dr Hj Euis Eti Rohaeti MpdBasic English for Communication - Dr Hj Euis Eti Rohaeti Mpd
Basic English for Communication - Dr Hj Euis Eti Rohaeti Mpd
Restu Bias Primandhika
 
Respiratory System , Urinary System
Respiratory  System , Urinary SystemRespiratory  System , Urinary System
Respiratory System , Urinary System
RushiMandali
 
june 10 2025 ppt for madden on art science is over.pptx
june 10 2025 ppt for madden on art science is over.pptxjune 10 2025 ppt for madden on art science is over.pptx
june 10 2025 ppt for madden on art science is over.pptx
roger malina
 
Parenting Teens: Supporting Trust, resilience and independence
Parenting Teens: Supporting Trust, resilience and independenceParenting Teens: Supporting Trust, resilience and independence
Parenting Teens: Supporting Trust, resilience and independence
Pooky Knightsmith
 
How to Configure Vendor Management in Lunch App of Odoo 18
How to Configure Vendor Management in Lunch App of Odoo 18How to Configure Vendor Management in Lunch App of Odoo 18
How to Configure Vendor Management in Lunch App of Odoo 18
Celine George
 
How to Create Quotation Templates Sequence in Odoo 18 Sales
How to Create Quotation Templates Sequence in Odoo 18 SalesHow to Create Quotation Templates Sequence in Odoo 18 Sales
How to Create Quotation Templates Sequence in Odoo 18 Sales
Celine George
 
Pests of Rice: Damage, Identification, Life history, and Management.pptx
Pests of Rice: Damage, Identification, Life history, and Management.pptxPests of Rice: Damage, Identification, Life history, and Management.pptx
Pests of Rice: Damage, Identification, Life history, and Management.pptx
Arshad Shaikh
 
Exploring Ocean Floor Features for Middle School
Exploring Ocean Floor Features for Middle SchoolExploring Ocean Floor Features for Middle School
Exploring Ocean Floor Features for Middle School
Marie
 
How to Manage Maintenance Request in Odoo 18
How to Manage Maintenance Request in Odoo 18How to Manage Maintenance Request in Odoo 18
How to Manage Maintenance Request in Odoo 18
Celine George
 
Artificial intelligence Presented by JM.
Artificial intelligence Presented by JM.Artificial intelligence Presented by JM.
Artificial intelligence Presented by JM.
jmansha170
 
Optimization technique in pharmaceutical product development.pptx
Optimization technique in pharmaceutical product development.pptxOptimization technique in pharmaceutical product development.pptx
Optimization technique in pharmaceutical product development.pptx
UrmiPrajapati3
 
Rose Cultivation Practices by Kushal Lamichhane.pdf
Rose Cultivation Practices by Kushal Lamichhane.pdfRose Cultivation Practices by Kushal Lamichhane.pdf
Rose Cultivation Practices by Kushal Lamichhane.pdf
kushallamichhame
 
Trends Spotting Strategic foresight for tomorrow’s education systems - Debora...
Trends Spotting Strategic foresight for tomorrow’s education systems - Debora...Trends Spotting Strategic foresight for tomorrow’s education systems - Debora...
Trends Spotting Strategic foresight for tomorrow’s education systems - Debora...
EduSkills OECD
 
Module 4 Presentation - Enhancing Competencies and Engagement Strategies in Y...
Module 4 Presentation - Enhancing Competencies and Engagement Strategies in Y...Module 4 Presentation - Enhancing Competencies and Engagement Strategies in Y...
Module 4 Presentation - Enhancing Competencies and Engagement Strategies in Y...
GeorgeDiamandis11
 
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptxDiptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Arshad Shaikh
 
SEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptx
SEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptxSEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptx
SEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptx
PoojaSen20
 
Final Sketch Designs for poster production.pptx
Final Sketch Designs for poster production.pptxFinal Sketch Designs for poster production.pptx
Final Sketch Designs for poster production.pptx
bobby205207
 
Unit 3 Poster Sketches with annotations.pptx
Unit 3 Poster Sketches with annotations.pptxUnit 3 Poster Sketches with annotations.pptx
Unit 3 Poster Sketches with annotations.pptx
bobby205207
 
Basic English for Communication - Dr Hj Euis Eti Rohaeti Mpd
Basic English for Communication - Dr Hj Euis Eti Rohaeti MpdBasic English for Communication - Dr Hj Euis Eti Rohaeti Mpd
Basic English for Communication - Dr Hj Euis Eti Rohaeti Mpd
Restu Bias Primandhika
 
Respiratory System , Urinary System
Respiratory  System , Urinary SystemRespiratory  System , Urinary System
Respiratory System , Urinary System
RushiMandali
 
june 10 2025 ppt for madden on art science is over.pptx
june 10 2025 ppt for madden on art science is over.pptxjune 10 2025 ppt for madden on art science is over.pptx
june 10 2025 ppt for madden on art science is over.pptx
roger malina
 

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:
  • 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"