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

Size: px
Start display at page:

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

Transcription

1 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

2 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;

3 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 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.

4 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);

5 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 is a negative number

6 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

7 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

8 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: 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

9 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

10 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: 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

11 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

12 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

13 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

14 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

15 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

16 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

17 Output: 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

18 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

19 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

20 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 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

21 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

22 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

23 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

24 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: 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

25 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

26 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 Number in increasing order: Numbers in decreasing order: 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

27 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

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

29 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

30 Output: < ADDITION OF TWO MATRICES > Enter the size of matrix1: 3 3 Enter the elements of matrix2: 3 3 Enter elements of matrix 1: Enter elements of matrix B: The resultant MATRIX is: 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;

31 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.

32 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

33 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:

34 #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;

35 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

36 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

37 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

38 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

39 #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

40 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

41 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

42 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

43 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

44 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

45 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

46 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 Value of C = R i=10 f= Address of c R=65489 Address of i 10=65490 Address of f =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= char c= x float f=4.2 - long l=

47 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

48 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

49 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

50 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 = 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

51 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

52

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

Computer Programming. C Array is a collection of data belongings to the same data type. data_type array_name[array_size]; Arrays An array is a collection of two or more adjacent memory cells, called array elements. Array is derived data type that is used to represent collection of data items. C Array is a collection of data

More information

LECTURE NOTES ON COMPUTER PROGRAMMING

LECTURE NOTES ON COMPUTER PROGRAMMING LECTURE NOTES ON COMPUTER PROGRAMMING 2018 2019 I B.Tech I Semester (Autonomous-R17) Mr. V. SambaSiva., Assistant Professor CHADALAWADA RAMANAMMA ENGINEERING COLLEGE (AUTONOMOUS) Chadalawada Nagar, Renigunta

More information

Q 1. Attempt any TEN of the following:

Q 1. Attempt any TEN of the following: Subject Code: 17212 Model Answer Page No: 1 / 26 Important Instructions to examiners: 1) The answers should be examined by key words and not as word-to-word as given in the model answer scheme. 2) The

More information

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

B.V. Patel Institute of Business Management, Computer & Information Technology, Uka Tarsadia University Unit 1 Programming Language and Overview of C 1. State whether the following statements are true or false. a. Every line in a C program should end with a semicolon. b. In C language lowercase letters are

More information

ONE DIMENSIONAL ARRAYS

ONE DIMENSIONAL ARRAYS LECTURE 14 ONE DIMENSIONAL ARRAYS Array : An array is a fixed sized sequenced collection of related data items of same data type. In its simplest form an array can be used to represent a list of numbers

More information

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

1. Simple if statement. 2. if else statement. 3. Nested if else statement. 4. else if ladder 1. Simple if statement UNIT- II: Control Flow: Statements and Blocks, if, switch statements, Loops: while, do-while, for, break and continue, go to and Labels. Arrays and Strings: Introduction, One- dimensional arrays, Declaring

More information

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

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous) (ISO/IEC Certified) MODEL ANSWER Important Instructions to examiners: 1) The answers should be examined by key words and not as word-to-word as given in the model answer scheme. 2) The model answer and the answer written by candidate

More information

UIC. C Programming Primer. Bharathidasan University

UIC. C Programming Primer. Bharathidasan University C Programming Primer UIC C Programming Primer Bharathidasan University Contents Getting Started 02 Basic Concepts. 02 Variables, Data types and Constants...03 Control Statements and Loops 05 Expressions

More information

Module 6: Array in C

Module 6: Array in C 1 Table of Content 1. Introduction 2. Basics of array 3. Types of Array 4. Declaring Arrays 5. Initializing an array 6. Processing an array 7. Summary Learning objectives 1. To understand the concept of

More information

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION Important Instructions to examiners: 1) The answers should be examined by key words and not as word-to-word as given in the model answer scheme. 2) The model answer and the answer written by candidate

More information

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

PES INSTITUTE OF TECHNOLOGY (BSC) I MCA, First IA Test, November 2015 Programming Using C (13MCA11) Solution Set Faculty: Jeny Jijo PES INSTITUTE OF TECHNOLOGY (BSC) I MCA, First IA Test, November 2015 Programming Using C (13MCA11) Solution Set Faculty: Jeny Jijo 1. (a)what is an algorithm? Draw a flowchart to print N terms of Fibonacci

More information

Unit 3 Decision making, Looping and Arrays

Unit 3 Decision making, Looping and Arrays Unit 3 Decision making, Looping and Arrays Decision Making During programming, we have a number of situations where we may have to change the order of execution of statements based on certain conditions.

More information

Computers Programming Course 12. Iulian Năstac

Computers Programming Course 12. Iulian Năstac Computers Programming Course 12 Iulian Năstac Recap from previous course Strings in C The character string is one of the most widely used applications that involves vectors. A string in C is an array of

More information

Multiple Choice Questions ( 1 mark)

Multiple Choice Questions ( 1 mark) Multiple Choice Questions ( 1 mark) Unit-1 1. is a step by step approach to solve any problem.. a) Process b) Programming Language c) Algorithm d) Compiler 2. The process of walking through a program s

More information

Write a C program using arrays and structure

Write a C program using arrays and structure 03 Arrays and Structutes 3.1 Arrays Declaration and initialization of one dimensional, two dimensional and character arrays, accessing array elements. (10M) 3.2 Declaration and initialization of string

More information

Model Viva Questions for Programming in C lab

Model Viva Questions for Programming in C lab Model Viva Questions for Programming in C lab Title of the Practical: Assignment to prepare general algorithms and flow chart. Q1: What is a flowchart? A1: A flowchart is a diagram that shows a continuous

More information

ARRAYS(II Unit Part II)

ARRAYS(II Unit Part II) ARRAYS(II Unit Part II) Array: An array is a collection of two or more adjacent cells of similar type. Each cell in an array is called as array element. Each array should be identified with a meaningful

More information

Computer Programming Unit 3

Computer Programming Unit 3 POINTERS INTRODUCTION Pointers are important in c-language. Some tasks are performed more easily with pointers such as dynamic memory allocation, cannot be performed without using pointers. So it s very

More information

Chapter 8 Character Arrays and Strings

Chapter 8 Character Arrays and Strings Chapter 8 Character Arrays and Strings INTRODUCTION A string is a sequence of characters that is treated as a single data item. String constant: String constant example. \ String constant example.\ \ includes

More information

'C' Programming Language

'C' Programming Language F.Y. Diploma : Sem. II [DE/EJ/ET/EN/EX] 'C' Programming Language Time: 3 Hrs.] Prelim Question Paper Solution [Marks : 70 Q.1 Attempt any FIVE of the following : [10] Q.1(a) Define pointer. Write syntax

More information

SELECTION STATEMENTS:

SELECTION STATEMENTS: UNIT-2 STATEMENTS A statement is a part of your program that can be executed. That is, a statement specifies an action. Statements generally contain expressions and end with a semicolon. Statements that

More information

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

String can be represented as a single-dimensional character type array. Declaration of strings String String is the collection of characters. An array of characters. String can be represented as a single-dimensional character type array. Declaration of strings char string-name[size]; char address[25];

More information

C Programming Multiple. Choice

C Programming Multiple. Choice C Programming Multiple Choice Questions 1.) Developer of C language is. a.) Dennis Richie c.) Bill Gates b.) Ken Thompson d.) Peter Norton 2.) C language developed in. a.) 1970 c.) 1976 b.) 1972 d.) 1980

More information

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

Unit 5. Decision Making and Looping. School of Science and Technology INTRODUCTION INTRODUCTION Decision Making and Looping Unit 5 In the previous lessons we have learned about the programming structure, decision making procedure, how to write statements, as well as different types of

More information

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

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous) (ISO/IEC Certified) Subject Code: 17212 Model Answer Page No: 1/28 Important Instructions to examiners: 1) The answers should be examined by key words and not as word-to-word as given in themodel answer scheme. 2) The model

More information

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

M4.1-R3: PROGRAMMING AND PROBLEM SOLVING THROUGH C LANGUAGE M4.1-R3: PROGRAMMING AND PROBLEM SOLVING THROUGH C LANGUAGE NOTE: 1. There are TWO PARTS in this Module/Paper. PART ONE contains FOUR questions and PART TWO contains FIVE questions. 2. PART ONE is to be

More information

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

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath UNIT - I Introduction to C Programming Introduction to C C was originally developed in the year 1970s by Dennis Ritchie at Bell Laboratories, Inc. C is a general-purpose programming language. It has been

More information

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

Characters in C consist of any printable or nonprintable character in the computer s character set including lowercase letters, uppercase letters, Strings Characters in C consist of any printable or nonprintable character in the computer s character set including lowercase letters, uppercase letters, decimal digits, special characters and escape

More information

C-LANGUAGE CURRICULAM

C-LANGUAGE CURRICULAM C-LANGUAGE CURRICULAM Duration: 2 Months. 1. Introducing C 1.1 History of C Origin Standardization C-Based Languages 1.2 Strengths and Weaknesses Of C Strengths Weaknesses Effective Use of C 2. C Fundamentals

More information

UNIT III ARRAYS AND STRINGS

UNIT III ARRAYS AND STRINGS UNIT III ARRAYS AND STRINGS Arrays Initialization Declaration One dimensional and Two dimensional arrays. String- String operations String Arrays. Simple programs- sorting- searching matrix operations.

More information

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

Unit 1 - Arrays. 1 What is an array? Explain with Example. What are the advantages of using an array? 1 What is an array? Explain with Example. What are the advantages of using an array? An array is a fixed-size sequenced collection of elements of the same data type. An array is derived data type. The

More information

Fundamentals of Computer Programming Using C

Fundamentals of Computer Programming Using C CHARUTAR VIDYA MANDAL S SEMCOM Vallabh Vidyanagar Faculty Name: Ami D. Trivedi Class: FYBCA Subject: US01CBCA01 (Fundamentals of Computer Programming Using C) *UNIT 3 (Structured Programming, Library Functions

More information

Question Bank (SPA SEM II)

Question Bank (SPA SEM II) Question Bank (SPA SEM II) 1. Storage classes in C (Refer notes Page No 52) 2. Difference between function declaration and function definition (This question is solved in the note book). But solution is

More information

LABORATORY MANUAL. (CSE-103F) FCPC Lab

LABORATORY MANUAL. (CSE-103F) FCPC Lab LABORATORY MANUAL (CSE-103F) FCPC Lab Department of Computer Science & Engineering BRCM College of Engineering & Technology Bahal, Haryana Aim: Main aim of this course is to understand and solve logical

More information

Government Polytechnic Muzaffarpur.

Government Polytechnic Muzaffarpur. Government Polytechnic Muzaffarpur. Name of the Lab: COMPUTER PROGRAMMING LAB (MECH. ENGG. GROUP) Subject Code: 1625408 Experiment: 1 Aim: Programming exercise on executing a C program. If you are looking

More information

Subject: PIC Chapter 2.

Subject: PIC Chapter 2. 02 Decision making 2.1 Decision making and branching if statement (if, if-, -if ladder, nested if-) Switch case statement, break statement. (14M) 2.2 Decision making and looping while, do, do-while statements

More information

Computers Programming Course 11. Iulian Năstac

Computers Programming Course 11. Iulian Năstac Computers Programming Course 11 Iulian Năstac Recap from previous course Cap. Matrices (Arrays) Matrix representation is a method used by a computer language to store matrices of different dimension in

More information

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

F.Y. Diploma : Sem. II [CO/CD/CM/CW/IF] Programming in C F.Y. Diploma : Sem. II [CO/CD/CM/CW/IF] Programming in C Time : 3 Hrs.] Prelim Question Paper Solution [Marks : 70 Q.1 Attempt any FIVE of the following : [10] Q.1 (a) List any four relational operators.

More information

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

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous) (ISO/IEC Certified) Important Instructions to examiners: 1) The answers should be examined by key words and not as word-to-word as given in the model answer scheme. 2) The model answer and the answer written by candidate

More information

Module 4: Decision-making and forming loops

Module 4: Decision-making and forming loops 1 Module 4: Decision-making and forming loops 1. Introduction 2. Decision making 2.1. Simple if statement 2.2. The if else Statement 2.3. Nested if Statement 3. The switch case 4. Forming loops 4.1. The

More information

Chapter 21: Introduction to C Programming Language

Chapter 21: Introduction to C Programming Language Ref. Page Slide 1/65 Learning Objectives In this chapter you will learn about: Features of C Various constructs and their syntax Data types and operators in C Control and Loop Structures in C Functions

More information

Introduction to string

Introduction to string 1 Introduction to string String is a sequence of characters enclosed in double quotes. Normally, it is used for storing data like name, address, city etc. ASCII code is internally used to represent string

More information

IV Unit Second Part STRUCTURES

IV Unit Second Part STRUCTURES STRUCTURES IV Unit Second Part Structure is a very useful derived data type supported in c that allows grouping one or more variables of different data types with a single name. The general syntax of structure

More information

PDS Class Test 2. Room Sections No of students

PDS Class Test 2. Room Sections No of students 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

More information

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

Questions Bank. 14) State any four advantages of using flow-chart Questions Bank Sub:PIC(22228) Course Code:-EJ-2I ----------------------------------------------------------------------------------------------- Chapter:-1 (Overview of C Programming)(10 Marks) 1) State

More information

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

INDORE INDIRA SCHOOL OF CAREER STUDIES C LANGUAGE Class B.Sc. - IIND Sem UNIT- I ALGORITHM: An algorithm is a finite sequence of instructions, a logic and explicit step-by-step procedure for solving a problem starting from a known beginning. OR A sequential solution of any

More information

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

I BCA[ ] SEMESTER I CORE: C PROGRAMMING - 106A Multiple Choice Questions. 1 of 22 8/4/2018, 4:03 PM Dr.G.R.Damodaran College of Science (Autonomous, affiliated to the Bharathiar University, recognized by the UGC)Reaccredited at the 'A' Grade Level by the NAAC and ISO 9001:2008

More information

CHAPTER 9 FLOW OF CONTROL

CHAPTER 9 FLOW OF CONTROL CHAPTER 9 FLOW OF CONTROL FLOW CONTROL In a program statement may be executed sequentially, selectively or iteratively. Every program language provides constructs to support sequence, selection or iteration.

More information

UNIT- 3 Introduction to C++

UNIT- 3 Introduction to C++ UNIT- 3 Introduction to C++ C++ Character Sets: Letters A-Z, a-z Digits 0-9 Special Symbols Space + - * / ^ \ ( ) [ ] =!= . $, ; : %! &? _ # = @ White Spaces Blank spaces, horizontal tab, carriage

More information

Basics of Programming

Basics of Programming Unit 2 Basics of Programming Problem Analysis When we are going to develop any solution to the problem, we must fully understand the nature of the problem and what we want the program to do. Without the

More information

Strings and Library Functions

Strings and Library Functions Unit 4 String String is an array of character. Strings and Library Functions A string variable is a variable declared as array of character. The general format of declaring string is: char string_name

More information

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

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 Sample Test Paper-I Marks : 25 Time:1 Hrs. Q1. Attempt any THREE 09 Marks a) State four relational operators with meaning. b) State the use of break statement. c) What is constant? Give any two examples.

More information

(2½ Hours) [Total Marks: 75

(2½ Hours) [Total Marks: 75 (2½ Hours) [Total Marks: 75 N. B.: (1) All questions are compulsory. (2) Make suitable assumptions wherever necessary and state the assumptions made. (3) Answers to the same question must be written together.

More information

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

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 Unti 4: C Arrays Arrays a kind of data structure that can store a fixed-size sequential collection of elements of the same type An array is used to store a collection of data, but it is often more useful

More information

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

I2204 ImperativeProgramming Semester: 1 Academic Year: 2018/2019 Credits: 5 Dr Antoun Yaacoub Lebanese University Faculty of Science Computer Science BS Degree I2204 ImperativeProgramming Semester: 1 Academic Year: 2018/2019 Credits: 5 Dr Antoun Yaacoub 2Computer Science BS Degree -Imperative Programming

More information

Computers Programming Course 7. Iulian Năstac

Computers Programming Course 7. Iulian Năstac Computers Programming Course 7 Iulian Năstac Recap from previous course Operators in C Programming languages typically support a set of operators, which differ in the calling of syntax and/or the argument

More information

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

Jagannath Institute of Management Sciences Lajpat Nagar. BCA II Sem. C Programming Jagannath Institute of Management Sciences Lajpat Nagar BCA II Sem C Programming UNIT I Pointers: Introduction to Pointers, Pointer Notation,Decalaration and Initialization, Accessing variable through

More information

Arrays and Pointers. CSE 2031 Fall November 11, 2013

Arrays and Pointers. CSE 2031 Fall November 11, 2013 Arrays and Pointers CSE 2031 Fall 2013 November 11, 2013 1 Arrays l Grouping of data of the same type. l Loops commonly used for manipulation. l Programmers set array sizes explicitly. 2 Arrays: Example

More information

UNIT - V STRUCTURES AND UNIONS

UNIT - V STRUCTURES AND UNIONS UNIT - V STRUCTURES AND UNIONS STRUCTURE DEFINITION A structure definition creates a format that may be used to declare structure variables. Let us use an example to illustrate the process of structure

More information

MODULE 2: Branching and Looping

MODULE 2: Branching and Looping MODULE 2: Branching and Looping I. Statements in C are of following types: 1. Simple statements: Statements that ends with semicolon 2. Compound statements: are also called as block. Statements written

More information

Classification s of Data Structures

Classification s of Data Structures Linear Data Structures using Sequential organization Classification s of Data Structures Types of Data Structures Arrays Declaration of arrays type arrayname [ arraysize ]; Ex-double balance[10]; Arrays

More information

Lecture 6. Statements

Lecture 6. Statements Lecture 6 Statements 1 Statements This chapter introduces the various forms of C++ statements for composing programs You will learn about Expressions Composed instructions Decision instructions Loop instructions

More information

INTRODUCTION 1 AND REVIEW

INTRODUCTION 1 AND REVIEW INTRODUTION 1 AND REVIEW hapter SYS-ED/ OMPUTER EDUATION TEHNIQUES, IN. Programming: Advanced Objectives You will learn: Program structure. Program statements. Datatypes. Pointers. Arrays. Structures.

More information

Decision Making -Branching. Class Incharge: S. Sasirekha

Decision Making -Branching. Class Incharge: S. Sasirekha Decision Making -Branching Class Incharge: S. Sasirekha Branching The C language programs presented until now follows a sequential form of execution of statements. Many times it is required to alter the

More information

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

COMPUTER SCIENCE HIGHER SECONDARY FIRST YEAR.  VOLUME II - CHAPTER 10 PROBLEM SOLVING TECHNIQUES AND C PROGRAMMING 1,2,3 & 5 MARKS COMPUTER SCIENCE HIGHER SECONDARY FIRST YEAR VOLUME II - CHAPTER 10 PROBLEM SOLVING TECHNIQUES AND C PROGRAMMING 1,2,3 & 5 MARKS S.LAWRENCE CHRISTOPHER, M.C.A., B.Ed., LECTURER IN COMPUTER SCIENCE PONDICHERRY

More information

Fundamental of Programming (C)

Fundamental of Programming (C) Borrowed from lecturer notes by Omid Jafarinezhad Fundamental of Programming (C) Lecturer: Vahid Khodabakhshi Lecture 3 Constants, Variables, Data Types, And Operations Department of Computer Engineering

More information

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

Arrays and Pointers. Arrays. Arrays: Example. Arrays: Definition and Access. Arrays Stored in Memory. Initialization. EECS 2031 Fall 2014. Arrays Arrays and Pointers l Grouping of data of the same type. l Loops commonly used for manipulation. l Programmers set array sizes explicitly. EECS 2031 Fall 2014 November 11, 2013 1 2 Arrays: Example

More information

PROGRAMMING IN C LAB MANUAL FOR DIPLOMA IN ECE/EEE

PROGRAMMING IN C LAB MANUAL FOR DIPLOMA IN ECE/EEE PROGRAMMING IN C LAB MANUAL FOR DIPLOMA IN ECE/EEE 1. Write a C program to perform addition, subtraction, multiplication and division of two numbers. # include # include int a, b,sum,

More information

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

Arrays Arrays and pointers Loops and performance Array comparison Strings. John Edgar 2 CMPT 125 Arrays Arrays and pointers Loops and performance Array comparison Strings John Edgar 2 Python a sequence of data access elements with [index] index from [0] to [len-1] dynamic length heterogeneous

More information

Flow Control. CSC215 Lecture

Flow Control. CSC215 Lecture Flow Control CSC215 Lecture Outline Blocks and compound statements Conditional statements if - statement if-else - statement switch - statement? : opertator Nested conditional statements Repetitive statements

More information

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

/* Area and circumference of a circle */ /*celsius to fahrenheit*/ /* Area and circumference of a circle */ #include #include #define pi 3.14 int radius; float area, circum; printf("\nenter radius of the circle : "); scanf("%d",&radius); area = pi

More information

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

Chapter 2. Introduction to C language. Together Towards A Green Environment Chapter 2 Introduction to C language Aim Aim of this chapter is to provide the fundamentals for basic program construction using C. Objectives To understand the basic information such as keywords, character

More information

UNIT-I Fundamental Notations

UNIT-I Fundamental Notations UNIT-I Fundamental Notations Introduction to Data Structure We know that data are simply values or set of values and information is the processed data. And actually the concept of data structure is much

More information

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

CS201- Introduction to Programming Latest Solved Mcqs from Midterm Papers May 07,2011. MIDTERM EXAMINATION Spring 2010 CS201- Introduction to Programming Latest Solved Mcqs from Midterm Papers May 07,2011 Lectures 1-22 Moaaz Siddiq Asad Ali Latest Mcqs MIDTERM EXAMINATION Spring 2010 Question No: 1 ( Marks: 1 ) - Please

More information

Principles of C and Memory Management

Principles of C and Memory Management COMP281 Lecture 9 Principles of C and Memory Management Dr Lei Shi Last Lecture Today Pointer to Array Pointer Arithmetic Pointer with Functions struct Storage classes typedef union String struct struct

More information

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

A. Year / Module Semester Subject Topic 2016 / V 2 PCD Pointers, Preprocessors, DS Syllabus: Pointers and Preprocessors: Pointers and address, pointers and functions (call by reference) arguments, pointers and arrays, address arithmetic, character pointer and functions, pointers to pointer,initialization

More information

DECISION CONTROL AND LOOPING STATEMENTS

DECISION CONTROL AND LOOPING STATEMENTS DECISION CONTROL AND LOOPING STATEMENTS DECISION CONTROL STATEMENTS Decision control statements are used to alter the flow of a sequence of instructions. These statements help to jump from one part of

More information

Data Types and Variables in C language

Data Types and Variables in C language Data Types and Variables in C language Disclaimer The slides are prepared from various sources. The purpose of the slides is for academic use only Operators in C C supports a rich set of operators. Operators

More information

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

ITC213: STRUCTURED PROGRAMMING. Bhaskar Shrestha National College of Computer Studies Tribhuvan University ITC213: STRUCTURED PROGRAMMING Bhaskar Shrestha National College of Computer Studies Tribhuvan University Lecture 10: Arrays Readings: Chapter 9 Introduction Group of same type of variables that have same

More information

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

PESIT Bangalore South Campus Hosur Road (1km before Electronic City), Bengaluru Department of Basic Science and Humanities SOLUTION OF CONTINUOUS INTERNAL EVALUATION TEST -1 Date : 27-02 2018 Marks:60 Subject & Code : Programming in C and Data Structures- 17PCD23 Name of faculty : Dr. J Surya Prasad/Mr. Naushad Basha Saudagar

More information

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

First of all, it is a variable, just like other variables you studied Pointers: Basics 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 address (rather than the value)

More information

SUMMER 13 EXAMINATION Model Answer

SUMMER 13 EXAMINATION Model Answer Important Instructions to examiners: 1) The answers should be examined by key words and not as word-to-word as given in the model answer scheme. 2) The model answer and the answer written by candidate

More information

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

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language 1 History C is a general-purpose, high-level language that was originally developed by Dennis M. Ritchie to develop the UNIX operating system at Bell Labs. C was originally first implemented on the DEC

More information

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

M1-R4: Programing and Problem Solving using C (JAN 2019) M1-R4: Programing and Problem Solving using C (JAN 2019) Max Marks: 100 M1-R4-07-18 DURATION: 03 Hrs 1. Each question below gives a multiple choice of answers. Choose the most appropriate one and enter

More information

Contents ARRAYS. Introduction:

Contents ARRAYS. Introduction: UNIT-III ARRAYS AND STRINGS Contents Single and Multidimensional Arrays: Array Declaration and Initialization of arrays Arrays as function arguments. Strings: Initialization and String handling functions.

More information

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

What is recursion. WAP to find sum of n natural numbers using recursion (5) DEC 2014 Q1 a What is recursion. WAP to find sum of n natural numbers using recursion (5) Recursion is a phenomenon in which a function calls itself. A function which calls itself is called recursive function.

More information

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

Aryan College. Fundamental of C Programming. Unit I: Q1. What will be the value of the following expression? (2017) A + 9 Fundamental of C Programming Unit I: Q1. What will be the value of the following expression? (2017) A + 9 Q2. Write down the C statement to calculate percentage where three subjects English, hindi, maths

More information

CS1100 Introduction to Programming

CS1100 Introduction to Programming CS1100 Introduction to Programming Arrays Madhu Mutyam Department of Computer Science and Engineering Indian Institute of Technology Madras Course Material SD, SB, PSK, NSN, DK, TAG CS&E, IIT M 1 An Array

More information

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

C: Pointers, Arrays, and strings. Department of Computer Science College of Engineering Boise State University. August 25, /36 Department of Computer Science College of Engineering Boise State University August 25, 2017 1/36 Pointers and Arrays A pointer is a variable that stores the address of another variable. Pointers are similar

More information

Chapter 1 Getting Started Structured Programming 1

Chapter 1 Getting Started Structured Programming 1 Chapter 1 Getting Started 204112 Structured Programming 1 Outline Introduction to Programming Algorithm Programming Style The printf( ) Function Common Programming Errors Introduction to Modularity Top-Down

More information

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

C Program. Output. Hi everyone. #include <stdio.h> main () { printf ( Hi everyone\n ); } C Program Output #include main () { printf ( Hi everyone\n ); Hi everyone #include main () { printf ( Hi everyone\n ); #include and main are Keywords (or Reserved Words) Reserved Words

More information

C-Refresher: Session 06 Pointers and Arrays

C-Refresher: Session 06 Pointers and Arrays C-Refresher: Session 06 Pointers and Arrays Arif Butt Summer 2017 I am Thankful to my student Muhammad Zubair bcsf14m029@pucit.edu.pk for preparation of these slides in accordance with my video lectures

More information

CS6202 - PROGRAMMING & DATA STRUCTURES UNIT I Part - A 1. W hat are Keywords? Keywords are certain reserved words that have standard and pre-defined meaning in C. These keywords can be used only for their

More information

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

LESSON 1. A C program is constructed as a sequence of characters. Among the characters that can be used in a program are: LESSON 1 FUNDAMENTALS OF C The purpose of this lesson is to explain the fundamental elements of the C programming language. C like other languages has all alphabet and rules for putting together words

More information

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

Arrays. Arrays are of 3 types One dimensional array Two dimensional array Multidimensional array Arrays Array is a collection of similar data types sharing same name or Array is a collection of related data items. Array is a derived data type. Char, float, int etc are fundamental data types used in

More information

Arrays, Strings, & Pointers

Arrays, Strings, & Pointers Arrays, Strings, & Pointers Alexander Nelson August 31, 2018 University of Arkansas - Department of Computer Science and Computer Engineering Arrays, Strings, & Pointers Arrays, Strings, & Pointers are

More information

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

IECD Institute for Entrepreneurship and Career Development Bharathidasan University, Tiruchirappalli 23. Subject code - CCP01 Chapt Chapter 1 INTRODUCTION TO C 1. A group of software developed for certain purpose are referred as ---- a. Program b. Variable c. Software d. Data 2. Software is classified into

More information

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

Chapter 8: Character & String. In this chapter, you ll learn about; Chapter 8: Character & String Principles of Programming In this chapter, you ll learn about; Fundamentals of Strings and Characters The difference between an integer digit and a character digit Character

More information

Unit 7. Functions. Need of User Defined Functions

Unit 7. Functions. Need of User Defined Functions Unit 7 Functions Functions are the building blocks where every program activity occurs. They are self contained program segments that carry out some specific, well defined task. Every C program must have

More information

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

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 Contents 1. WAP to accept the value from the user and exchange the values.... 2 2. WAP to check whether the number is even or odd.... 2 3. WAP to Check Odd or Even Using Conditional Operator... 3 4. WAP

More information