UNIT - II Selections Statements Iteration Statements Jump Statements- Expression Statements - Block Statements. Single Dimensional Arrays Generating

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

LECTURE NOTES ON COMPUTER PROGRAMMING

Q 1. Attempt any TEN of the following:

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

ONE DIMENSIONAL ARRAYS

1. Simple if statement. 2. if else statement. 3. Nested if else statement. 4. else if ladder 1. Simple if statement

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous) (ISO/IEC Certified) MODEL ANSWER

UIC. C Programming Primer. Bharathidasan University

Module 6: Array in C

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION

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

Unit 3 Decision making, Looping and Arrays

Computers Programming Course 12. Iulian Năstac

Multiple Choice Questions ( 1 mark)

Write a C program using arrays and structure

Model Viva Questions for Programming in C lab

ARRAYS(II Unit Part II)

Computer Programming Unit 3

Chapter 8 Character Arrays and Strings

'C' Programming Language

SELECTION STATEMENTS:

String can be represented as a single-dimensional character type array. Declaration of strings

C Programming Multiple. Choice

Unit 5. Decision Making and Looping. School of Science and Technology INTRODUCTION

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous) (ISO/IEC Certified)

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

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath

Characters in C consist of any printable or nonprintable character in the computer s character set including lowercase letters, uppercase letters,

C-LANGUAGE CURRICULAM

UNIT III ARRAYS AND STRINGS

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

Fundamentals of Computer Programming Using C

Question Bank (SPA SEM II)

LABORATORY MANUAL. (CSE-103F) FCPC Lab

Government Polytechnic Muzaffarpur.

Subject: PIC Chapter 2.

Computers Programming Course 11. Iulian Năstac

F.Y. Diploma : Sem. II [CO/CD/CM/CW/IF] Programming in C

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous) (ISO/IEC Certified)

Module 4: Decision-making and forming loops

Chapter 21: Introduction to C Programming Language

Introduction to string

IV Unit Second Part STRUCTURES

PDS Class Test 2. Room Sections No of students

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

INDORE INDIRA SCHOOL OF CAREER STUDIES C LANGUAGE Class B.Sc. - IIND Sem

I BCA[ ] SEMESTER I CORE: C PROGRAMMING - 106A Multiple Choice Questions.

CHAPTER 9 FLOW OF CONTROL

UNIT- 3 Introduction to C++

Basics of Programming

Strings and Library Functions

Scheme G. Sample Test Paper-I. Course Name : Computer Engineering Group Course Code : CO/CD/CM/CW/IF Semester : Second Subject Tile : Programming in C

(2½ Hours) [Total Marks: 75

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

I2204 ImperativeProgramming Semester: 1 Academic Year: 2018/2019 Credits: 5 Dr Antoun Yaacoub

Computers Programming Course 7. Iulian Năstac

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

Arrays and Pointers. CSE 2031 Fall November 11, 2013

UNIT - V STRUCTURES AND UNIONS

MODULE 2: Branching and Looping

Classification s of Data Structures

Lecture 6. Statements

INTRODUCTION 1 AND REVIEW

Decision Making -Branching. Class Incharge: S. Sasirekha

COMPUTER SCIENCE HIGHER SECONDARY FIRST YEAR. VOLUME II - CHAPTER 10 PROBLEM SOLVING TECHNIQUES AND C PROGRAMMING 1,2,3 & 5 MARKS

Fundamental of Programming (C)

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

PROGRAMMING IN C LAB MANUAL FOR DIPLOMA IN ECE/EEE

Arrays Arrays and pointers Loops and performance Array comparison Strings. John Edgar 2

Flow Control. CSC215 Lecture

/* Area and circumference of a circle */ /*celsius to fahrenheit*/

Chapter 2. Introduction to C language. Together Towards A Green Environment

UNIT-I Fundamental Notations

CS201- Introduction to Programming Latest Solved Mcqs from Midterm Papers May 07,2011. MIDTERM EXAMINATION Spring 2010

Principles of C and Memory Management

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

DECISION CONTROL AND LOOPING STATEMENTS

Data Types and Variables in C language

ITC213: STRUCTURED PROGRAMMING. Bhaskar Shrestha National College of Computer Studies Tribhuvan University

PESIT Bangalore South Campus Hosur Road (1km before Electronic City), Bengaluru Department of Basic Science and Humanities

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

SUMMER 13 EXAMINATION Model Answer

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

M1-R4: Programing and Problem Solving using C (JAN 2019)

Contents ARRAYS. Introduction:

What is recursion. WAP to find sum of n natural numbers using recursion (5)

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

CS1100 Introduction to Programming

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

Chapter 1 Getting Started Structured Programming 1

C Program. Output. Hi everyone. #include <stdio.h> main () { printf ( Hi everyone\n ); }

C-Refresher: Session 06 Pointers and Arrays


LESSON 1. A C program is constructed as a sequence of characters. Among the characters that can be used in a program are:

Arrays. Arrays are of 3 types One dimensional array Two dimensional array Multidimensional array

Arrays, Strings, & Pointers

IECD Institute for Entrepreneurship and Career Development Bharathidasan University, Tiruchirappalli 23.

Chapter 8: Character & String. In this chapter, you ll learn about;

Unit 7. Functions. Need of User Defined Functions

WAP 10. WAP 11. WAP 12. WAP 13. WAP 14. WAP 15. WAP 16. WAP 1. : 17. WAP 18. WAP 19. WAP 20. WAP 21. WAP 22. WAP 23. WAP & 24. WAP

Transcription:

UNIT - II Selections Statements Iteration Statements Jump Statements- Expression Statements - Block Statements. Single Dimensional Arrays Generating a Pointer to an Array Passing Single Dimension Arrays to Functions Strings Two Dimensional Arrays Indexing Pointers Array Initialization Variable Length Arrays

UNIT-2 CONTROL STRUCTURES Control Constructs specify the order in which the various instructions in a program are to be executed by the Computer. There are 4 types of control statement in C. They are: 1. Selection Control Statements. 2. Iteration Control Statements 3. Case control statements. 4. Jump Control Statements 1. Selection Control Statements. Selection Control Statements also called as Decision control statements and Conditional Statements allow the computer to take decision. And force to work under given condition: A Selection Control Statement gives the control to the computer for taking the decisions. Four selection control instruction which are implemented in C are following: a) if statement. b) if-else statement. c) Nested if-else statement. d) if-else Ladder. Simple if statement. Syntax: if (condition is true) Statement;

An example programs for if statement: #include<stdio.h> #include<conio.h> void main( ) int m,n; clrscr( ); printf( Enter any two number:\n ); scanf( %d %d,&m,&n); if(m-n==0) printf( the entered numbers are equal \n ); getch( ); Output: Enter any two number 50 50 You have entered numbers are equal if else statements. The if-else statement is an extension of the if statement. The ifelse statement takes care of true as well as false conditions. It has two blocks.

One block is for if and it is executed when the condition is true. The other block is of else and it is executed when the condition is false. The else statement cannot be used without if. No multiple else statements are allowed without one if. Syntax: if(expression is true) Statement-A; Statement-B else Statement-C; 1. An example programs for if-else statement: #include<stdio.h> #include<conio.h> void main( ) int age; clrscr( ); printf( Enter candidate age :\n ); scanf( %d,&age);

if(age>17) printf( Eligible for voting \n ); else printf( Not Eligible for voting \n); getch(); Output: Enter age: 20 Eligible for voting Enter age: 16 Not Eligible for voting 2. Write a program to determine whether a given value is positive or negative? #include<stdio.h> #include<conio.h> void main() int num; clrscr(); printf("enter a number"); scanf("%d",&num); if(num>0) printf("\n%d is a positive number",num); else printf("%d is a negative number",num); getch(); Output: Enter a number -9-9 is a negative number Enter a number 67 67 is a negative number

Nested if-else statements: The numbers of Logical conditions are checked for executing various statements by using nested if-else statements. Syntax: if(condition) if(condition) Statement-A; else Statement-B; else Statement-C; Statement-x; 37

Write a program to find largest number out of three numbers. Read the numbers through the keyboard? #include<stdio.h> #include<conio.h> void main() int x,y,z; clrscr(); printf("\nenter the values of x,y,z"); scanf("%d %d %d",&x,&y,&z); printf("\n Largest out of three numbers is:"); if(x>y) if(x>z) printf("x=%d\n",x); else 38

printf("z=%d\n",z); else if(z>y) printf("z=%d\n",z); else printf("y=%d\n",y); getch(); Output: Enter three numbers x, y, z: 56 89 78 Largest out of three numbers is: y=89 The else-if Ladder There is another way of putting if s together when multipath decisions are involved.a multipath decision is a chain of if s in which the statement associated with each else is an if. Syntax: if(condition-1) Statement-1; else if(condition-2) Statement-2; else if(condition-3) Statement-3; else if(condition-n) Statement-n; else Default statement; Statement-x; 39

Write a program to find the average of six subjects and display the results as follows. AVERAGE RESULT < 40 FAIL >=40 & <50 THIRD CLASS >=50 & <60 SECOND CLASS >=60 & <75 FIRST CLASS >=75 & <100 DISTINCTION #include<stdio.h> #include<conio.h> void main() int sum=0,tel,eng,math,hin,pys,chem; float avg; clrscr(); printf("\n Enter marks\ntelugu:\nenglish:\nmaths:\nhindi:\nphysics:\nchemistry:\n\n"); scanf("%d%d%d%d%d%d",&tel,&eng,&math,&hin,&pys,&chem); 40

sum=tel+eng+math+hin+pys+chem; avg=sum/6; printf("total :%d\naverage:%.2f",sum,avg); if(tel<40 eng<40 math<40 hin<40 pys<40 chem<40) printf("\n Result:fail"); else if(avg>=40&&avg<50) printf("\n Result:Third class"); else if(avg>=50&&avg<60) printf("\nresult:second class"); else if(avg>=60&&avg<75) printf("\n Result:first class"); else if(avg>=75&&avg<100) printf("\nresult:distinction"); getch(); Output: Enter marks Telugu: 96 English: 86 Maths: 77 Hindi: 66 Physics: 65 Chemistry: 88 Total: 478 Average: 79.00 Result: Distinction Case control or switch statement The Case control statements allow the computer to take decision as to be which statements are to be executed next. 41

It is a multi way decision construct facilitate number of alternatives has multi way decision statement known as switch statements.. Syntax: switch(expression) case constant_1: statements; break; case constant_2: statements; break; case constant_n: statements; break; default: statements; break; Explanation: First in expression parentheses we give the condition. This condition checks to match, one by one with case constant. If value match then its statement will be executed. Otherwise the default statement will appear.every case statement terminates with : Write a program to convert years into Minutes, Hours, Days, Months, and Seconds using switch statements. #include<stdio.h> 42

void main() long int ch,min,hrs,ds,mon,yrs,se; clrscr(); printf("\n[1]minutes"); printf("\n[2]hours"); printf("\n[3]days"); printf("\n[4]months"); printf("\n[5]seconds"); printf("\n[0]exit"); printf("\n Enter your choice:"); scanf("%ld",&ch); if(ch>0&&ch<6) printf("enter years:"); scanf("%ld",&yrs); mon=yrs*12; ds=mon*30; ds=ds+yrs*5; hrs=ds*24; min=hrs*60; se=min*60; switch(ch) case 1: printf("\n MINUTES:%ld",min); break; case 2: printf("\n Hours:%ld",hrs); break; case 3: printf("\ndays:%ld",ds); break; case 4: printf("\n Months:%ld",mon); break; case 5: printf("\n seconds:%ld",se);.,..,.. 43

break; case 0: printf("\terminated by choice"); exit(); break; default: printf("\n invalid choice"); getch(); Output: [1]MINUTES [2]HOURS [3]DAYS [4]MONTHS [5]SECONDS [0]EXIT Enter your choice: 2 Enter years: 1 Hours: 8760 ITERAION CONTROL STATEMENTS Iteration Control Statements also called as Repetition or Loop Control Statements. This type of statements helps the computer to execute a group of statements repeatedly. This allows a set of instruction to be performed until a certain condition is reached. What is a loop? A loop is defined as a block of statements which are repeatedly executed for certain number of times. There are three types of loops in C: 1. for loop 2. while loop 3. do-while loop The for loop There are three parts of for loop: a) Counter initialization. 44

b) Check condition. c) Modification of counter. Syntax: for (variable initialize; check condition; modify counter) statements 1; -----------; -----------; statements n; Explanation: 1. The initialization is usually an..gnment that is used to set the loop control variable. 2. The condition is a relational expression that determines when the loop will exit. 3. The modify counter defines how loop control variables will change each time the loop is repeated. These three sections are separated by semicolon (;). The for loop is executed as long as the condition is true. When, the condition becomes false the program execution will resume on the statement following the block. Advantage of for loop over other loops: All three parts of for loop (i.e. counter initialization, check condition, modification of counter) are implemented on a single line. 45

Something more about for loop: 1. for (p=1,n=2;n<17;n++):- we can..gn multiple variable together in for loop. 2. for (n=1,m=50;n<=m;n=n+1,m=m-1):-the increment section may also have more than one part as given. 3. for (i=1,sum=0;i<20&&sum<100;++i):-the test condition may have any compound relation as given. 4. for (x=(m;n)/2;x>0;x=x/2):-it is also permissible to use expressions in the..gnment statements of initialization and increment section as given. 5. for (; m!=100;):-we can omitted the initialization and increment section to set up time delay. An example program to print a message 5 times using for loop: #include<stdio.h> #include<conio.h> void main( ) 46

int i=1; clrscr( ); for(i=1;i<5;i++) printf( C R E C %d times \n,i); getch( ); Output: C R E C 1 C R E C 2 C R E C 3 C R E C 4 C R E C 5 Explanation of the program: The o/p will be C R E C 1 time, 2times till 5 times. WAP to display numbers from 1 to 16.use increment operation in the body of the loop for more than once. #include<stdio.h> #include<conio.h> void main() int i,c=0; clrscr(); for(i=0;i<=15;) i++; printf("%3d",i); i=i+1; printf("%3d",i); c++; printf("\n The body of the loop is executed for %d times",c); getch(); 47

Output: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 The body of the loop is executed for 8 times while loop It is a primitive type looping control because it repeats the loop a fixed no. of time. It is also called entry controlled loop statements. Syntax: while (test condition) body of loop Explanation: The test condition is evaluated if the condition is true, the body of loop will be executed. 48

Write a program to print the entered number in reverse order? #include<stdio.h> void main() int n,d,x=1; int i; clrscr(); printf("enter the number of digits:-"); scanf("%d",&d); printf("\nenter the number which is to be reversed:"); scanf("%d",&n); printf("\n the reversed number is :-"); while(x<=d) i=n%10; printf("%d",i); n=n/10; x++; getch(); 49

Output: Enter the number of digits: 4 Enter the number which is to be reversed: 7896 The reversed number is: 6987 Enter the number of digits: 4 Enter the number which is to be reversed: 3692 The reversed number is: 2963 The do-while loop The minor Difference between the working of while and do-while loop is the place where the condition is tested. The while tests the condition before executing any of the statements within the while loop.as against this, the do-while loop tests the condition after having executed the statement within the loop. syntax: do body of loop; while (test condition); Explanation: It first executes the body of the loop, and then evaluates the test condition. If the condition is true, the body of loop will executed again and again until the condition becomes false. 50

Write a program to find the numbers using do while loop. #include<stdio.h> #include<math.h> void main() int y,x=1; clrscr(); printf("\nprint the numbers and cubes"); printf("\n"); do y=pow(x,3); printf("%5d %27d\n",x,y); x++; while(x<=10); getch(); Output: Printf the numbers and their cubes 1 1 2 8 3 27 4 64 5 125 6 216 7 343 8 512 9 729 10 1000 Jump Control Statements: The break Statement We have already met break in the discussion of the switch statement. It is used to exit from a loop or a switch, p..ng control to the first statement beyond the loop or a switch. 51

With loops, break can be used to force an early exit from the loop, or to implement a loop with a test to exit in the middle of the loop body. A break within a loop should always be protected within an if statement which provides the test to control the exit condition. Syntax: Statements; break; It can be used with for, while, do-while and switch statement. The continue Statement This is similar to break but is encountered less frequently. It only works within loops where its effect is to force an immediate jump to the loop control statement. Syntax: statement 1; continue; statement 2; In a while loop, jump to the test statement. In a do while loop, jump to the test statement. In a for loop, jump to the test, and perform the iteration (looping). Like a break, continue should be protected by an if statement. You are unlikely to use it very often. The goto Statement C has a goto statement which permits unstructured jumps to be made. It requires a label in order to identify the place where the branch is to be made. A label is any valid variable name, and must be followed by a colon (:). Syntax: goto label;... label: statement; The label can be anywhere in the program either before or after the goto label; statement.another use of the goto statement is to transfer the control out of a loop (or nested loops) when certain particular conditions are encountered. Note: We should try to avoid using goto as far as possible because, it is not good for readability of the program or to improve the program execution speed. 52

ARRAYS So far we have used only the fundamental data types, namely char, float, int, double and variations of int and double. A variable of these types can store only one value at any given time. Therefore, they can be used only to handle limited amounts of data. To Process such large amounts of data, we need a powerful data type that would facilitate efficient storing, accessing and manipulation of data items. Array is a secondary or Derived Data type At some important areas the concept arrays are used To maintain list of employees in a company. In pharmacy to maintain list of Drugs and their cost. To maintain test scores of a class of students. Def: An array is a collection of elements of the same data type and it can be referred with a single name. OR Def: An array is fixed size sequence collection of elements of the same data type. Array Declaration: Arrays are defined in the same manner as ordinary variables, except that each array name must be accompanied by the size specification. The general form of array declaration is: Syntax: data type array name [size]; Data type specifies the type of array; size is a positive integer number or symbolic constant that indicates the maximum number of elements that can be stored in the array. E.g. float kick [50]; This declaration declares an array named height containing 50 elements of type float. Here 50 is an integer enclosed in brackets is the array subscript, and its value range from zero to one less than the number of memory cells in the array. Above statement instructs the compiler to associate 50 memory cells with the name kick, these cells will be adjacent to each other in memory. The memory format as fallows 53

i.e. Array elements are stored in memory as a sequential form Initialization of Arrays: The elements of array are initialized in the same way as the ordinary variables. Syntax: data type array-name [size]=list of elements; The values in the list are separated by commas. e.g. int y[10]=205, 207,208,209,210,211; From the above statements the array -name y elements are stored in memory as follows. Compiler will allocates two bytes of space for each array elements, totally 4 bytes of space is allocated for array name y. e.g. char N [10] = WELCOME ; Array Subscripts: A value or expression enclosed in brackets after the array name, specifying which array element to access. e.g.: double R [8]; 54

The integer enclosed in brackets is the Array Subscript and its value must be in the range from zero to one less than the number of memory cells in the array. Write a program to find Average of Student marks #include<stdio.h> #include<conio.h> void main() int marks[50],i,sum=0,average,count=0; clrscr(); printf("enter the Student marks"); for(i=0;i<5;i++) scanf("%d",&marks[i]); sum=sum+marks[i]; average=sum/5; for(i=0;i<5;i++) if(marks[i]>average) count++; printf("no of students who scored more than average marks:%d",count); getch(); Output: Enter the Student marks: 96 56 86 76 36 No of students who scored more than average marks: 3 An array can be of 1. One dimensional array. 2. Two dimensional arrays. 3. Multi dimensional arrays. One Dimensional Arrays: A list of values can be given one variable name using only one subscript and such a variable is called a single subscripted variable (or) onedimensional array. Declaration of one-dimensional array: 55

Syntax: type array name [size]; e.g: int bull [10]; char b[10]; C language treats character strings that represents the maximum number of characters. The size in a character string represents the maximum number of character that the string can hold. Write a program to print space required for storing them in memory using arrays. #include<stdio.h> void main() int i[9]; char j[95]; long l[7]; clrscr( ); printf("%d location for i\n",sizeof(i)); printf("%d location for j\n",sizeof(j)); printf("%d location for l\n", sizeof(l)); getch( ); Output: 18 locations for i 95 locations for j 28 locations for l Write a program to arrange the numbers in increasing and decreasing order using loops. #include<stdio.h> #include<math.h> void main() int i,j,sum=0,a[10]; clrscr(); printf("enter ten numbers"); for(i=0;i<10;i++) scanf("%d",&a[i]); sum=sum+a[i]; 56

printf("number in increasing order\n"); for(i=0;i<=sum;i++) for(j=0;j<10;j++) if(i==a[j]) printf("%d\n",a[j]); printf("numbers in decreasing order"); for(i=sum;i>=0;i--) for(j=0;j<10;j++) if(i==a[j]) printf("%d",a[j]); getch( ); Output: Enter ten numbers 1 2 3 4 5 6 7 8 9 0 Number in increasing order: 1 2 3 4 5 6 7 8 9 0 Numbers in decreasing order: 0 9 8 7 6 5 4 3 2 1 Two Dimensional arrays So far we have discussed the array variables that can store a list of values. There could be situations where a table of values will have to be stored. In such situations this concept is useful. An array with two dimensions are called Two dimensional array An array with two dimensions are called matrix. When the data must be stored in the form of a matrix we use two dimensional arrays. Declaration of Two Dimensional array: Syntax: datatype array-name [row- size] [column- size]; For example a two dimensional array consisting of 5 rows and 3 columns. So the total number of elements which can be stored in this array are 5*3 i.e. 15 57

Initialization of 2-D array: Two D array can also be initialized at the place of declaration itself. Syntax: list; Data-type array-name [row-size] [column-size] = row1 list, row2 list,. row n e.g. int mkm[2][3]= 2,3,4,5,6,7 ; Here 2, 3 and 4 are..gned to there columns of first row and 5, 6, 7 are..gned to three columns of second row in order. If the values are missing in initialization, they are set to garbage values. We can also initialize a 2-D array in the form of a matrix. e.g. int table[2][3]= 1,2,3,4,5,6; (Or) int table[2][3]= 1,2,3,4,5,6 ; (Or) int table [2][3]= 1,2,3, 4, 5, 6 ; (Or) int table[ ][ ]= 1,2,3,4,5,6 ; (Or) int table [2] [3] = 1, 2, 3; Storage Representation of two Dimensional array: When speaking of two-dimensional arrays, we are logically saying that, it consists of two rows and columns but when it is stored in memory, the memory is linear. Hence, the actual storage differs from our matrix representation. Two major types of representation can be used for 2-D array 1. Row representation 2. Column representation e.g. int a[3][3] 58

Logical view of a [3] [4];., 59

Write a program to perform Addition of Matrices #include<stdio.h> void main() int i,j,m,n,p,q; int a[10][10],b[10][10],c[10][10]; clrscr(); printf(" <---ADDITION OF TWO MATRICES---->\n"); printf("enter the size of matrix1:"); scanf("%d%d",&p,&q); printf("enter the elements of matrix2:"); scanf("%d%d",&m,&n); printf("enter elements of matrix 1:\n"); for(i=0;i<p;i++) for(j=0;j<q;j++) scanf("%d",&a[i][j]); printf("enter elements of matrix B:\n"); for(i=0;i<m;i++) for(j=0;j<n;j++) scanf("%d",&b[i][j]); if(m!=p n!=q) printf("matrix addition not possible"); else for(i=0;i<m;i++) for(j=0;j<n;j++) c[i][j]=a[i][j]+b[i][j]; printf("the resultant MATRIX is :\n"); for(i=0;i<m;i++) for(j=0;j<n;j++) printf("%5d",c[i][j]); printf("\n"); getch(); 60

Output: <----------ADDITION OF TWO MATRICES------------> Enter the size of matrix1: 3 3 Enter the elements of matrix2: 3 3 Enter elements of matrix 1: 1 2 3 4 5 6 7 8 9 Enter elements of matrix B: 1 2 3 4 5 6 7 8 9 The resultant MATRIX is: 2 4 6 8 10 12 14 16 18 Pointer to an Array Array Pointer Consider the following program: #include<stdio.h> int main() int arr[5] = 1, 2, 3, 4, 5 ; int *ptr = arr; printf("%p\n", ptr); return 0;

In this program, we have a pointer ptr that points to the 0 th element of the array. Similarly, we can also declare a pointer that can point to whole array instead of only one element of the array. This pointer is useful when talking about multidimensional arrays. Syntax: data_type (*var_name)[size_of_array]; int (*ptr)[10]; Here ptr is pointer that can point to an array of 10 integers. Since subscript have higher precedence than indirection, it is necessary to enclose the indirection operator and pointer name inside parentheses. Here the type of ptr is pointer to an array of 10 integers. Note : The pointer that points to the 0 th element of array and the pointer that points to the whole array are totally different. The following program shows this: // C program to understand difference between // pointer to an integer and pointer to an // array of integers. #include<stdio.h> int main() // Pointer to an integer int *p; // Pointer to an array of 5 integers int (*ptr)[5]; int arr[5]; // Points to 0th element of the arr. p = arr; // Points to the whole array arr. ptr = &arr; printf("p = %p, ptr = %p\n", p, ptr); p++; ptr++; printf("p = %p, ptr = %p\n", p, ptr); return 0; Output: p = 0x7fff4f32fd50, ptr = 0x7fff4f32fd50 p = 0x7fff4f32fd54, ptr = 0x7fff4f32fd64 p: is pointer to 0 th element of the array arr, while ptr is a pointer that points to the whole array arr. The base type of p is int while base type of ptr is an array of 5 integers.

We know that the pointer arithmetic is performed relative to the base size, so if we write ptr++, then the pointer ptr will be shifted forward by 20 bytes. The following figure shows the pointer p and ptr. Darker arrow denotes pointer to an array. On dereferencing a pointer expression we get a value pointed to by that pointer expression. Pointer to an array points to an array, so on dereferencing it, we should get the array, and the name of array denotes the base address. So whenever a pointer to an array is dereferenced, we get the base address of the array to which it points. // C program to illustrate sizes of // pointer of array #include<stdio.h> int main() int arr[] = 3, 5, 6, 7, 9 ; int *p = arr; int (*ptr)[5] = &arr; printf("p = %p, ptr = %p\n", p, ptr); printf("*p = %d, *ptr = %p\n", *p, *ptr); printf("sizeof(p) = %lu, sizeof(*p) = %lu\n", sizeof(p), sizeof(*p)); printf("sizeof(ptr) = %lu, sizeof(*ptr) = %lu\n", sizeof(ptr), sizeof(*ptr)); return 0; Output: p = 0x7ffde1ee5010, ptr = 0x7ffde1ee5010 *p = 3, *ptr = 0x7ffde1ee5010 sizeof(p) = 8, sizeof(*p) = 4 sizeof(ptr) = 8, sizeof(*ptr) = 20

In C, when we pass an array to a function say fun(), it is always treated as a pointer by fun(). Below example demonstrates the same. #include <stdio.h> // Note that arr[] for fun is just a pointer even if square // brackets are used void fun(int arr[]) // SAME AS void fun(int *arr) unsigned int n = sizeof(arr)/sizeof(arr[0]); printf("\narray size inside fun() is %d", n); // Driver program int main() int arr[] = 1, 2, 3, 4, 5, 6, 7, 8; unsigned int n = sizeof(arr)/sizeof(arr[0]); printf("array size inside main() is %d", n); fun(arr); return 0; Output: Array size inside main() is 8 Array size inside fun() is 1 Therefore in C, we must pass size of array as a parameter. Size may not be needed only in case of \0 terminated character arrays, size can be determined by checking end of string character. Following is a simple example to show how arrays are typically passed in C. #include <stdio.h> void fun(int *arr, unsigned int n) int i; for (i=0; i<n; i++) printf("%d ", arr[i]); int main() int arr[] = 1, 2, 3, 4, 5, 6, 7, 8; unsigned int n = sizeof(arr)/sizeof(arr[0]); fun(arr, n); return 0; output: 1 2 3 4 5 6 7 8

#include <stdio.h> void fun(int *arr) int i; unsigned int n = sizeof(arr)/sizeof(arr[0]); for (i=0; i<n; i++) printf("%d ", arr[i]); int main() int arr[] = 1, 2, 3, 4, 5, 6, 7, 8; fun(arr); return 0;

STRINGS AND POINTERS Strings: Declaring, Initialization of a String, Reading and Writing Strings, String manipulation functions from the standard Library, String I/O Functions: gets(), puts(). Pointers: Pointer Variables, Pointer Expressions, Pointers And Arrays, Pointers to Strings. Problems with Pointers. STRINGS A set (or) group of characters, digits and symbols enclosed with in quotation marks, double quotations are called strings. A string is an array of characters in other words character arrays are called strings. Every string is terminated with \0 (null) character. Declaration and Initialization of Strings: The general format of declaring string variable is as follows: Syntax: datatype string name[size]; Declaration of strings is also same as Array declaration. E.g.: char name [8] = TITANIC ; From above statement name is char type and size is 7, but..gned string TITANIC has 6 characters 7 th is null characters. That is you must leave an extra space for null characters, when we deal with character strings. The c compiler inserts the null (\0) character automatically at the end of the string so initialization of null character is not essential. Above example is also can be initialized as follows 62

Char name [8] = T, I, T, A, N, I, C ; Write a program to display the output when null is not considered #include<stdio.h> #include<string.h> Void main ( ) char name [5] = INDIA ; clrscr( ); printf( Name=%s,name); getch( ); Output: India along with garbage values Reading and Writing Strings The scanf( ) and printf( ) functions are used to read and print string respectively for formatted input and output. scanf( ) function: The familiar input functions scanf() can be used with %s format specification to be read in a string of characters. Syntax: char name [25]= POKIRI ; scanf ( % s, name); To read string, ampersand (&) is not required before the string variable. The name of the string itself acts as a base address. To eliminate the disadvantage of using a scanf function to read a line we use getchar() or gets( )functions. getchar( ): This function reads string character by character until terminating condition is satisfied. gets( ): This function reads the entire line of text. E.g: char m[30]; gets(m); 63

Printf( ) function: The commonly used output function is printf().the function can also be used for writing string, but % s should be used as format specification. E.g.: char name [30] = chadalawada ; printf ( %s, name); Here the output produced will be chadalawada. We are going to use as output functions puts (),putchar(). Puts( ): Syntax: This function prints line on the screen. char name [30] = chadalawada ; puts(name); Putchar( ); when putchar function is used, single character is printed on screen at a time until the terminating condition occurs. Write a program to print a string in different ways. #include<stdio.h> #include<conio.h> #include<string.h> void main( ) char a[10]; clrscr(); gets(a); printf("\n"); puts(a); printf("%0.5s\n",a); printf("%0.3s\n",a); printf("%-7.4s\n",a); printf("%+7.4s\n",a); getch(); Output: TITANIC 64

Note: TITANIC TITAN TIT TITA TITA - (Negative sign) indicates that specified string is printed left(left justified). + (positive sign) indicates that specified string is printed right side(right justified). String Library Functions C library supports a large no. of string handling functions that can be used to carry out many of the string manipulations. All this functions are defined in the <string.h> file. The following table gives a list of string functions. Strcat( ) string concatenate Strcmp( ) compares two strings. Strncmp( ) compares first n characters of two strings. Strcpy( ) copies strings into another. Strncpy( ) copies first n characters of a strings into another. Strlen( ) returns the length of string not counting the null character. Strlwr( ) converts string into lower case. Strupr( ) converts string into upper case. Strdup( ) copies string into a newly created location. Strrev( ) reverse string. 1. strlen( ): Determines the length of string that is it counts the no. of characters in a given string. Syntax: strlen (string); Write a program to count the number of character in a given string. #include<stdio.h> 65

#include<string.h> void main() char text[10]; int len; printf("enter the text:"); gets(text); len=strlen(text); printf("length of the string:%d",len); getch(); Output: Enter the text: GOVINDA Length of the string: 7 2. Strcpy ( ): This function copies the contents of one string to another. Syntax: Strcpy(string1,string2); Here string2 is copied into string1. Write a program to copy the contents of one string to another #include<string.h> void main() char a[10],b[10]; clrscr(); printf("enter the string A:"); gets(a); printf("enter the String B:"); gets(b); strcpy(a,b); printf("after string copy a=%s\n",a); printf("after string copy b= %s",b); getch(); 66

Output: Enter the string A: TIRUPATHY Enter the String B: TIRUMALA After string copy a= TIRUMALA After string copy b= TIRUMALA 3. Strncpy ( ); This function performs same as strcpy( ).The only difference is that this function copy string to string with specified length. Syntax: strncpy(string1,string2,n); Write a program to copy source string to destination string up to a specified length. #include<string.h> void main() char x[10]="titanic"; char y[10]="wanted"; int n=4; clrscr(); strncpy(x,y,n); printf("source string y=%s\n",y); printf(" Destination string x=%s",x); getch(); Output: 4. Strcat ( ) Source string y= WANTED Destination string x= WANTNIC This function appends the target string to source string. Concatenation of two strings can be done using this function. 67

Syntax: Strcat(string1,string2); Write a program to append second string at the end of first string using strcat( ). #include<string.h> void main() char s[10],s1[20]; clrscr(); printf("enter the string s,s1"); scanf("%s%s",s,s1); strcat(s,s1); printf("after the strcat() %s",s); getch(); Output: Enter the string s,s1: Mech Electronics After the strcat() : MechElectronics 5. Strncat ( ); This function is used to Concatenation of the strings to another up to specified length. Syntax: Strncat(string1,string2,n); Where, n is the number of character to append. Write a program to append second string with specified length of character at thew end of first string using strncat( ). #include<string.h> void main() char x[10],y[10]; int n; clrscr(); printf("enter the string x and y "); scanf("%s %s",x,y); 68

printf("enter the length"); scanf("%d",&n); strncat(x,y,n); printf("%s",x); getch(); Output: Enter the string x and y TIRUPATHY TIRUMALA Enter the length 4 TIRUPATHYTIRU 6. Strcmp ( ) This function compares two strings with case. The characters of the strings must be in lower case (or) uppercase.if the strings are same it returns Zero, other wise 1(non zero). Syntax: Strcmp(string1,string2); Write a program to the two strings using strcmp(). #include<string.h> void main() char a[10]; char b[10]; int d; clrscr(); printf("enter the string a:"); scanf("%s",a); printf("enter the string b:"); scanf("%s",b); d=strcmp(a,b); if(d==0) printf("two Strings are identical "); else printf("different"); 69

getch(); Output: Enter the string a: Rajesh Enter the string b: Ramu Different Enter the string a: Rajesh Enter the string b: Rajesh Two Strings are identical POINTERS Def: pointer is a variable which stores address of another variable. Or Pointer is variable which stores address of a variable. Or A pointer is a memory variable that stores a memory address. We can take an example to view about pointers. Pointers are widely used in programming; they are used to refer to memory location of another variable without using variable identifier itself. To declare pointer variable we need to use * operator (indirection/dereferencing operator) before the variable identifier and after data type. Pointer can only point to variable of the same data type. 70

Features of pointers Pointers are used frequently in c, as they offer a number of benefits to the programmers. 1. Pointers save the memory space. 2. Execution time with pointer is faster because data is manipulated with the address i.e direct access to memory address. 3. Pointers reduce length and complexity of programs. 4. A pointer allows C to support dynamic memory management. 5. Pointers are useful for representing two-dimensional and multi-dimensional arrays. 6. Pointers are used with data structures. Syntax; datatype *pointer_variable; The pointer variable is needed to store the memory address of any variable. The pointer is denoted by (*) asterisk symbol. It is also called Indirection/Deference operator. By using pointer variable always we can store address only, not values i.e. directly we don t..gn a value to pointer variable. By using ordinary variable only we can directly..gn a value. Declaration and Initialization Pointer variables are declared in the same way as normal variables. But pointers must declared along * operator. Syntax: Data type * variable name; E.g.: int * n; Hear n is a pointer variable of type variable of type integer, and it tells to compiler that it holds the address of any integer variable only. 71

an example program #include<stdio.h> #include<conio.h> main() int u=3; int v; int *pu; int *pv; clrscr(); pu=&u; v=*pu; pv=&v; printf("\n u=%d &u=%u pu=%u *pu=%d",u,&u,pu,*pu); printf("\n\n v=%d &v=%x pv=%x *pv=%d ",v,&v,pv,*pv); getch(); Output: Note that pu is a pointer to u, and pv is a pointer to v. therefore pu represent the address of u, and pv represents the address of v. The output shown above is, in the first printf we have printed the address of variables output with unsigned integer (%u), and in the Second printf the address of variables is printed with hexa decimal values (%X). Write a program to display the addresses of different variables together with their values. #include<stdio.h> void main() char c; int i; float f; clrscr(); printf("enter the Alphabet,Number,Float="); scanf("%c %d %f",&c,&i,&f); 72

printf("value of c=%c i=%d f=%f\n",c,i,f); printf("\n Address of c %c=%u",c,&c); printf("\n Address of i %d=%u",i,&i); printf("\naddresss of f %.2f=%u",f,&f); getche(); Output: Enter the Alphabet, Number, Float= R 10 6.7 Value of C = R i=10 f=6.700000 Address of c R=65489 Address of i 10=65490 Address of f 6.700000=65492 Arithmetic operation with Pointers Arithmetic operations on pointer variables are also possible. Increase, Decrease prefix, postfix operations can be performed with the help of the pointers. The effect of these operations are shown in the below given. Pointer and Arithmetic operation Data Initial Operation Address of after operations Required type address bytes int i=2 4046 ++ - 4048 4044 2 - char c= x 4053 ++ - 4054 4052 1 - float 4058 ++ - 4062 4054 4 f=4.2 - long l=2 4060 ++ - 4064 4056 4-73

From the above table we can observe that on increase of pointer variable for integers the address is increased by two 4046 is original address and on increase its value will be 4048 because integer requires two bytes. Similarly characters, float numbers and long integers requires 1,4and 4 bytes respectively. Write a program different Arithmetic operation using pointers. /*pointers using arithmetic operations*/ #include<stdio.h> #include<conio.h> void main() int a=25,b=10,*p,*j; clrscr(); p=&a; j=&b; printf("addition a+b=%d\n",*p+b); printf("sub a-b=%d\n",*p-b); printf("product a*b=%d\n",*p**j); printf("division a/b=%d\n",*p / *j); printf(" a mod b=%d\n", *p%*j); getch(); Output: Addition a+b= 35 sub a-b=15 Product a*b=250 Division a/b=2 a mod b=5 Pointers and Arrays Array name by itself is an address or pointer. it points to the address of the first element (0 th element of array).the element of the array together with their addresses can displayed by using array name itself. Array elements are always are always stored in contiguous memory locations. 74

For example see in the following figure. in the above figure we have taken 3 array elements i.e array[3]=0,1,2, in the second line we have directly..gned array to the pointer variable without using ampersand operator. *ptr is pointing to array[0] th element and by incrementing the pointer variable we can access the array[1],array[2] elements. Here is an example program to explain the one dimensional array Therefore if x is a one dimensional array, then the address of the first element can be expressed as either &x[0] or simply as x. The address of the second array element can be written as either &x[1]or as (x+1), and so on In general the address of array element (i+1) can be expressed as either &x[i] or as (x+i). thus we have two different ways to write the address of any array element. #include<stdio.h> #include<conio.h> void main() static int x[10]=10,11,12,13,14,15,16,17,18,19; int i; clrscr(); for(i=0;i<=9;i++) /* dispaly an array eleemnt */ printf("\n i=%d x[i]=%d *(x+i)=%d\n",i,x[i],*(x+i)); /* display the corresponding array address*/ printf(" &x[i]=%x x+i=%x ",&x[i],(x+i)); getch(); 75

Output: This program defines a one dimensional, 10- element integer array x, whose elements are..gned the values 10,11,12,13, 19.here the value of each element is specified in two different ways as x[i] and as *(x+i), in order to illustrates their equivalence. Similarly the address of each array element is specified in two different ways as &x[i] and as (x+i). The output clearly illustrates the distinction between x[i], which represents the value of the ith array element, and &x[i], which represent its address. Similarly the value of the ith array element can be represented by either x[i] or *(x+i), and the address of the ith element can be represented by either &x[i] or x+i Pointer to Strings A pointer which pointing to an array is known as pointer to array of strings. In this example ptr : It is pointer to array of string of size 4. array[4] : It is an array and its content are string. 1 : Printing Address of the Character Array #include<stdio.h> int main() 76

int i; char *arr[4] = "C","C++","Java","VBA"; char *(*ptr)[4] = &arr; for(i=0;i<4;i++) printf("address of String %d : %u\n",i+1,(*ptr)[i]); return 0; Output : Address of String 1 = 178 Address of String 2 = 180 Address of String 3 = 184 Address of String 4 = 189 2. Printing Contents of character array #include<stdio.h> int main() int i; char *arr[4] = "C","C++","Java","VBA"; char *(*ptr)[4] = &arr; for(i=0;i<4;i++) printf("string %d : %s\n",i+1,(*ptr)[i]); return 0; Output : String 1 = C String 2 = C++ String 3 = Java String 4 = VBA Problems with pointers When a pointer is used incorrectly, or contains the wrong value, it can be a very difficult to bug to find. To help you avoid them, a few of the more common errors are discussed here. 77

Example1: int x=10,*p; *p=x; /*error, p not initialized*/ Example2: int x=10,*p; p=x; /*here,..gn the value, but..gn the address */ Example3: char s[50],y[80]; char *p1,*p2; p1=s; p2=y; if(p1<p2) Is generally an invalid concept.(in very unusual situations, you might use something like this to determine the relative position of the variables. but this would be rare. 78