PDS Class Test 2. Room Sections No of students

Similar documents
CS11001/CS11002 Programming and Data Structures (PDS) (Theory: 3-0-0)

Two Dimensional Arrays

Arrays. CS10001: Programming & Data Structures. Pallab Dasgupta Dept. of Computer Sc. & Engg., Indian Institute of Technology Kharagpur

Arrays. CS10001: Programming & Data Structures. Pallab Dasgupta Dept. of Computer Sc. & Engg., Indian Institute of Technology Kharagpur

Pointers Part 1. Introduction

Computer Programming. C Array is a collection of data belongings to the same data type. data_type array_name[array_size];

B.V. Patel Institute of Business Management, Computer & Information Technology, Uka Tarsadia University

Pointers (part 1) What are pointers? EECS We have seen pointers before. scanf( %f, &inches );! 25 September 2017

Arrays and Pointers. CSE 2031 Fall November 11, 2013

Pointers. Introduction

Arrays and Pointers. Arrays. Arrays: Example. Arrays: Definition and Access. Arrays Stored in Memory. Initialization. EECS 2031 Fall 2014.

Arrays and Pointers (part 1)

Write a C program using arrays and structure

C BOOTCAMP DAY 2. CS3600, Northeastern University. Alan Mislove. Slides adapted from Anandha Gopalan s CS132 course at Univ.

mith College Computer Science CSC270 Spring 2016 Circuits and Systems Lecture Notes, Week 11 Dominique Thiébaut

ARRAYS(II Unit Part II)

Other C materials before pointer Common library functions [Appendix of K&R] 2D array, string manipulations. <stdlib.

Arrays and Pointers (part 1)

ONE DIMENSIONAL ARRAYS

Multiple Choice Questions ( 1 mark)

M4.1-R3: PROGRAMMING AND PROBLEM SOLVING THROUGH C LANGUAGE

UNIT 2 ARRAYS 2.0 INTRODUCTION. Structure. Page Nos.

First of all, it is a variable, just like other variables you studied

Government Polytechnic Muzaffarpur.

Character Strings. String-copy Example

Arrays. An array is a collection of several elements of the same type. An array variable is declared as array name[size]

Aryan College. Fundamental of C Programming. Unit I: Q1. What will be the value of the following expression? (2017) A + 9

Introduction to string

Content. In this chapter, you will learn:

UNIT-I Fundamental Notations

Why arrays? To group distinct variables of the same type under a single name.

Language comparison. C has pointers. Java has references. C++ has pointers and references

Questions Bank. 14) State any four advantages of using flow-chart

Introduction to Scientific Computing and Problem Solving

C-LANGUAGE CURRICULAM

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

Lesson 7. Reading and Writing a.k.a. Input and Output

Subject: PROBLEM SOLVING THROUGH C Time: 3 Hours Max. Marks: 100

C: Pointers, Arrays, and strings. Department of Computer Science College of Engineering Boise State University. August 25, /36

Chapter 8 Character Arrays and Strings

Computer Programming Unit 3

CSC 2400: Computer Systems. Arrays and Strings in C

PRINCIPLES OF OPERATING SYSTEMS

UNIT 6. STRUCTURED DATA TYPES PART 1: ARRAYS

Programming Language B

Output of sample program: Size of a short is 2 Size of a int is 4 Size of a double is 8

Outline. Computer Memory Structure Addressing Concept Introduction to Pointer Pointer Manipulation Summary

Computers Programming Course 11. Iulian Năstac

Computers Programming Course 10. Iulian Năstac

20 Dynamic allocation of memory: malloc and calloc

ESC101N: Fundamentals of Computing End-sem st semester

Ricardo Rocha. Department of Computer Science Faculty of Sciences University of Porto

At this time we have all the pieces necessary to allocate memory for an array dynamically. Following our example, we allocate N integers as follows:

Department of Computer Science & Engineering Indian Institute of Technology Kharagpur. Practice Sheet #07. Topic: Pointer in C Date:

Lab #10 Multi-dimensional Arrays

Procedural Programming & Fundamentals of Programming

ESc101: Pointers and Arrays

UNIVERSITY OF TORONTO FACULTY OF APPLIED SCIENCE AND ENGINEERING

CS1100 Introduction to Programming

Unit 1 - Arrays. 1 What is an array? Explain with Example. What are the advantages of using an array?

C: Pointers. C: Pointers. Department of Computer Science College of Engineering Boise State University. September 11, /21

Advanced Pointer Topics

Fundamental of Programming (C)

M3-R4: PROGRAMMING AND PROBLEM SOLVING THROUGH C LANGUAGE

ESC101N Fundamentals of Computing

CSC 2400: Computer Systems. Arrays and Strings in C

Strings and Library Functions

Intermediate Programming, Spring 2017*

MODULE 5: Pointers, Preprocessor Directives and Data Structures

Programming & Data Structure Laboratory. Arrays, pointers and recursion Day 5, August 5, 2014

Q 1. Attempt any TEN of the following:

C Programming Language: C ADTs, 2d Dynamic Allocation. Math 230 Assembly Language Programming (Computer Organization) Thursday Jan 31, 2008

Topics so far. Review. scanf/fscanf. How data is read 1/20/2011. All code handin sare at /afs/andrew/course/15/123/handin

Memory Management. CSC215 Lecture

Subject: Fundamental of Computer Programming 2068

CS 61c: Great Ideas in Computer Architecture

Multi-Dimensional arrays

CS 137 Part 5. Pointers, Arrays, Malloc, Variable Sized Arrays, Vectors. October 25th, 2017

PES INSTITUTE OF TECHNOLOGY (BSC) I MCA, First IA Test, November 2015 Programming Using C (13MCA11) Solution Set Faculty: Jeny Jijo

Jagannath Institute of Management Sciences Lajpat Nagar. BCA II Sem. C Programming

Chapter 9 Strings. With this array declaration: char s[10];

C Tutorial. Pointers, Dynamic Memory allocation, Valgrind, Makefile - Abhishek Yeluri and Yashwant Reddy Virupaksha

A. Year / Module Semester Subject Topic 2016 / V 2 PCD Pointers, Preprocessors, DS

C for Java Programmers 1. Last Week. Overview of the differences between C and Java. The C language (keywords, types, functies, etc.

How to declare an array in C?

In the previous lecture, we learned about how to find the complexity of algorithms and search algorithms on array.

Dynamic Memory Allocation

CS 222: Pointers and Manual Memory Management

Homework #3 CS2255 Fall 2012

Dynamic memory allocation

High Performance Programming Programming in C part 1

Question Bank (SPA SEM II)

COP 3223 Introduction to Programming with C - Study Union - Fall 2017

Main Program. C Programming Notes. #include <stdio.h> main() { printf( Hello ); } Comments: /* comment */ //comment. Dr. Karne Towson University

POINTER & REFERENCE VARIABLES

'C' Programming Language

Strings(2) CS 201 String. String Constants. Characters. Strings(1) Initializing and Declaring String. Debzani Deb

Answer all questions. Write your answers only in the space provided. Full marks = 50

Pointers and File Handling

Structures. Basics of Structures (6.1) EECS l Now struct point is a valid type. l Defining struct variables: struct point { int x; int y; };

Transcription:

PDS Class Test 2 Date: October 27, 2016 Time: 7pm to 8pm Marks: 20 (Weightage 50%) Room Sections No of students V1 Section 8 (All) Section 9 (AE,AG,BT,CE, CH,CS,CY,EC,EE,EX) V2 Section 9 (Rest, if not allotted in V1) Section 10 (All) 101 49 50 98 V3 Section 11 (All) 98 V4 Section 12 (All) 94 F116 Section 13 (All) 95 F142 Section 14 (All) 96 Let us establish the Pointer from Autumn Break to PDS!!! Programming and Data Structure 1

Example Consider the statement int xyz = 50; This statement instructs the compiler to allocate a location for the integer variable xyz, and put the value 50 in that location. Suppose that the address location chosen is 1380. xyz 1380 50 content Variable name (identity to the programmer) Memory address (identity to the system) Pointers Variables that hold memory addresses are called pointers. Since a pointer is a variable, its value is also stored in some memory location. Variable Value Address xyz 50 1380 p = &xyz; p 1380 2545 2545 1380 1380 50 p xyz Programming and Data Structure 2

Declaration of pointer int xyz; int *p; p=&xyz; Summary int *p; Data Type Pointer Variable printf( %d,xyz); is equivalent to printf( %d,*p); So xyz and *p can be used for same purpose. Both can be declared simultaneously. Example: int xyz,*p; Typecasting Typecasting is mostly not required in a well written C program. However, you can do this as follows: char c = '5 char *d = &c; int *e = (int*)d; Remember (sizeof(char)!= sizeof(int)) Programming and Data Structure 3

Examples of pointer arithmetic int a=10, b=5, *p, *q; p=&a; q=&b; printf("*p=%d,p=%x\n",*p,p); p=p-b; printf("*p=%d,p=%x\n",*p,p); printf("a=%d, address(a)=%x\n",a,&a); Output: *p=10, p=24b3f6ac *p=4195592, p=24b3f698 a=10, address(a)=24b3f6ac Pointers and Arrays Pointers can be incremented and decremented by integral values. After the assignment p = &A[i]; the increment p++ (or ++p) lets p one element down the array, whereas the decrement p-- (or --p) lets p move by one element up the array. (Here "up" means one index less, and "down" means one index more.) Similarly, incrementing or decrementing p by an integer value n lets p move forward or backward in the array by n locations. Consider the following sequence of pointer arithmetic: p = A; /* Let p point to the 0-th location of the array A */ p++; /* Now p points to the 1-st location of A */ p = p + 6; /* Now p points to the 8-th location of A */ p += 2; /* Now p points to the 10-th location of A */ --p; /* Now p points to the 9-th location of A */ p -= 5; /* Now p points to the 4-rd location of A */ p -= 5; /* Now p points to the (-1)-nd location of A */ Remember: Increment/ Decrement is by data type not by bytes. Programming and Data Structure 4

Example Consider the declaration: int *p; int x[5] = 1, 2, 3, 4, 5 ; Suppose that the base address of x is 2500, and each integer requires 4 bytes. Element Value Address x[0] 1 2500 x[1] 2 2504 x[2] 3 2508 x[3] 4 2512 x[4] 5 2516 Relationship between p and x: p = &x[0] = 2500 p+1 = &x[1] = 2504 p+2 = &x[2] = 2508 p+3 = &x[3] = 2512 p+4 = &x[4] = 2516 Accessing Array elements NOTE #include<stdio.h> int main() int iarray[5]=1,2,3,4,5; int i, *ptr; ptr=iarray; for(i=0;i<5;i++) printf( iarray[%d] (%x): %d\n",i,ptr,*ptr); ptr++; return 0; 1. The name of the array is the starting address (base address) of the array. 2. It is the address of the first element in the array. 3. Thus it can be used as a normal pointer, to access the other elements in the array. printf( iarray[%d] (%x): %d\n",i, (iarray+i),*(iarray+i)); Programming and Data Structure 5

Swapping two numbers void swap(int *a, int *b) int temp = *a; *a = *b; *b = temp; void main( ) int i, j; scanf( %d %d, &i, &j); printf( After swap: %d %d,i,j); swap(i,j); swap(&i,&j); printf( After swap: %d %d,i,j); void swap(int a, int b) int temp = a; a = b; b = temp; Revisited Character Array / String Programming and Data Structure 6

Declaring String Variables A string is declared like any other array: char string-name [size]; size determines the number of characters in string_name. When a character string is assigned to a character array, it automatically appends the null character ( \0 ) at the end of the string. size should be equal to the number of characters in the string plus one. Examples char name[30]; char city[15]; char dob[11]; A string may be initialized at the time of declaration. char city[15] = Calcutta ; char city[15] = C, a, l, c, u, t, t, a ; Equivalent char dob[] = 12-10-1975 ; Programming and Data Structure 7

Reading words scanf can be used with the %s format specification. char name[30]; : : scanf ( %s, name); The ampersand (&) is not required before the variable name with %s. The problem here is that the string is taken to be upto the first white space (blank, tab, carriage return, etc.) If we type Amit Ray name will be assigned the string Amit Reading a line of text In many applications, we need to read in an entire line of text (including blank spaces). We can use the getchar() or gets() function for the purpose. Terminating criterion will be \n. Programming and Data Structure 8

Writing Strings to the Screen We can use printf with the %s format specification. char name[50]; : : printf ( \n %s, name); Processing Character Strings There exists a set of C library functions for character string manipulation. strcpy :: string copy strlen :: string length strcmp :: string comparison strtcat :: string concatenation. It is required to include the following #include <string.h> Programming and Data Structure 9

strcpy() Works very much like a string assignment operator. strcpy (string1, string2); Assigns the contents of string2 to string1. Examples: strcpy (city, Calcutta ); strcpy (city, mycity); Warning: Assignment operator do not work for strings. city = Calcutta ; INVALID strlen() Counts and returns the number of characters in a string. len = strlen (string); /* Returns an integer */ The null character ( \0 ) at the end is not counted. Counting ends at the first null character. Programming and Data Structure 10

strcmp() Compares two character strings. int strcmp (string1, string2); Compares the two strings and returns 0 if they are identical; non-zero otherwise. Examples: if (strcmp (city, Delhi ) = = 0). if (strcmp (city1, city2)! = 0). strcat() Joins or concatenates two strings together. strcat (string1, string2); string2 is appended to the end of string1. The null character at the end of string1 is removed, and string2 is joined at that point. Example: strcpy (name1, Amit ); strcpy (name2, Ray ); strcat (name1, name2); A m i R a A m i t y \0 t \0 R a y \0 Programming and Data Structure 11

Multi Dimensional Arrays Two Dimensional Arrays We have seen that an array variable can store a list of values. Many applications require us to store a table of values. The table contains a total of 20 values, five in each line. The table can be regarded as a matrix consisting of four rows and five columns. C allows us to define such tables of items by using twodimensional arrays. Student 1 Student 2 Student 3 Student 4 Subject 1 Subject 2 Subject 3 Subject 4 Subject 5 75 82 90 65 76 68 75 80 70 72 88 74 85 76 80 50 65 68 40 70 Programming and Data Structure 12

Declaring 2-D Arrays General form: data_type array_name [row_size][column_size]; Examples: int marks[4][5]; float sales[12][25]; double matrix[100][100]; Accessing Elements of a 2-D Array Similar to that for 1-D array, but use two indices. First indicates row, second indicates column. Both the indices should be expressions which evaluate to integer values. Examples: x[m][n] = 0; c[i][k] += a[i][j] * b[j][k]; a = sqrt (a[j*3][k]); Programming and Data Structure 13

Read the elements of a 2-D array By reading them one element at a time for (i=0; i<nrow; i++) for (j=0; j<ncol; j++) scanf ( %d, &a[i][j]); The ampersand (&) is necessary. The elements can be entered all in one line or in different lines. Print the elements of a 2-D array for (i=0; i<nrow; i++) for (j=0; j<ncol; j++) printf ( \n %d, a[i][j]); The elements are printed one per line. for (i=0; i<nrow; i++) for (j=0; j<ncol; j++) printf ( %d, a[i][j]); The elements are all printed on the same line. for (i=0; i<nrow; i++) printf ( \n ); for (j=0; j<ncol; j++) printf ( %d, a[i][j]); The elements are printed nicely in matrix form. Programming and Data Structure 14

Example: Matrix Addition #include <stdio.h> void main() int a[100][100], b[100][100], c[100][100], p, q, m, n; scanf ( %d %d, &m, &n); for (p=0; p<m; p++) for (q=0; q<n; q++) scanf ( %d, &a[p][q]); for (p=0; p<m; p++) for (q=0; q<n; q++) scanf ( %d, &b[p][q]); for (p=0; p<m; p++) for (q=0; q<n; q++) c[p][q] = a[p][q] + b[p][q]; for (p=0; p<m; p++) printf ( \n ); for (q=0; q<n; q++) printf ( %d, a[p][q]); How to print three matrices side by side? 2 3 4 1 2 3 3 5 7 2 1 3 6 7 5 8 8 8 2 1 5 3 3 3 5 4 8 Programming and Data Structure 15

Passing 2-D Arrays Similar to that for 1-D arrays. The array contents are not copied into the function. Rather, the address of the first element is passed. For calculating the address of an element in a 2-D array, we need: The starting address of the array in memory. Number of bytes per element. Number of columns in the array. The above three pieces of information must be known to the function. The Actual Mechanism When an array is passed to a function, the values of the array elements are not passed to the function. The array name is interpreted as the address of the first array element. The formal argument therefore becomes a pointer to the first array element. When an array element is accessed inside the function, the address is calculated using the formula stated before. Changes made inside the function are thus also reflected in the calling program. Programming and Data Structure 16

Example Usage #include <stdio.h> main() int a[15][25], b[15]25]; : : add (a, b, 15, 25); : void add (int x[][25],int y[][25], int rows, int cols) : We can also write int x[15][25], y[15][25]; Number of columns Example: Transpose of a matrix void transpose (int x[][100], int n) int p, q; for (p=0; p<n; p++) for (q=0; q<n; q++) t = x[p][q]; x[p][q] = x[q][p]; x[q][p] = t; 10 20 30 40 50 60 70 80 90 10 20 30 40 50 60 70 80 90 a[100][100] transpose(a,3) Programming and Data Structure 17

The Correct Version void transpose (int x[][100], n) int p, q; 10 20 30 40 50 60 for (p=0; p<n; p++) for (q=p; q<n; q++) t = x[p][q]; x[p][q] = x[q][p]; x[q][p] = t; 70 80 90 10 40 70 20 50 80 30 60 90 Multi-Dimensional Arrays How can you add more than two dimensions? int a[100]; int b[100][100]; int c[100][100][100];. How long? Can you add any dimension? Can you add any size? Programming and Data Structure 18

Exercise Write a function to multiply two matrices of orders m x n and n x p respectively. Homework Step -1: Read the number of persons from the user. Step -2: Read the first name of each of the persons. Step -3: Alphabetically sort their names. Step -4: Print the sorted list. Input: Enter the number of persons: 3 Enter their first name: Tridha Susmita Pranab Output: Pranab Susmita Tridha Programming and Data Structure 19

Multi Dimensional Array Initialization Example 1 int values[3][4] = ; 1,2,3,4, 5,6,7,8, 9,10,11,12 Example 2 int values[3][4]=1,2,3,4,5,6,7,8,9,10,11,12; 2D array to 1D array How? Example 2D array 1 2 3 4 5 6 7 8 9 Row-wise representation 1 2 3 4 5 6 7 8 9 Column-wise representation 1 4 7 2 5 8 3 6 9 Why? Chunk of memory is required. May not be available. 2D array of size 50X50 is available, but not 1D array of size 2500 POSSIBLE?? 1D array of size 2500 is available, but not 2D array of size 50X50 POSSIBLE?? Programming and Data Structure 20

2-D array representation in C Starting from a given memory location, the elements are stored row-wise in consecutive memory locations. Example: int A[5][4]; A[0][0] A[0][1] A[0][2] A[0][3] A[1][0] A[1][1] A[1][2] A[1][3] A[2][0] A[2][1] A[2][2] A[2][3] A[3][0] A[3][1] A[3][2] A[3][3] A[4][0] A[4][1] A[4][2] A[4][3] 2-D array representation in C A[0][0] A[0][1] A[0][2] A[0][3] A[1][0] A[1][1] A[1][2] A[1][3] A[2][0] A[2][1] A[2][2] A[2][3] A[3][0] A[3][1] A[3][2] A[3][3] A[4][0] A[4][1] A[4][2] A[4][3] A[0]0] A[0][1] A[0]2] A[0][3] A[1][0] A[1][1] A[1][2] A[1][3] A[2][0] A[2][1] A[2][2] A[2][3] Row 0 Row 1 Row 2 x: starting address of the array in memory c: number of columns k: number of bytes allocated per array element a[i][j] is allocated at x + (i * c + j) * k Programming and Data Structure 21

Problems 1. Write a C program to multiply two matrices of orders m x n and n x p respectively. 2. Write a C program to multiply to large matrices. Interactive Input #include <stdlib.h> void main() int **mat,nrows,ncols,i; Memory allocation (2D pointer). mat=(int **)malloc(sizeof(int *)*nrows); for(i=0;i<nrows;i++) mat[i]=(int *)malloc(sizeof(int)*ncols); Memory allocation (1D pointer) for(i=0;i<nrows;i++) free(mat[i]); free(mat); Memory deallocation (1D pointer) Memory deallocation (2D pointer) Programming and Data Structure 22

2-D Array Allocation #include <stdio.h> #include <stdlib.h> int **allocate(int h, int w) Allocate array int **p; of pointers int i,j; p=(int **) calloc(h, sizeof (int *) ); for(i=0;i<h;i++) p[i]=(int *) calloc(w,sizeof (int)); return(p); Allocate array of integers for each row void read_data(int **p,int h,int w) int i,j; for(i=0;i<h;i++) for(j=0;j<w;j++) scanf ("%d",&p[i][j]); Elements accessed like 2-D array elements. 2-D Array Allocation void print_data(int **p,int h,int w) int i,j; for(i=0;i<h;i++) for(j=0;j<w;j++) printf("%5d ",p[i][j]); printf("\n"); Give M and N 3 3 1 2 3 4 5 6 7 8 9 void main() int **p; int M,N; printf("give M and N \n"); scanf("%d%d",&m,&n); p=allocate(m,n); read_data(p,m,n); printf("\n The array read as \n"); print_data(p,m,n); The array read as 1 2 3 4 5 6 7 8 9 Programming and Data Structure 23

Pointer to Pointer int **p; p=(int **) malloc(3 * sizeof(int *)); p[0]=(int *) malloc(5 * sizeof(int)); p[1]=(int *) malloc(5 * sizeof(int)); p[2]=(int *) malloc(5 * sizeof(int)); p[0] p int ** p[1] int * int * int * p[2] Linked List :: Basic Concepts A list refers to a set of items organized sequentially. An array is an example of a list. The array index is used for accessing and manipulation of array elements. Problems with array: The array size has to be specified at the beginning. Deleting an element or inserting an element may require shifting of elements. Programming and Data Structure 24

Linked List A completely different way to represent a list: Make each item in the list part of a structure. The structure contains the item and a pointer or link to the structure containing the next item. This type of list is called a linked list. Structure Variable 1 item Structure Variable 2 item Structure Variable 3 item Linked List Where to start and where to stop? Head / Start Structure Variable 1 item Structure Variable 2 item Structure Variable 3 item End / Last Programming and Data Structure 25

Linked List Facts Each structure of the list is called a node, and consists of two fields: Item(s). Address of the next item in the list. The data items comprising a linked list need not be contiguous in memory. They are ordered by logical links that are stored as part of the data in the structure itself. The link is a pointer to another structure of the same type. Declaration of a linked list struct node int item; struct node *next; ; node item next Such structures which contain a member field pointing to the same structure type are called self-referential structures. Programming and Data Structure 26