Module 2 Arrays and strings – example programs.

Slides:



Advertisements
Similar presentations
1 Chapter 10 Strings and Pointers. 2 Introduction  String Constant  Example: printf(“Hello”); “Hello” : a string constant oA string constant is a series.
Advertisements

What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
CMPE-013/L: “C” Programming Gabriel Hugh Elkaim – Spring 2013 CMPE-013/L Arrays and Strings Gabriel Hugh Elkaim Spring 2013.
Chapter 9 Character Strings 9.1 Character String Constants A character string constant is a sequence of characters enclosed in double quotation mark. Examples.
STRING Dong-Chul Kim BioMeCIS UTA 10/7/
Arrays  Array is a collection of same type elements under the same variable identifier referenced by index number.  Arrays are widely used within programming.
מערכים (arrays) 02 דצמבר דצמבר דצמבר 1502 דצמבר דצמבר דצמבר 1502 דצמבר דצמבר דצמבר 15 1 Department of Computer Science-BGU.
Representing Strings and String I/O. Introduction A string is a sequence of characters and is treated as a single data item. A string constant, also termed.
Structured Programming Approach Module VIII - Additional C Data Types Arrays Prof: Muhammed Salman Shamsi.
Chapter 8 Arrays. A First Book of ANSI C, Fourth Edition2 Introduction Atomic variable: variable whose value cannot be further subdivided into a built-in.
Computer Programming for Engineers
In C programming, one of the frequently arising problem is to handle similar types of data. For example: If the user want to store marks of 100 students.
1 Arrays and Pointers The name of an array is a pointer constant to the first element. Because the array’s name is a pointer constant, its value cannot.
Beginning C for Engineers Fall 2005 Arrays, 2-D arrays, character strings Bettina Schimanski Lecture 5: Section 2 (9/28/05) Section 4 (9/29/05)
KUKUM-06/07 EKT120: Computer Programming 1 Week 6 Arrays-Part 1.
Arrays in C. What is Array? The variables we have used so far can store a single value. Array is a new type of variable capable of storing many values.
MULTI-DIMENSION ARRAY STRING Computer Programming Asst. Prof. Dr. Choopan Rattanapoka and Asst. Prof. Dr. Suphot Chunwiphat.
Strings C supports strings using one-dimensional character arrays. A string is defined as a null-terminated character array. In C, a null is 0. You must.
1 Chapter 8 – Character Arrays and Strings Outline 8.1Introduction 8.2Declaring and Initializing String 8.3Input/output of strings 8.4String-handling Functions.
Chapter 2 Array and String. Array Definition of Array : An array is a sequence or collection of the related data items that share a common name. Purpose.
Introduction to Programming Using C Arrays. 2 Contents Arrays Subscripting.
מערכים (arrays) 02 אוקטובר אוקטובר אוקטובר 1602 אוקטובר אוקטובר אוקטובר 1602 אוקטובר אוקטובר אוקטובר 16 Department.
1-d Arrays.
Computer Organization and Design Pointers, Arrays and Strings in C
C ARRAYS.
Chapter 8 Arrays, Strings and Pointers
Course Contents KIIT UNIVERSITY Sr # Major and Detailed Coverage Area
(Numerical Arrays of Multiple Dimensions)
INC 161 , CPE 100 Computer Programming
Pointers & Arrays 1-d arrays & pointers 2-d arrays & pointers.
Computer Science 210 Computer Organization
Computer Programming BCT 1113
Lecture 7 Arrays 1. Concept of arrays Array and pointers
CHP-2 ARRAYS.
C Scope Rules and Arrays
Lecture 8 String 1. Concept of strings String and pointers
C Programming Tutorial – Part I
Quiz 11/15/16 – C functions, arrays and strings
Lecture-5 Arrays.
Array 9/8/2018.
BY GAWARE S.R. COMPUTER SCI. DEPARTMENT
Arrays in C.
Programming Languages and Paradigms
Computer Science 210 Computer Organization
Arrays C provides the option to the user to combine similar data types into a single entity It followed contiguous.
Programming and Data Structure
Lecture 9 : Array Acknowledgment : Lecture notes from Ohio Supercomputing Center.
CS111 Computer Programming
Arrays, For loop While loop Do while loop
INC 161 , CPE 100 Computer Programming
EKT150 : Computer Programming
Strings A collection of characters taken as a set:
Declaration, assignment & accessing
Review of Arrays and Pointers
Chapter 7 Arrays PROGRAMMING IN ANSI C.
Outline Defining and using Pointers Operations on pointers
Chapter 2 Array and String Visit to more Learning Resources.
Chapter 8 Character Arrays and Strings
Multidimensional array
Dr Tripty Singh Arrays.
Arrays C provides the option to the user to combine similar data types into a single entity It followed contiguous.
Strings in C Array of characters is called a string.
Strings #include <stdio.h>
Programming Languages and Paradigms
ICS103 Programming in C Lecture 12: Arrays I
Dr. Khizar Hayat Associate Prof. of Computer Science
Structures, Unions, and Enumerations
Getting Started With Coding
Introduction to Problem Solving and Programming
Visit for more Learning Resources
Presentation transcript:

Module 2 Arrays and strings – example programs. Two dimensional arrays – matrix operations. Structure, union and enumerated data types.

Arrays An array is a collection of data that holds fixed number of values of same type. can store group of data of same data type in an array. Array might be belonging to any of the data types Array size must be a constant value. Contiguous (adjacent) memory locations are used to store array elements in memory. Example for C Arrays: int a[10];       // integer array char b[10];    // character array   i.e. string

Types of C arrays: There are 2 types of C arrays. One dimensional array Multi dimensional array Two dimensional array Three dimensional array Four dimensional array etc…

declare an array in C data_type array_name[array_size]; For example, float mark[5]; Here, we declared an array, mark, of floating-point type and size 5. Meaning, it can hold 5 floating-point values.

access array elements can access elements of an array by indices. float mark[5]; The first element is mark[0], second element is mark[1] and so on.

Few key notes: Arrays have 0 as the first index not 1. In this example, mark[0] If the size of an array is n, to access the last element, (n-1) index is used. In this example, mark[4] Suppose the starting address of mark[0] is 2120d. Then, the next address, a[1], will be 2124d, address of a[2] will be 2128d and so on. It's because the size of a float is 4 bytes.

initialize an array It's possible to initialize an array during declaration. int mark[5] = {19, 10, 8, 17, 9}; int mark[] = {19, 10, 8, 17, 9};

insert and print array elements int mark[5] = {19, 10, 8, 17, 9} mark[3] = 9; ​scanf("%d", &mark[2]); // print first element of an array printf("%d", mark[0]); // print ith element of an array printf("%d", mark[i-1]);

find the average of n numbers using arrays #include <stdio.h> int main() { int marks[10], i, n, sum = 0, average; printf("Enter n: "); scanf("%d", &n); for(i=0; i<n; ++i) printf("Enter number%d: ",i+1); scanf("%d", &marks[i]); sum += marks[i]; } average = sum/n; printf("Average marks = %d", average); return 0;

Deletion of an element from an array Searching an element in an array

C Program to Find the Largest Number in an Array #include <stdio.h> int main() { int array[50], size, i, largest; printf("\n Enter the size of the array: "); scanf("%d", &size); printf("\n Enter %d elements of the array: ", size); for (i = 0; i < size; i++) { scanf("%d", &array[i]);} largest = array[0]; for (i = 1; i < size; i++) { if (largest < array[i]) largest = array[i]; } printf("\n largest element present in the given array is : %d", largest); return 0;

Two Dimension Matrix 2D arrays are generally known as matrix. Syntax : type arrayName [ 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 considered as a table which will have x number of rows and y number of columns. A two-dimensional array a, which contains three rows and four columns can be shown as follows −

Initializing Two-Dimensional Arrays Multidimensional arrays may be initialized by specifying bracketed values for each row. 1. 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 */ }; 2. int a[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11};

Accessing Two-Dimensional Array Elements An element in a two-dimensional array is accessed by using the subscripts, i.e., row index and column index of the array. int val = a[2][3];

#include<stdio.h> int main() { int i, j; int a[3][2] = { { 1, 4 }, { 5, 2 }, { 6, 5 }}; for (i = 0; i < 3; i++) { for (j = 0; j < 2; j++) { printf("%d ", a[i][j]); } printf("\n"); return 0;

2. Uninitialized elements will get default 0 value. #include <stdio.h> int main() { int i, j; int a[3][2] = { { 1 }, { 5, 2 }, { 6 }}; for (i = 0; i < 3; i++) { for (j = 0; j < 2; j++) { printf("%d ", a[i][j]); } printf("\n"); return 0;

Programs Matrix Addition Matrix Subtraction Matrix Multiplication Matrix Transpose

String array of characters ended with null character (‘\0’).  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: 1. char string[20] = {‘f’, ’r’, ‘e’, ‘s’, ‘h’, ‘2’, ‘r’, ‘e’, ‘f’, ’r’, ‘e’, ‘s’, ‘h’, ‘\0’}; 2. char string[20] = “fresh2refresh”; 3. char string []    = “fresh2refresh”;

char greeting[] = "Hello";

Reading Strings from user use the scanf() function to read a string the scanf() function only takes the first entered word. The function terminates when it encounters a white space (or just space). #include <stdio.h> int main() { char name[20]; printf("Enter name: "); scanf("%s", name); printf("Your name is %s.", name); return 0; } Output Enter name: Dennis Ritchie Your name is Dennis.

Reading a line of text Use getchar() to read a line of text #include <stdio.h> int main() { char name[30], ch; int i = 0; printf("Enter name: "); while(ch != '\n') // terminates if user hit enter ch = getchar(); name[i] = ch; i++; } name[i] = '\0'; // inserting null character at end printf("Name: %s", name); return 0;

to read line of text using gets() and puts() #include <stdio.h> int main() { char name[30]; printf("Enter name: "); gets(name); //Function to read string from user. printf("Name: "); puts(name); //Function to display string. return 0; }

Example #include <stdio.h> int main () {   int main () {    char string[20] = “welcome";    printf("The string is : %s \n", string );    return 0; }

Function & Purpose strcpy(s1, s2); strcat(s1, s2); strlen(s1); Copies string s2 into string s1. strcat(s1, s2); Concatenates string s2 onto the end of string s1. strlen(s1); Returns the length of string s1. strcmp(s1, s2); Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if s1>s2.

Strcmp() example #include <stdio.h> #include <string.h> int main( ) { char str1[ ] = "fresh" ; char str2[ ] = "refresh" ; int i, j, k ; i = strcmp ( str1, "fresh" ) ; j = strcmp ( str1, str2 ) ; k = strcmp ( str1, "f" ) ; printf ( "\n%d %d %d", i, j, k ) ; return 0; }

#include<stdio.h> #include<string.h> int main() { strrev() strrev( ) function reverses a given string in C language. #include<stdio.h> #include<string.h>   int main() {    char name[30] = "Hello";     printf("String before strrev( ) : %s\n",name); printf("String after strrev( )  : %s",strrev(name));    return 0; }

Structure C Structure is a collection of different data types which are grouped together each element in a C structure is called member. To access structure members in C, structure variable should be declared. Many structure variables can be declared for same structure and memory will be allocated for each separately. User defined data type used to represent a record

Defining a Structure struct [structure tag] { member definition; ... } [one or more structure variables];

Example Struct student { char name[50]; int rollno; float mark1,mark2,total; }st;

Accessing Structure Members use the member access operator (.). The member access operator is coded as a period between the structure variable name and the structure member that wish to access Example st.name=“Arun” st.rollno=15; st.mark1=45.2; st.mark1=47.2;

ANOTHER WAY OF DECLARING C STRUCTURE #include<stdio.h> #include<string.h> Struct student { char name[50]; int rollno; float mark1,mark2,total; } main() struct student st; strcpy(st.name,”Arun”); st.rollno=23; …. …

#include <stdio. h> #include <string #include <stdio.h> #include <string.h> struct student { int id; char name[20]; float percentage; } record; main() record.id=1; strcpy(record.name, "Raju"); record.percentage = 86.5; printf(" Id is: %d \n", record.id); printf(" Name is: %s \n", record.name); printf(" Percentage is: %f \n", record.percentage); }

Difference between array & structure Structures 1. An array is a collection of related data elements of same type. 1. Structure can have elements of different  types 2. An array is a derived data type 2. A structure is a programmer-defined data type 3. Any array behaves like a built-in data types. All we have to do is to declare an array variable and use it. 3. But in the case of structure, first we have to design and declare a data structure before the variable of that type are declared and used. 4. Array allocates static memory and uses index / subscript for accessing elements of the array. 4. Structures allocate dynamic memory and uses (.) operator for accessing the member of a structure. 5. Array is a pointer to the first element of it 5. Structure is not a pointer 6. Element access takes relatively less time. 6. Property access takes relatively large time.

Union A union is a special data type available in C that allows to store different data types in the same memory location Union and structure in C  are same in concepts, except allocating memory for their members. Structure allocates storage space for all its members separately. Whereas, Union allocates one common storage space for all its members

can access only one member of union at a time can access only one member of union at a time. We can’t access all member values at the same time in union. But, structure can access all member values at the same time. This is because, Union allocates one common storage space for all its members. Where as Structure allocates storage space for all its members separately.

DIFFERENCE BETWEEN STRUCTURE AND UNION IN C: C Structure C Union Structure allocates storage space for all its members separately. Union allocates one common storage space for all its members. Union finds that which of its member needs high storage space over other members and allocates that much space Structure occupies higher memory space. Union occupies lower memory space over structure. We can access all members of structure at a time. We can access only one member of union at a time. Structure example: struct student { int mark; char name[6]; double average; }; Union example: union student { int mark; char name[6]; double average; };

Defining a Union union [union tag] { member definition; ... } [one or more union variables];

Example union Data { int i; float f; char str[20]; } data;

Accessing Union Members To access any member of a union, we use the member access operator (.). The member access operator is coded as a period between the union variable name and the union member. Example data.i=10;

#include <stdio. h> #include <string #include <stdio.h> #include <string.h> union Data { int i; float f; char str[20]; }; main( ) { union Data data; data.i = 10; printf( "data.i : %d\n", data.i); data.f = 220.5; printf( "data.f : %f\n", data.f); strcpy( data.str, "C Programming"); printf( "data.str : %s\n", data.str); }