SlideShare une entreprise Scribd logo
1  sur  9
C - Arrays
C programming language provides a data structure called the array, which can store a fixed-size sequential
collection of elements ofthe same type. An array is used to store a collection ofdata, but it is often more useful to
think of an array as a collection of variables of the same type.
Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare one array
variable such as numbers and use numbers[0],numbers[1],and ..., numbers[99]to representindividual variables.
A specific element in an array is accessed by an index.
All arrays consistofcontiguous memorylocations. The lowest address corresponds to the first element and the
highest address to the last element.
Declaring Arrays
To declare an array in C, a programmer specifies the type of the elements and the number of elements required
by an array as follows:
typearrayName[arraySize];
This is called a single-dimensional array. The arraySize must be an integer constant greater than zero
and type can be any valid C data type. For example, to declare a 10-element array called balance of type
double, use this statement:
double balance[10];
Now balance is avariable array which is sufficient to hold upto 10 double numbers.
Initializing Arrays
You can initialize array in C either one by one or using a single statement as follows:
double balance[5]={1000.0,2.0,3.4,7.0,50.0};
The number of values between braces { } can not be larger than the number of elements that we declare for the
array between square brackets [ ].
If you omit the size of the array, an array just big enough to hold the initialization is created. Therefore, if you
write:
double balance[]={1000.0,2.0,3.4,7.0,50.0};
You will create exactly the same array as you did in the previous example. Following is an example to assign a
single element of the array:
balance[4]=50.0;
The above statementassigns elementnumber 5th in the array with a value of 50.0. All arrays have 0 as the index
of their first elementwhich is also called base indexand last index of an array will be total size of the array minus
1. Following is the pictorial representation of the same array we discussed above:
Accessing Array Elements
An element is accessed by indexing the array name. This is done by placing the index of the element within
square brackets after the name of the array. For example:
double salary = balance[9];
The above statement will take 10th element from the array and assign the value to salary variable. Following is
an example which will use all the above mentioned three concepts viz. declaration, assignment and accessing
arrays:
#include <stdio.h>
int main ()
{
int n[ 10 ]; /* n is an array of 10 integers*/
inti,j;
/* initialize elementsofarray n to 0 */
for ( i = 0; i< 10; i++ )
{
n[ i ] = i + 100; /* setelementat location i to i + 100 */
}
/* output each array element'svalue */
for (j = 0; j < 10; j++ )
{
printf("Element[%d]=%dn",j, n[j]);
}
return 0;
}
Out put:
Element[0] = 100
Element[1] = 101
Element[2] = 102
Element[3] = 103
Element[4] = 104
Element[5] = 105
Element[6] = 106
Element[7] = 107
Element[8] = 108
Element[9] = 109
C Arrays in Detail
Arrays are important to C and should need lots of more details. There are following few important concepts
related to array which should be clear to a C programmer:
Concept Description
Multi-dimensional arrays
C supports multidimensional arrays.The simplestform ofthe
multidimensional arrayis the two-dimensional array.
Passing arrays to functions
You can pass to the function a pointer to an array by specifying the
array's name withoutan index.
Return array from a function C allows a function to return an array.
Pointer to an array
You can generate a pointer to the firstelementof an array by sim ply
specifying the array name,withoutany index.
Multi-dimensional Arrays in C
C programming language allows multidimensional arrays. Here is the general form of a multidimensional array
declaration:
type name[size1][size2]...[sizeN];
For example, the following declaration creates a three dimensional 5 .10 . 4 integer array:
intthreedim[5][10][4];
Two-Dimensional Arrays:
The simplest form of the multidimensional array is the two-dimensional array. A two-dimensional array is, in
essence,a listof one-dimensional arrays. To declare a two-dimensional integer array of size x,y you would write
something as follows:
typearrayName[ x ][ y ];
Where type can be any valid C data type and arrayName will be a valid C identifier.A two-dimensional array can
be think as a table which will have x number of rows and y number of columns. A 2-dimensional array a, which
contains three rows and four columns can be shown as below:
Thus, every element in array a is identified by an element name of the form a[ i ][ j ], where a is the name of the
array, and i and j are the subscripts that uniquely identify each element in a.
Initializing Two-Dimensional Arrays:
Multidimensional arrays maybe initialized by specifying bracketed values for each row. Following is an array with
3 rows and each row has 4 columns.
int a[3][4]={
{0,1,2,3},/* initializers for row indexed by 0 */
{4,5,6,7},/* initializers for row indexed by 1 */
{8,9,10,11}/* initializers for row indexed by 2 */
};
The nested braces, which indicate the intended row, are optional. The following initialization is equivalent to
previous example:
int a[3][4]={0,1,2,3,4,5,6,7,8,9,10,11};
Accessing Two-Dimensional Array Elements:
An element in 2-dimensional array is accessed by using the subscripts, i.e., row index and column index of the
array. For example:
intval= a[2][3];
The above statement will take 4th element from the 3rd row of the array. You can verify it in the above diagram.
Let us check below program where we have used nested loop to handle a two dimensional array:
#include<stdio.h>
int main()
{
inti,j;
// declaring and Initializing array
intarr[2][2] = {10,20,30,40};
/* Above array can be initialized as below also
arr[0][0] = 10; // Initializing array
arr[0][1] = 20;
arr[1][0] = 30;
arr[1][1] = 40;
*/
for (i=0;i<2;i++)
{
for (j=0;j<2;j++)
{
// Accessing variables
printf("value of arr[%d] [%d] : %dn",i,j,arr[i][j]);
}
}}
Output:
value of arr[0] [0] is 10
value of arr[0] [1] is 20
value of arr[1] [0] is 30
value of arr[1] [1] is 40
C – String
 C Strings are nothing but array of characters ended with null character (‘0’).
 This null character indicates the end of the string.
 Strings are always enclosed by double quotes. Whereas, character is enclosed by single quotes in C.
Example for C string:
 char string[20] = { ‘f’ , ’r’ , ‘e’ , ‘s’ , ‘h’ , ‘2’ , ‘r’ , ‘e’ , ‘f’ , ’r’ , ‘e’ , ‘s’ , ‘h’ , ‘0’}; (or)
 char string[20] = “fresh2refresh”; (or)
 char string [] = “fresh2refresh”;
 Difference between above declarations are, when we declare char as “string[20]“, 20 bytes of memory space is
allocated for holding the string value.
 When we declare char as “string [] “, memory space will be allocated as per the requirement during execution of the
program.
#include <stdio.h>
int main ()
{
char string[20] = "NIIT.com";
printf("The stringis : %s n", string );
return 0;
}
Output:
The string is : NIIT.com
C String functions:
 String.h header file supports all the string functions in C language. All the string functions are given below.
S.no
String
functions
Description
1 strcat ( ) Concatenates str2 at theend of str1.
2 strncat ( ) appends a portion of string to another
3 strcpy ( ) Copies str2 into str1
4 strncpy ( ) copies given number of characters of one string to another
5 strlen ( ) gives the length of str1.
6 strcmp ( )
Returns 0 if str1 is same as str2. Returns <0 if strl< str2. Returns >0 if
str1 > str2.
C – strcat() function
 strcat( ) function in C language concatenates two given strings. It concatenates source string at the end of destination
string. Syntax for strcat( ) function is given below.
char * strcat( char * destination,constchar * source );
 Example :
strcat ( str2, str1 ); - str1 is concatenated at the end of str2.
strcat ( str1, str2 ); - str2 is concatenated at the end of str1.
 As you know, each string in C is ended up with null character (‘0′).
 In strcat( ) operation, null character of destination string is overwritten by source string’s first character and null
character is added at the end of new destination string which is created after strcat( ) operation.
Example program for strcat( ) function in C:
 In this program, two strings “NIIT” and “C tutorial” are concatenated using strcat( ) function and result is
displayed as “C tutorial NIIT”.
#include <stdio.h>
#include <string.h>
int main( )
{
char source[] = " NIIT" ;
char target[ ]= " C tutorial" ;
printf ( "nSource string = %s",source ) ;
printf ( "nTarget string = %s",target ) ;
strcat ( target, source ) ;
printf ( "nTarget string afterstrcat( ) = %s", target ) ;
}
Output:
Source string = NIIT
Target string = C tutorial
Target string after strcat( ) = C tutorial NIIT
C – strncat() function
 strncat( ) function in C language concatenates ( appends ) portion of one string at the end of another string. Syntax for
strncat( ) function is given below.
char * strncat( char * destination,constchar * source,size_tnum );
 Example :
strncat( str2,str1, 3 ); – First3 characters of str1 is concatenated atthe end of str2.
strncat( str1,str2, 3 ); - First 3 characters of str2 is concatenated at the end of str1.
 As you know, each string in C is ended up with null character (‘0′).
 In strncat( ) operation, null character of destination string is overwritten by source string’s first character and null
character is added at the end of new destination string which is created after strncat( ) operation.
Example program for strncat( ) function in C:
 In this program, first 5 characters of the string “NIIT” is concatenated at the end of the string”C tutorial” using
strncat( ) function and result is displayed as “C tutorial fres”.
#include <stdio.h>
#include <string.h>
int main( )
{
char source[] = " NIIT" ;
char target[ ]= "C tutorial" ;
printf ( "nSource string = %s",source ) ;
printf ( "nTarget string = %s",target ) ;
strncat ( target, source,5 ) ;
printf ( "nTarget string afterstrncat( ) = %s",target ) ;
}
Output:
Source string = NIIT
Target string = C tutorial
Target string after strcat( ) = C tutorial fres
C – strcpy() function
 strcpy( ) function copies contents of one string into another string. Syntax for strcpy function is given below.
char * strcpy ( char * destination,constchar * source );
 Example:
strcpy ( str1,str2) – It copies contents ofstr2 into str1.
strcpy ( str2,str1) – It copies contents ofstr1 into str2.
 If destination string length is less than source string, entire source string value won’t be copied into destination string.
 For example, consider destination string length is 20 and source string length is 30. Then, only 20 characters from
source string will be copied into destination string and remaining 10 characters won’t be copied and will be truncated.
Example program for strcpy( ) function in C:
 In this program, source string “NIIT” is copied into target string using strcpy( ) function.
#include <stdio.h>
#include <string.h>
int main( )
{
char source[] = "NIIT" ;
char target[20]= "" ;
printf ( "nsource string = %s",source ) ;
printf ( "ntargetstring = %s",target ) ;
strcpy ( target, source ) ;
printf ( "ntargetstring after strcpy( ) = %s",target ) ;
return 0;
}
Output:
source string = NIIT
target string =
target string after strcpy( ) = NIIT

Contenu connexe

Tendances (20)

Unit 2
Unit 2Unit 2
Unit 2
 
Programming in c Arrays
Programming in c ArraysProgramming in c Arrays
Programming in c Arrays
 
Arrays in C language
Arrays in C languageArrays in C language
Arrays in C language
 
C programming session 05
C programming session 05C programming session 05
C programming session 05
 
Arrays and Strings
Arrays and Strings Arrays and Strings
Arrays and Strings
 
C Programming Unit-3
C Programming Unit-3C Programming Unit-3
C Programming Unit-3
 
C++ lecture 04
C++ lecture 04C++ lecture 04
C++ lecture 04
 
Arrays and strings in c++
Arrays and strings in c++Arrays and strings in c++
Arrays and strings in c++
 
Tut1
Tut1Tut1
Tut1
 
Lecture 9
Lecture 9Lecture 9
Lecture 9
 
Array and string
Array and stringArray and string
Array and string
 
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
 
Arrays
ArraysArrays
Arrays
 
Unitii classnotes
Unitii classnotesUnitii classnotes
Unitii classnotes
 
Arrays
ArraysArrays
Arrays
 
Unit4 Slides
Unit4 SlidesUnit4 Slides
Unit4 Slides
 
Unit 6. Arrays
Unit 6. ArraysUnit 6. Arrays
Unit 6. Arrays
 
COM1407: Arrays
COM1407: ArraysCOM1407: Arrays
COM1407: Arrays
 
Arrays
ArraysArrays
Arrays
 
Memory management of datatypes
Memory management of datatypesMemory management of datatypes
Memory management of datatypes
 

Similaire à Arrays

Homework Assignment – Array Technical DocumentWrite a technical .pdf
Homework Assignment – Array Technical DocumentWrite a technical .pdfHomework Assignment – Array Technical DocumentWrite a technical .pdf
Homework Assignment – Array Technical DocumentWrite a technical .pdfaroraopticals15
 
Arrays and library functions
Arrays and library functionsArrays and library functions
Arrays and library functionsSwarup Boro
 
Functions, Strings ,Storage classes in C
 Functions, Strings ,Storage classes in C Functions, Strings ,Storage classes in C
Functions, Strings ,Storage classes in Carshpreetkaur07
 
C programming session 04
C programming session 04C programming session 04
C programming session 04Dushmanta Nath
 
Array assignment
Array assignmentArray assignment
Array assignmentAhmad Kamal
 
3.ArraysandPointers.pptx
3.ArraysandPointers.pptx3.ArraysandPointers.pptx
3.ArraysandPointers.pptxFolkAdonis
 
Intro to C# - part 2.pptx emerging technology
Intro to C# - part 2.pptx emerging technologyIntro to C# - part 2.pptx emerging technology
Intro to C# - part 2.pptx emerging technologyworldchannel
 
C UNIT-3 PREPARED BY M V B REDDY
C UNIT-3 PREPARED BY M V B REDDYC UNIT-3 PREPARED BY M V B REDDY
C UNIT-3 PREPARED BY M V B REDDYRajeshkumar Reddy
 
Programming in c arrays
Programming in c   arraysProgramming in c   arrays
Programming in c arraysUma mohan
 
Data Structure Midterm Lesson Arrays
Data Structure Midterm Lesson ArraysData Structure Midterm Lesson Arrays
Data Structure Midterm Lesson ArraysMaulen Bale
 
C++ - UNIT_-_IV.pptx which contains details about Pointers
C++ - UNIT_-_IV.pptx which contains details about PointersC++ - UNIT_-_IV.pptx which contains details about Pointers
C++ - UNIT_-_IV.pptx which contains details about PointersANUSUYA S
 
C++ Programming Homework Help
C++ Programming Homework HelpC++ Programming Homework Help
C++ Programming Homework HelpC++ Homework Help
 
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.pdfajajkhan16
 

Similaire à Arrays (20)

Homework Assignment – Array Technical DocumentWrite a technical .pdf
Homework Assignment – Array Technical DocumentWrite a technical .pdfHomework Assignment – Array Technical DocumentWrite a technical .pdf
Homework Assignment – Array Technical DocumentWrite a technical .pdf
 
Introduction to Arrays in C
Introduction to Arrays in CIntroduction to Arrays in C
Introduction to Arrays in C
 
Arrays and library functions
Arrays and library functionsArrays and library functions
Arrays and library functions
 
Functions, Strings ,Storage classes in C
 Functions, Strings ,Storage classes in C Functions, Strings ,Storage classes in C
Functions, Strings ,Storage classes in C
 
C programming session 04
C programming session 04C programming session 04
C programming session 04
 
Array
ArrayArray
Array
 
02 arrays
02 arrays02 arrays
02 arrays
 
Unit ii data structure-converted
Unit  ii data structure-convertedUnit  ii data structure-converted
Unit ii data structure-converted
 
Array assignment
Array assignmentArray assignment
Array assignment
 
3.ArraysandPointers.pptx
3.ArraysandPointers.pptx3.ArraysandPointers.pptx
3.ArraysandPointers.pptx
 
Intro to C# - part 2.pptx emerging technology
Intro to C# - part 2.pptx emerging technologyIntro to C# - part 2.pptx emerging technology
Intro to C# - part 2.pptx emerging technology
 
C UNIT-3 PREPARED BY M V B REDDY
C UNIT-3 PREPARED BY M V B REDDYC UNIT-3 PREPARED BY M V B REDDY
C UNIT-3 PREPARED BY M V B REDDY
 
Programming in c arrays
Programming in c   arraysProgramming in c   arrays
Programming in c arrays
 
Arrays
ArraysArrays
Arrays
 
Data Structure Midterm Lesson Arrays
Data Structure Midterm Lesson ArraysData Structure Midterm Lesson Arrays
Data Structure Midterm Lesson Arrays
 
C++ - UNIT_-_IV.pptx which contains details about Pointers
C++ - UNIT_-_IV.pptx which contains details about PointersC++ - UNIT_-_IV.pptx which contains details about Pointers
C++ - UNIT_-_IV.pptx which contains details about Pointers
 
C++ Programming Homework Help
C++ Programming Homework HelpC++ Programming Homework Help
C++ Programming Homework Help
 
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
 
Arrays
ArraysArrays
Arrays
 
Arrays
ArraysArrays
Arrays
 

Plus de Chukka Nikhil Chakravarthy (20)

DESIGN AND DEVELOPMENT OF SOLAR CHARGE CONTROLLER WITH SUN TRACKING
DESIGN AND DEVELOPMENT OF SOLAR CHARGE CONTROLLER WITH SUN TRACKINGDESIGN AND DEVELOPMENT OF SOLAR CHARGE CONTROLLER WITH SUN TRACKING
DESIGN AND DEVELOPMENT OF SOLAR CHARGE CONTROLLER WITH SUN TRACKING
 
Li fi
Li fiLi fi
Li fi
 
extint,endangered, endmic species
extint,endangered, endmic speciesextint,endangered, endmic species
extint,endangered, endmic species
 
types of resources
types of resourcestypes of resources
types of resources
 
ISOMETRIC DRAWING
ISOMETRIC DRAWINGISOMETRIC DRAWING
ISOMETRIC DRAWING
 
ORTHOGRAPHIC PROJECTIONS
ORTHOGRAPHIC PROJECTIONSORTHOGRAPHIC PROJECTIONS
ORTHOGRAPHIC PROJECTIONS
 
projection of solide
projection of solideprojection of solide
projection of solide
 
projection of solids
projection of solidsprojection of solids
projection of solids
 
projection of planes
projection of planesprojection of planes
projection of planes
 
projection of planes
projection of planesprojection of planes
projection of planes
 
angle of projections
angle of projectionsangle of projections
angle of projections
 
construction of ellipse and scales
construction of ellipse and scalesconstruction of ellipse and scales
construction of ellipse and scales
 
Unit 8
Unit 8Unit 8
Unit 8
 
Unit 7
Unit 7Unit 7
Unit 7
 
Unit 6
Unit 6Unit 6
Unit 6
 
Unit 5
Unit 5Unit 5
Unit 5
 
C tutorial
C tutorialC tutorial
C tutorial
 
C – operators and expressions
C – operators and expressionsC – operators and expressions
C – operators and expressions
 
Looping statements
Looping statementsLooping statements
Looping statements
 
7 wonders of world(new)
7 wonders of world(new)7 wonders of world(new)
7 wonders of world(new)
 

Dernier

New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DaySri Ambati
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 

Dernier (20)

New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 

Arrays

  • 1. C - Arrays C programming language provides a data structure called the array, which can store a fixed-size sequential collection of elements ofthe same type. An array is used to store a collection ofdata, but it is often more useful to think of an array as a collection of variables of the same type. Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare one array variable such as numbers and use numbers[0],numbers[1],and ..., numbers[99]to representindividual variables. A specific element in an array is accessed by an index. All arrays consistofcontiguous memorylocations. The lowest address corresponds to the first element and the highest address to the last element. Declaring Arrays To declare an array in C, a programmer specifies the type of the elements and the number of elements required by an array as follows: typearrayName[arraySize]; This is called a single-dimensional array. The arraySize must be an integer constant greater than zero and type can be any valid C data type. For example, to declare a 10-element array called balance of type double, use this statement: double balance[10]; Now balance is avariable array which is sufficient to hold upto 10 double numbers. Initializing Arrays You can initialize array in C either one by one or using a single statement as follows: double balance[5]={1000.0,2.0,3.4,7.0,50.0}; The number of values between braces { } can not be larger than the number of elements that we declare for the array between square brackets [ ]. If you omit the size of the array, an array just big enough to hold the initialization is created. Therefore, if you write: double balance[]={1000.0,2.0,3.4,7.0,50.0}; You will create exactly the same array as you did in the previous example. Following is an example to assign a single element of the array: balance[4]=50.0; The above statementassigns elementnumber 5th in the array with a value of 50.0. All arrays have 0 as the index of their first elementwhich is also called base indexand last index of an array will be total size of the array minus 1. Following is the pictorial representation of the same array we discussed above:
  • 2. Accessing Array Elements An element is accessed by indexing the array name. This is done by placing the index of the element within square brackets after the name of the array. For example: double salary = balance[9]; The above statement will take 10th element from the array and assign the value to salary variable. Following is an example which will use all the above mentioned three concepts viz. declaration, assignment and accessing arrays: #include <stdio.h> int main () { int n[ 10 ]; /* n is an array of 10 integers*/ inti,j; /* initialize elementsofarray n to 0 */ for ( i = 0; i< 10; i++ ) { n[ i ] = i + 100; /* setelementat location i to i + 100 */ } /* output each array element'svalue */ for (j = 0; j < 10; j++ ) { printf("Element[%d]=%dn",j, n[j]); } return 0; }
  • 3. Out put: Element[0] = 100 Element[1] = 101 Element[2] = 102 Element[3] = 103 Element[4] = 104 Element[5] = 105 Element[6] = 106 Element[7] = 107 Element[8] = 108 Element[9] = 109 C Arrays in Detail Arrays are important to C and should need lots of more details. There are following few important concepts related to array which should be clear to a C programmer: Concept Description Multi-dimensional arrays C supports multidimensional arrays.The simplestform ofthe multidimensional arrayis the two-dimensional array. Passing arrays to functions You can pass to the function a pointer to an array by specifying the array's name withoutan index. Return array from a function C allows a function to return an array. Pointer to an array You can generate a pointer to the firstelementof an array by sim ply specifying the array name,withoutany index. Multi-dimensional Arrays in C C programming language allows multidimensional arrays. Here is the general form of a multidimensional array declaration: type name[size1][size2]...[sizeN]; For example, the following declaration creates a three dimensional 5 .10 . 4 integer array: intthreedim[5][10][4]; Two-Dimensional Arrays: The simplest form of the multidimensional array is the two-dimensional array. A two-dimensional array is, in essence,a listof one-dimensional arrays. To declare a two-dimensional integer array of size x,y you would write something as follows: typearrayName[ x ][ y ];
  • 4. Where type can be any valid C data type and arrayName will be a valid C identifier.A two-dimensional array can be think as a table which will have x number of rows and y number of columns. A 2-dimensional array a, which contains three rows and four columns can be shown as below: Thus, every element in array a is identified by an element name of the form a[ i ][ j ], where a is the name of the array, and i and j are the subscripts that uniquely identify each element in a. Initializing Two-Dimensional Arrays: Multidimensional arrays maybe initialized by specifying bracketed values for each row. Following is an array with 3 rows and each row has 4 columns. int a[3][4]={ {0,1,2,3},/* initializers for row indexed by 0 */ {4,5,6,7},/* initializers for row indexed by 1 */ {8,9,10,11}/* initializers for row indexed by 2 */ }; The nested braces, which indicate the intended row, are optional. The following initialization is equivalent to previous example: int a[3][4]={0,1,2,3,4,5,6,7,8,9,10,11}; Accessing Two-Dimensional Array Elements: An element in 2-dimensional array is accessed by using the subscripts, i.e., row index and column index of the array. For example: intval= a[2][3]; The above statement will take 4th element from the 3rd row of the array. You can verify it in the above diagram. Let us check below program where we have used nested loop to handle a two dimensional array: #include<stdio.h> int main() { inti,j; // declaring and Initializing array intarr[2][2] = {10,20,30,40}; /* Above array can be initialized as below also arr[0][0] = 10; // Initializing array arr[0][1] = 20; arr[1][0] = 30; arr[1][1] = 40; */ for (i=0;i<2;i++) { for (j=0;j<2;j++) { // Accessing variables
  • 5. printf("value of arr[%d] [%d] : %dn",i,j,arr[i][j]); } }} Output: value of arr[0] [0] is 10 value of arr[0] [1] is 20 value of arr[1] [0] is 30 value of arr[1] [1] is 40 C – String  C Strings are nothing but array of characters ended with null character (‘0’).  This null character indicates the end of the string.  Strings are always enclosed by double quotes. Whereas, character is enclosed by single quotes in C. Example for C string:  char string[20] = { ‘f’ , ’r’ , ‘e’ , ‘s’ , ‘h’ , ‘2’ , ‘r’ , ‘e’ , ‘f’ , ’r’ , ‘e’ , ‘s’ , ‘h’ , ‘0’}; (or)  char string[20] = “fresh2refresh”; (or)  char string [] = “fresh2refresh”;  Difference between above declarations are, when we declare char as “string[20]“, 20 bytes of memory space is allocated for holding the string value.  When we declare char as “string [] “, memory space will be allocated as per the requirement during execution of the program. #include <stdio.h> int main () { char string[20] = "NIIT.com"; printf("The stringis : %s n", string ); return 0; }
  • 6. Output: The string is : NIIT.com C String functions:  String.h header file supports all the string functions in C language. All the string functions are given below. S.no String functions Description 1 strcat ( ) Concatenates str2 at theend of str1. 2 strncat ( ) appends a portion of string to another 3 strcpy ( ) Copies str2 into str1 4 strncpy ( ) copies given number of characters of one string to another 5 strlen ( ) gives the length of str1. 6 strcmp ( ) Returns 0 if str1 is same as str2. Returns <0 if strl< str2. Returns >0 if str1 > str2. C – strcat() function  strcat( ) function in C language concatenates two given strings. It concatenates source string at the end of destination string. Syntax for strcat( ) function is given below. char * strcat( char * destination,constchar * source );  Example : strcat ( str2, str1 ); - str1 is concatenated at the end of str2. strcat ( str1, str2 ); - str2 is concatenated at the end of str1.  As you know, each string in C is ended up with null character (‘0′).  In strcat( ) operation, null character of destination string is overwritten by source string’s first character and null character is added at the end of new destination string which is created after strcat( ) operation. Example program for strcat( ) function in C:  In this program, two strings “NIIT” and “C tutorial” are concatenated using strcat( ) function and result is displayed as “C tutorial NIIT”. #include <stdio.h>
  • 7. #include <string.h> int main( ) { char source[] = " NIIT" ; char target[ ]= " C tutorial" ; printf ( "nSource string = %s",source ) ; printf ( "nTarget string = %s",target ) ; strcat ( target, source ) ; printf ( "nTarget string afterstrcat( ) = %s", target ) ; } Output: Source string = NIIT Target string = C tutorial Target string after strcat( ) = C tutorial NIIT C – strncat() function  strncat( ) function in C language concatenates ( appends ) portion of one string at the end of another string. Syntax for strncat( ) function is given below. char * strncat( char * destination,constchar * source,size_tnum );  Example : strncat( str2,str1, 3 ); – First3 characters of str1 is concatenated atthe end of str2. strncat( str1,str2, 3 ); - First 3 characters of str2 is concatenated at the end of str1.  As you know, each string in C is ended up with null character (‘0′).  In strncat( ) operation, null character of destination string is overwritten by source string’s first character and null character is added at the end of new destination string which is created after strncat( ) operation.
  • 8. Example program for strncat( ) function in C:  In this program, first 5 characters of the string “NIIT” is concatenated at the end of the string”C tutorial” using strncat( ) function and result is displayed as “C tutorial fres”. #include <stdio.h> #include <string.h> int main( ) { char source[] = " NIIT" ; char target[ ]= "C tutorial" ; printf ( "nSource string = %s",source ) ; printf ( "nTarget string = %s",target ) ; strncat ( target, source,5 ) ; printf ( "nTarget string afterstrncat( ) = %s",target ) ; } Output: Source string = NIIT Target string = C tutorial Target string after strcat( ) = C tutorial fres C – strcpy() function  strcpy( ) function copies contents of one string into another string. Syntax for strcpy function is given below. char * strcpy ( char * destination,constchar * source );  Example: strcpy ( str1,str2) – It copies contents ofstr2 into str1. strcpy ( str2,str1) – It copies contents ofstr1 into str2.  If destination string length is less than source string, entire source string value won’t be copied into destination string.
  • 9.  For example, consider destination string length is 20 and source string length is 30. Then, only 20 characters from source string will be copied into destination string and remaining 10 characters won’t be copied and will be truncated. Example program for strcpy( ) function in C:  In this program, source string “NIIT” is copied into target string using strcpy( ) function. #include <stdio.h> #include <string.h> int main( ) { char source[] = "NIIT" ; char target[20]= "" ; printf ( "nsource string = %s",source ) ; printf ( "ntargetstring = %s",target ) ; strcpy ( target, source ) ; printf ( "ntargetstring after strcpy( ) = %s",target ) ; return 0; } Output: source string = NIIT target string = target string after strcpy( ) = NIIT