SlideShare a Scribd company logo
1 of 23
ARRAY
Array:
An array is defined as the collection of similar type of
data items stored at contiguous memory locations.
Arrays are the derived data type in C programming
language which can store the primitive type of data
such as int, char, double, float, etc.
Properties of Array:
 The array contains the following properties.
 Each element of an array is of same data type and
carries the same size, i.e., int = 4 bytes.
 Elements of the array are stored at contiguous
memory locations where the first element is stored at
the smallest memory location.
 Elements of the array can be randomly accessed
since we can calculate the address of each element
of the array with the given base address and the size
of the data element.
Declaration of C Array
We can declare an array in the c language in the
following way.
data_type array_name[array_size];
Now, let us see the example to declare the array.
int marks[5];
Here, int is the data_type, marks are the array_name,
and 5 is the array_size
Initialization of C Array
 The simplest way to initialize an array is by using the
index of each element. We can initialize each element of
the array by using the index. Consider the following
example.
1. marks[0]=80;//initialization of array
2. marks[1]=60;
3. marks[2]=70;
4. marks[3]=85;
5. marks[4]=75;
C array example
#include<stdio.h>
int main(){
int i=0;
int marks[5];//declaration of array
marks[0]=80;//initialization of array
marks[1]=60;
marks[2]=70;
marks[3]=85;
marks[4]=75;
//traversal of array
for(i=0;i<5;i++){
printf("%d n",marks[i]);
}//end of for loop
return 0;
}
Output
80
60
70
85
75
Length of an array:
#include <unistd.h>
int main()
{
int array[] = {15, 50, 34, 20, 10, 79, 100};
int n;
n = sizeof(array);
printf("Size of the given array is %dn", n/sizeof(int));
return 0;
}
Two Dimensional Array in C
 The two-dimensional array can be defined as an
array of arrays. The 2D array is organized as
matrices which can be represented as the collection
of rows and columns. However, 2D arrays are
created to implement a relational database lookalike
data structure. It provides ease of holding the bulk of
data at once which can be passed to any number of
functions wherever required.
Declaration of two dimensional Array in C:
The syntax to declare the 2D array is given below.
 data_type array_name[rows][columns];
 Consider the following example.
 int twodimen[4][3];
 Here, 4 is the number of rows, and 3 is the number
of columns.
Initialization of 2D Array in C:
int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
Two-dimensional array example in C
#include<stdio.h>
int main(){
int i=0,j=0;
int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
//traversing 2D array
for(i=0;i<4;i++){
for(j=0;j<3;j++){
printf("arr[%d] [%d] = %d n",i,j,arr[i][j]);
}//end of j
}//end of i
return 0;
}
Output
arr[0][0] = 1
arr[0][1] = 2
arr[0][2] = 3
arr[1][0] = 2
arr[1][1] = 3
arr[1][2] = 4
arr[2][0] = 3
arr[2][1] = 4
arr[2][2] = 5
arr[3][0] = 4
arr[3][1] = 5
arr[3][2] = 6
Storing elements in a matrix and printing it.
1. #include <stdio.h>
2. void main ()
3. {
4. int arr[3][3],i,j;
5. for (i=0;i<3;i++)
6. {
7. for (j=0;j<3;j++)
8. {
9. printf("Enter a[%d][%d]: ",i,j);
10. scanf("%d",&arr[i][j]);
11. }
12. }
13. printf("n printing the elements ....n");
14. for(i=0;i<3;i++)
15. {
16. printf("n");
17. for (j=0;j<3;j++)
18. {
19. printf("%dt",arr[i][j]);
20. }
21. }
22. }
Output
Enter a[0][0]: 56
Enter a[0][1]: 10
Enter a[0][2]: 30
Enter a[1][0]: 34
Enter a[1][1]: 21
Enter a[1][2]: 34
Enter a[2][0]: 45
Enter a[2][1]: 56
Enter a[2][2]: 78
printing the elements ....
56 10 30
34 21 34
45 56 78
Passing Array to Function in C
Consider the following syntax to pass an array to the
function.
 functionname(arrayname);//passing array
Methods to declare a function that receives an array as
an argument
There are 3 ways to declare the function which is intended
to receive an array as an argument.
1.First way:
 return_type function(type arrayname[])
 Declaring blank subscript notation [] is the widely used
technique.
2.Second way:
 return_type function(type arrayname[SIZE])
 Optionally, we can define size in subscript notation [].
3.Third way:
 return_type function(type *arrayname)
C language passing an array to function example
1. #include<stdio.h>
2. int minarray(int arr[],int size){
3. int min=arr[0];
4. int i=0;
5. for(i=1;i<size;i++){
6. if(min>arr[i]){
7. min=arr[i];
8. }
9. }//end of for
10. return min;
11. }//end of function
12.
13. int main(){
14. int i=0,min=0;
15. int numbers[]={4,5,7,3,8,9};//declaration of array
16.
17. min=minarray(numbers,6);//passing array with size
18. printf("minimum number is %d n",min);
19. return 0;
20. }
Output
minimum number is 3
C function to sort the array
1. #include<stdio.h>
2. void Bubble_Sort(int[]);
3. void main ()
4. {
5. int arr[10] = { 10, 9, 7, 101, 23, 44, 12, 78, 34, 23};
6. Bubble_Sort(arr);
7. }
8. void Bubble_Sort(int a[]) //array a[] points to arr.
9. {
10. int i, j,temp;
11. for(i = 0; i<10; i++)
12. {
13. for(j = i+1; j<10; j++)
14. {
15. if(a[j] < a[i])
16. {
17. temp = a[i];
18. a[i] = a[j];
19. a[j] = temp;
20. }
21. }
22. }
23. printf("Printing Sorted Element List ...n");
24. for(i = 0; i<10; i++)
25. {
26. printf("%dn",a[i]);
27. }
28. }
Output
Printing Sorted Element List ...
7
9
10
12
23
23
34
44
78
101
STRINGS
C Strings
 The string can be defined as the one-dimensional
array of characters terminated by a null ('0').
 The character array or the string is used to
manipulate text such as word or sentences. Each
character in the array occupies one byte of memory,
and the last character must always be 0.
 The termination character ('0') is important in a
string since it is the only way to identify where the
string ends.
 When we define a string as char s[10], the character
s[10] is implicitly initialized with the null in the
memory.
There are two ways to declare a string in c language.
1.By char array
2.By string literal
Let's see the example of declaring string by char
array in C language.
1. char ch[10]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '0'
};
As we know, array index starts from 0, so it will be
represented as in the figure given below.
 While declaring string, size is not mandatory. So we
can write the above code as given below:
 char ch[]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '0'};
 We can also define the string by the string literal in
C language. For example:
 char ch[]="javatpoint";
 In such case, '0' will be appended at the end of the
string by the compiler.
Difference between char array and string literal:
There are two main differences between char array
literal and.
We need to add the null character '0' at the end of
the array by ourself whereas, it is appended
internally by the compiler in the case of the character
array.
The string literal cannot be reassigned to another set
Example program:
#include<stdio.h>
#include <string.h>
int main(){
char ch[11]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '0'};
char ch2[11]="javatpoint";
printf("Char Array Value is: %sn", ch);
printf("String Literal Value is: %sn", ch2);
return 0;
}
Output:
Char Array Value is: javatpoint
String Literal Value is: javatpoint
Traversing String:
Hence, there are two ways to traverse a string.
1. By using the length of string
2. By using the null character.
Using the length of string:
Let's see an example of counting the number of vowels in a string.
#include<stdio.h>
void main ()
{
char s[11] = "javatpoint";
int i = 0;
int count = 0;
while(i<11)
{
if(s[i]=='a' || s[i] == 'e' || s[i] == 'i' || s[i] == 'u' || s[i] == 'o')
{
count ++;
}
i++;
}
printf("The number of vowels %d",count);
}
Output
The number of vowels 4
Using the null character:
Let's see the same example of counting the number of vowels by using the null
character.
#include<stdio.h>
void main ()
{
char s[11] = "javatpoint";
int i = 0;
int count = 0;
while(s[i] != NULL)
{
if(s[i]=='a' || s[i] == 'e' || s[i] == 'i' || s[i] == 'u' || s[i] == 'o')
{
count ++;
}
i++;
}
printf("The number of vowels %d",count);
}
Output:
The number of vowels 4
C gets() and puts() functions:
 The gets() and puts() are declared in the header file stdio.h. Both the
functions are involved in the input/output operations of the strings.
C gets() function:
 The gets() function enables the user to enter some characters followed by
the enter key. All the characters entered by the user get stored in a character
array. The null character is added to the array to make it a string. The gets()
allows the user to enter the space-separated strings. It returns the string
entered by the user.
Declaration
 char[] gets(char[]);
Reading string using gets():
#include<stdio.h>
void main ()
{
char s[30];
printf("Enter the string? ");
gets(s);
printf("You entered %s",s);
}
Output:
Enter the string? javatpoint is the best
You entered javatpoint is the best
C puts() function:
 The puts() function is very much similar to printf() function. The puts() function is used to
print the string on the console which is previously read by using gets() or scanf() function.
The puts() function returns an integer value representing the number of characters being
printed on the console. Since, it prints an additional newline character with the string,
which moves the cursor to the new line on the console, the integer value returned by
puts() will always be equal to the number of characters present in the string plus 1.
Declaration:
 int puts(char[])
Let's see an example to read a string using gets() and print it on the console using puts().
#include<stdio.h>
#include <string.h>
int main(){
char name[50];
printf("Enter your name: ");
gets(name); //reads string from user
printf("Your name is: ");
puts(name); //displays string
return 0;
}
Output:
Enter your name: Sonoo Jaiswal
C String Functions:
 There are many important string functions defined in
"string.h" library.
No. Function Description
1) strlen(string_name) returns the length of string name.
2) strcpy(destination, source) copies the contents of source string to destination
string.
3) strcat(first_string,
second_string)
concats or joins first string with second string. The
result of the string is stored in first string.
4) strcmp(first_string,
second_string)
compares the first string with second string. If both
strings are same, it returns 0.
5) strrev(string) returns reverse string.
6) strlwr(string) returns string characters in lowercase.
7) strupr(string) returns string characters in uppercase.

More Related Content

What's hot (20)

Constants in C Programming
Constants in C ProgrammingConstants in C Programming
Constants in C Programming
 
C function
C functionC function
C function
 
Function in C program
Function in C programFunction in C program
Function in C program
 
Structure & union
Structure & unionStructure & union
Structure & union
 
Function overloading(c++)
Function overloading(c++)Function overloading(c++)
Function overloading(c++)
 
C functions
C functionsC functions
C functions
 
Unit 5.ppt
Unit 5.pptUnit 5.ppt
Unit 5.ppt
 
Functions in C
Functions in CFunctions in C
Functions in C
 
String in c programming
String in c programmingString in c programming
String in c programming
 
C keywords and identifiers
C keywords and identifiersC keywords and identifiers
C keywords and identifiers
 
Functions in C
Functions in CFunctions in C
Functions in C
 
C Programming: Control Structure
C Programming: Control StructureC Programming: Control Structure
C Programming: Control Structure
 
Control statements in c
Control statements in cControl statements in c
Control statements in c
 
Structures
StructuresStructures
Structures
 
What is identifier c programming
What is identifier c programmingWhat is identifier c programming
What is identifier c programming
 
C introduction by thooyavan
C introduction by  thooyavanC introduction by  thooyavan
C introduction by thooyavan
 
Types of Statements in Python Programming Language
Types of Statements in Python Programming LanguageTypes of Statements in Python Programming Language
Types of Statements in Python Programming Language
 
Presentation on c structures
Presentation on c   structures Presentation on c   structures
Presentation on c structures
 
Function overloading ppt
Function overloading pptFunction overloading ppt
Function overloading ppt
 
Handling of character strings C programming
Handling of character strings C programmingHandling of character strings C programming
Handling of character strings C programming
 

Similar to C Programming Unit-3

Similar to C Programming Unit-3 (20)

Arrays
ArraysArrays
Arrays
 
Module 4- Arrays and Strings
Module 4- Arrays and StringsModule 4- Arrays and Strings
Module 4- Arrays and Strings
 
Unit ii data structure-converted
Unit  ii data structure-convertedUnit  ii data structure-converted
Unit ii data structure-converted
 
Arrays and strings in c++
Arrays and strings in c++Arrays and strings in c++
Arrays and strings in c++
 
Functions, Strings ,Storage classes in C
 Functions, Strings ,Storage classes in C Functions, Strings ,Storage classes in C
Functions, Strings ,Storage classes in C
 
Array &strings
Array &stringsArray &strings
Array &strings
 
Unit 2
Unit 2Unit 2
Unit 2
 
Unitii classnotes
Unitii classnotesUnitii classnotes
Unitii classnotes
 
Lecture 15_Strings and Dynamic Memory Allocation.pptx
Lecture 15_Strings and  Dynamic Memory Allocation.pptxLecture 15_Strings and  Dynamic Memory Allocation.pptx
Lecture 15_Strings and Dynamic Memory Allocation.pptx
 
Introduction to Arrays in C
Introduction to Arrays in CIntroduction to Arrays in C
Introduction to Arrays in C
 
3.ArraysandPointers.pptx
3.ArraysandPointers.pptx3.ArraysandPointers.pptx
3.ArraysandPointers.pptx
 
Arrays-Computer programming
Arrays-Computer programmingArrays-Computer programming
Arrays-Computer programming
 
Arrays and library functions
Arrays and library functionsArrays and library functions
Arrays and library functions
 
Array.pptx
Array.pptxArray.pptx
Array.pptx
 
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
 
String notes
String notesString notes
String notes
 
C++ Programming Homework Help
C++ Programming Homework HelpC++ Programming Homework Help
C++ Programming Homework Help
 
ARRAYS
ARRAYSARRAYS
ARRAYS
 
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
 
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
 

More from Vikram Nandini

IoT: From Copper strip to Gold Bar
IoT: From Copper strip to Gold BarIoT: From Copper strip to Gold Bar
IoT: From Copper strip to Gold BarVikram Nandini
 
Linux File Trees and Commands
Linux File Trees and CommandsLinux File Trees and Commands
Linux File Trees and CommandsVikram Nandini
 
Introduction to Linux & Basic Commands
Introduction to Linux & Basic CommandsIntroduction to Linux & Basic Commands
Introduction to Linux & Basic CommandsVikram Nandini
 
Manufacturing - II Part
Manufacturing - II PartManufacturing - II Part
Manufacturing - II PartVikram Nandini
 
Prototyping Online Components
Prototyping Online ComponentsPrototyping Online Components
Prototyping Online ComponentsVikram Nandini
 
Artificial Neural Networks
Artificial Neural NetworksArtificial Neural Networks
Artificial Neural NetworksVikram Nandini
 
Design Principles for Connected Devices
Design Principles for Connected DevicesDesign Principles for Connected Devices
Design Principles for Connected DevicesVikram Nandini
 
Communication in the IoT
Communication in the IoTCommunication in the IoT
Communication in the IoTVikram Nandini
 
Introduction to Cyber Security
Introduction to Cyber SecurityIntroduction to Cyber Security
Introduction to Cyber SecurityVikram Nandini
 
cloud computing UNIT-2.pdf
cloud computing UNIT-2.pdfcloud computing UNIT-2.pdf
cloud computing UNIT-2.pdfVikram Nandini
 
Introduction to Web Technologies
Introduction to Web TechnologiesIntroduction to Web Technologies
Introduction to Web TechnologiesVikram Nandini
 
Cascading Style Sheets
Cascading Style SheetsCascading Style Sheets
Cascading Style SheetsVikram Nandini
 

More from Vikram Nandini (20)

IoT: From Copper strip to Gold Bar
IoT: From Copper strip to Gold BarIoT: From Copper strip to Gold Bar
IoT: From Copper strip to Gold Bar
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
 
Linux File Trees and Commands
Linux File Trees and CommandsLinux File Trees and Commands
Linux File Trees and Commands
 
Introduction to Linux & Basic Commands
Introduction to Linux & Basic CommandsIntroduction to Linux & Basic Commands
Introduction to Linux & Basic Commands
 
INTRODUCTION to OOAD
INTRODUCTION to OOADINTRODUCTION to OOAD
INTRODUCTION to OOAD
 
Ethics
EthicsEthics
Ethics
 
Manufacturing - II Part
Manufacturing - II PartManufacturing - II Part
Manufacturing - II Part
 
Manufacturing
ManufacturingManufacturing
Manufacturing
 
Business Models
Business ModelsBusiness Models
Business Models
 
Prototyping Online Components
Prototyping Online ComponentsPrototyping Online Components
Prototyping Online Components
 
Artificial Neural Networks
Artificial Neural NetworksArtificial Neural Networks
Artificial Neural Networks
 
IoT-Prototyping
IoT-PrototypingIoT-Prototyping
IoT-Prototyping
 
Design Principles for Connected Devices
Design Principles for Connected DevicesDesign Principles for Connected Devices
Design Principles for Connected Devices
 
Introduction to IoT
Introduction to IoTIntroduction to IoT
Introduction to IoT
 
Embedded decices
Embedded decicesEmbedded decices
Embedded decices
 
Communication in the IoT
Communication in the IoTCommunication in the IoT
Communication in the IoT
 
Introduction to Cyber Security
Introduction to Cyber SecurityIntroduction to Cyber Security
Introduction to Cyber Security
 
cloud computing UNIT-2.pdf
cloud computing UNIT-2.pdfcloud computing UNIT-2.pdf
cloud computing UNIT-2.pdf
 
Introduction to Web Technologies
Introduction to Web TechnologiesIntroduction to Web Technologies
Introduction to Web Technologies
 
Cascading Style Sheets
Cascading Style SheetsCascading Style Sheets
Cascading Style Sheets
 

Recently uploaded

How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfakmcokerachita
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application ) Sakshi Ghasle
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 

Recently uploaded (20)

How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdf
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application )
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 

C Programming Unit-3

  • 2. Array: An array is defined as the collection of similar type of data items stored at contiguous memory locations. Arrays are the derived data type in C programming language which can store the primitive type of data such as int, char, double, float, etc. Properties of Array:  The array contains the following properties.  Each element of an array is of same data type and carries the same size, i.e., int = 4 bytes.  Elements of the array are stored at contiguous memory locations where the first element is stored at the smallest memory location.  Elements of the array can be randomly accessed since we can calculate the address of each element of the array with the given base address and the size of the data element.
  • 3. Declaration of C Array We can declare an array in the c language in the following way. data_type array_name[array_size]; Now, let us see the example to declare the array. int marks[5]; Here, int is the data_type, marks are the array_name, and 5 is the array_size
  • 4. Initialization of C Array  The simplest way to initialize an array is by using the index of each element. We can initialize each element of the array by using the index. Consider the following example. 1. marks[0]=80;//initialization of array 2. marks[1]=60; 3. marks[2]=70; 4. marks[3]=85; 5. marks[4]=75;
  • 5. C array example #include<stdio.h> int main(){ int i=0; int marks[5];//declaration of array marks[0]=80;//initialization of array marks[1]=60; marks[2]=70; marks[3]=85; marks[4]=75; //traversal of array for(i=0;i<5;i++){ printf("%d n",marks[i]); }//end of for loop return 0; } Output 80 60 70 85 75
  • 6. Length of an array: #include <unistd.h> int main() { int array[] = {15, 50, 34, 20, 10, 79, 100}; int n; n = sizeof(array); printf("Size of the given array is %dn", n/sizeof(int)); return 0; }
  • 7. Two Dimensional Array in C  The two-dimensional array can be defined as an array of arrays. The 2D array is organized as matrices which can be represented as the collection of rows and columns. However, 2D arrays are created to implement a relational database lookalike data structure. It provides ease of holding the bulk of data at once which can be passed to any number of functions wherever required.
  • 8. Declaration of two dimensional Array in C: The syntax to declare the 2D array is given below.  data_type array_name[rows][columns];  Consider the following example.  int twodimen[4][3];  Here, 4 is the number of rows, and 3 is the number of columns. Initialization of 2D Array in C: int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
  • 9. Two-dimensional array example in C #include<stdio.h> int main(){ int i=0,j=0; int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}}; //traversing 2D array for(i=0;i<4;i++){ for(j=0;j<3;j++){ printf("arr[%d] [%d] = %d n",i,j,arr[i][j]); }//end of j }//end of i return 0; } Output arr[0][0] = 1 arr[0][1] = 2 arr[0][2] = 3 arr[1][0] = 2 arr[1][1] = 3 arr[1][2] = 4 arr[2][0] = 3 arr[2][1] = 4 arr[2][2] = 5 arr[3][0] = 4 arr[3][1] = 5 arr[3][2] = 6
  • 10. Storing elements in a matrix and printing it. 1. #include <stdio.h> 2. void main () 3. { 4. int arr[3][3],i,j; 5. for (i=0;i<3;i++) 6. { 7. for (j=0;j<3;j++) 8. { 9. printf("Enter a[%d][%d]: ",i,j); 10. scanf("%d",&arr[i][j]); 11. } 12. } 13. printf("n printing the elements ....n"); 14. for(i=0;i<3;i++) 15. { 16. printf("n"); 17. for (j=0;j<3;j++) 18. { 19. printf("%dt",arr[i][j]); 20. } 21. } 22. } Output Enter a[0][0]: 56 Enter a[0][1]: 10 Enter a[0][2]: 30 Enter a[1][0]: 34 Enter a[1][1]: 21 Enter a[1][2]: 34 Enter a[2][0]: 45 Enter a[2][1]: 56 Enter a[2][2]: 78 printing the elements .... 56 10 30 34 21 34 45 56 78
  • 11. Passing Array to Function in C Consider the following syntax to pass an array to the function.  functionname(arrayname);//passing array Methods to declare a function that receives an array as an argument There are 3 ways to declare the function which is intended to receive an array as an argument. 1.First way:  return_type function(type arrayname[])  Declaring blank subscript notation [] is the widely used technique. 2.Second way:  return_type function(type arrayname[SIZE])  Optionally, we can define size in subscript notation []. 3.Third way:  return_type function(type *arrayname)
  • 12. C language passing an array to function example 1. #include<stdio.h> 2. int minarray(int arr[],int size){ 3. int min=arr[0]; 4. int i=0; 5. for(i=1;i<size;i++){ 6. if(min>arr[i]){ 7. min=arr[i]; 8. } 9. }//end of for 10. return min; 11. }//end of function 12. 13. int main(){ 14. int i=0,min=0; 15. int numbers[]={4,5,7,3,8,9};//declaration of array 16. 17. min=minarray(numbers,6);//passing array with size 18. printf("minimum number is %d n",min); 19. return 0; 20. } Output minimum number is 3
  • 13. C function to sort the array 1. #include<stdio.h> 2. void Bubble_Sort(int[]); 3. void main () 4. { 5. int arr[10] = { 10, 9, 7, 101, 23, 44, 12, 78, 34, 23}; 6. Bubble_Sort(arr); 7. } 8. void Bubble_Sort(int a[]) //array a[] points to arr. 9. { 10. int i, j,temp; 11. for(i = 0; i<10; i++) 12. { 13. for(j = i+1; j<10; j++) 14. { 15. if(a[j] < a[i]) 16. { 17. temp = a[i]; 18. a[i] = a[j]; 19. a[j] = temp; 20. } 21. } 22. } 23. printf("Printing Sorted Element List ...n"); 24. for(i = 0; i<10; i++) 25. { 26. printf("%dn",a[i]); 27. } 28. } Output Printing Sorted Element List ... 7 9 10 12 23 23 34 44 78 101
  • 15. C Strings  The string can be defined as the one-dimensional array of characters terminated by a null ('0').  The character array or the string is used to manipulate text such as word or sentences. Each character in the array occupies one byte of memory, and the last character must always be 0.  The termination character ('0') is important in a string since it is the only way to identify where the string ends.  When we define a string as char s[10], the character s[10] is implicitly initialized with the null in the memory.
  • 16. There are two ways to declare a string in c language. 1.By char array 2.By string literal Let's see the example of declaring string by char array in C language. 1. char ch[10]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '0' }; As we know, array index starts from 0, so it will be represented as in the figure given below.
  • 17.  While declaring string, size is not mandatory. So we can write the above code as given below:  char ch[]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '0'};  We can also define the string by the string literal in C language. For example:  char ch[]="javatpoint";  In such case, '0' will be appended at the end of the string by the compiler. Difference between char array and string literal: There are two main differences between char array literal and. We need to add the null character '0' at the end of the array by ourself whereas, it is appended internally by the compiler in the case of the character array. The string literal cannot be reassigned to another set
  • 18. Example program: #include<stdio.h> #include <string.h> int main(){ char ch[11]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '0'}; char ch2[11]="javatpoint"; printf("Char Array Value is: %sn", ch); printf("String Literal Value is: %sn", ch2); return 0; } Output: Char Array Value is: javatpoint String Literal Value is: javatpoint
  • 19. Traversing String: Hence, there are two ways to traverse a string. 1. By using the length of string 2. By using the null character. Using the length of string: Let's see an example of counting the number of vowels in a string. #include<stdio.h> void main () { char s[11] = "javatpoint"; int i = 0; int count = 0; while(i<11) { if(s[i]=='a' || s[i] == 'e' || s[i] == 'i' || s[i] == 'u' || s[i] == 'o') { count ++; } i++; } printf("The number of vowels %d",count); } Output The number of vowels 4
  • 20. Using the null character: Let's see the same example of counting the number of vowels by using the null character. #include<stdio.h> void main () { char s[11] = "javatpoint"; int i = 0; int count = 0; while(s[i] != NULL) { if(s[i]=='a' || s[i] == 'e' || s[i] == 'i' || s[i] == 'u' || s[i] == 'o') { count ++; } i++; } printf("The number of vowels %d",count); } Output: The number of vowels 4
  • 21. C gets() and puts() functions:  The gets() and puts() are declared in the header file stdio.h. Both the functions are involved in the input/output operations of the strings. C gets() function:  The gets() function enables the user to enter some characters followed by the enter key. All the characters entered by the user get stored in a character array. The null character is added to the array to make it a string. The gets() allows the user to enter the space-separated strings. It returns the string entered by the user. Declaration  char[] gets(char[]); Reading string using gets(): #include<stdio.h> void main () { char s[30]; printf("Enter the string? "); gets(s); printf("You entered %s",s); } Output: Enter the string? javatpoint is the best You entered javatpoint is the best
  • 22. C puts() function:  The puts() function is very much similar to printf() function. The puts() function is used to print the string on the console which is previously read by using gets() or scanf() function. The puts() function returns an integer value representing the number of characters being printed on the console. Since, it prints an additional newline character with the string, which moves the cursor to the new line on the console, the integer value returned by puts() will always be equal to the number of characters present in the string plus 1. Declaration:  int puts(char[]) Let's see an example to read a string using gets() and print it on the console using puts(). #include<stdio.h> #include <string.h> int main(){ char name[50]; printf("Enter your name: "); gets(name); //reads string from user printf("Your name is: "); puts(name); //displays string return 0; } Output: Enter your name: Sonoo Jaiswal
  • 23. C String Functions:  There are many important string functions defined in "string.h" library. No. Function Description 1) strlen(string_name) returns the length of string name. 2) strcpy(destination, source) copies the contents of source string to destination string. 3) strcat(first_string, second_string) concats or joins first string with second string. The result of the string is stored in first string. 4) strcmp(first_string, second_string) compares the first string with second string. If both strings are same, it returns 0. 5) strrev(string) returns reverse string. 6) strlwr(string) returns string characters in lowercase. 7) strupr(string) returns string characters in uppercase.