Vous êtes sur la page 1sur 26

Lab Work Book for C Programming (BCA Level)

Pattern of Exercises Guided Work: Consider the guided properties and observe the output of given program. Do manipulations to explore and learn. Exercises: Write program on your own for given tasks. Sect.-I. Main(), Printf() and scanf() family functions
i Learn Main() function and use of printf function #include <stdio.h> // this '//' means line comment...will be ignored by compiler // the first void means main() doesn't return anything // the second void means, main() doesn't receive anything void main(void) // the beginning of the main/other function body is indicated by } a curly brace { // declare and initialize a variable with integer type... // every C/C++ statement will be terminated by ; (semi colon) int MyAge = 12; // printf() is another built-in/standard function for standard // output - your terminal/console/screen that defined in stdio.h. // In the following three printf()s, they receive and return // formatted strings... // the \n is an escape to new line...more on this later... printf("My name is Mr. C. Cplusplus\n"); printf("Hello C/C++ world!\n"); printf("-Learning about function-\n"); // the following printf() return the age... printf("My age is %d\n", MyAge); // no return statement coz main() return nothing (void) // the end of the main()/other functions body is indicated by } } ## refer to text book for format and type specifications for printf. ii In this lab you will learn another function, scanf() or a new secure version scanf_s(), on how to accept input from your standard input such as keyboard or user. // preprocessor directive #include <stdio.h> // another preprocessor directive, means replace all INIT_BALANCE // occurrences in this program with 250.50 #define INIT_BALANCE 250.50 void main(void) { float Deposit; // name is an array variable, more on this later... // means reserve 65 bytes of storage including terminated // string, '\0' char Initial, Name[65]; // some prompt to user... printf("Input name, initial and deposit:\n"); printf("What is your name? "); // read the user input and store the data at... scanf("%64s", Name); printf("What is your initial? "); // don't forget the space before %c!!! else the output

// will be proceeded to the next line...bug or what? // read the user input and store the data at... // & means storage/memory address of Initial variable... scanf(" %c", &Initial); printf("How much your deposit? "); // read the user input and store the data at... scanf("%f", &Deposit); // C4996: scanf and wscanf are deprecated; consider // using a secure version, scanf_s and wscanf_s // now it is time to read the stored data... printf("\nDUMMY REPORT:\n"); printf(" %c. %s had $%.2f\n", Initial, Name, INIT_BALANCE); printf(" Now he has $%.2f\n", (INIT_BALANCE + Deposit)); printf(" His initial is stored at address %p in the system.\n", &Initial); // No need to put the & because an array variable without [] // is already a pointer... printf(" His Name is stored at address %p in the system.\n", Name); }

Some clues
Input White-space characters Description Blank (' '); tab ('\t'); or newline ('\n'). A white-space character causes scanf() to read, but not store, all consecutive white-space characters in the input up to the next non white-space character. One white-space character in the format matches any number (including 0) and combination of white-space characters in the input. Except for the percent sign (%). A nonwhite-space character causes scanf() to read, but not store, a matching nonwhite-space character. If the next character in the input stream does not match, scanf() terminates Introduced by the percent sign (%). A format specification causes scanf() to read and convert characters in the input into values of a specified type. The value is assigned to an argument in the argument list.

Non-white-space characters Format specifications

Sect.-II.

Data Types

i). When declaring a variable (the values that change during the program execution), memory locations will be reserved for storing the values. Depending on the declared variables, these values may be number, name or any such item. An integer is a data type that stores only whole numbers. In the following code, n, m and k are declared as integers and n is initialized (given an initial value) to 40. Then m is assigned the value of 10 and k is assigned the value of 70 after adding m, n and 20. // needed for printf() #include <stdio.h> // needed for strcpy(), strcpy_s() - a secure version and their family #include <string.h> int main() { // declare variables and initialize some of them // some compiler ask you to initialize all the variables... // in this case just initialize them with dummy value.. // for example: int x = 0, float y = 0.00 etc. int i, j = 4, k; float x, y = 8.8; // warning, can change to double... char a, b ='V'; char q[20], r[20] = "Incredible Hulk"; printf("Declared and initialized some variables...\n" "...and see the action...\n\n");

// READ AND EVALUATE C/C++ EXPRESSION FROM RIGHT TO LEFT i = 5; // i becomes 5 i = i + j; // i becomes 9 (5 +4) i = i + y; // i becomes 17 (9+8.8), warning... k = (5 + (6/2)) * (3-1); printf("i = %d, k = %d\n", i, k); i = 3; x = (j/i); // integer divided by integer is an integer, warning y = (j*1.0) / i; // warning... k = (j*1.0) / i; // warning... printf("x = %.2f, y = %.2f, k = %d\n", x, y, k); a = 'Z'; printf("a = %c\nb = %c\n", a, b); // using secure version instead of strcpy(), previously // these functions generate a buffer overflow problems... // we have strcpy(dest, source), wide character version // - wcscpy(dest, source), secure version - wcscpy_s(dest, dest size, source) and // strcpy_s(dest, dest size, source) another one is multibyte version - _mbscpy(...), find it yourself... strcpy_s(q, 20, r); strcpy_s(r, 20, "CopiedString"); printf("q = %s\nr = %s\n", q, r); return 0; } ii). One must be careful when dividing two integers. The result will always be an integer, so that 14 divided by 3 is 4 else you need to use float or double. Show the output for the following program. // needed for printf() #include <stdio.h> int main() { // declare variables and initialize some of them // Some compiler ask you to initialize all the variables... // in this case just initialize them with dummy value.. // for example: int x = 0, float y = 0.00 etc. int i, j = 18, k = -20; printf("Initially, given j = 18 and k = -20\n"); printf("Do some operations..." "i = j / 12, j = k / 18 and k = k / 4\n"); i = j / 12; j = k / 8; k = k / 4; printf("At the end of the operations...\n"); printf("i = %d, j = %d and k = %d\n", i, j, k); return 0; } iii). To manipulate fractional numbers, we must declare variables of type float. Show the output for the following program. // needed for printf() #include <stdio.h> int main() { // declare variables and initialize some of them // some compiler ask you to initialize all the variables...and it is a good habit // in this case just initialize them with dummy value.. // for example: int x = 0, float y = 0.00 etc. float x, y = 20.5; printf("Given y = 20.5\n");

printf("Then do some operations..." "x = y / 8, y = (y + 18) * 3\n"); x = y / 8; y = (y + 18) * 3; printf("The results are: x = %.2f and y = %.2f\n", x, y); return 0; } iv).If an expression divides 10 by 4, the answer is 2 (integer) and not 2.5 (float). If 10 / 4 is assigned to a float, then 2 is converted to 2.0 before assign it to the float. In the following example we can force the int type to float but not vice versa. Show the output for the following program. // needed for printf() #include <stdio.h> int main() { // declare variables and initialize some of them // some compiler ask you to initialize all the variables... // in this case just initialize them with dummy value.. // for example: int x = 0, float y = 0.00 etc. int j = 18; float x, y = 20.5; printf("Given j = 18, y = 20.5\n"); printf("The operations: x = j / 7, y = y / 7\n"); x = j / 7; y = y / 7; printf("The result are: x = %.2f and y = %.2f\n", x, y); printf("But we can force or promote the int to float - type promotion...\n"); x = ((float) j / 7); printf("The result are: x = %.2f and y = %.2f\n", x, y); return 0; } v). Try next example, show the output. // needed for printf() #include <stdio.h> int main() { // declare variables and initialize some of them // some compiler ask you to initialize all the variables... // in this case just initialize them with dummy value.. // for example: int x = 0, float y = 0.00 etc. int i = 5, j = 8; printf("Given i = 5, j = 8\n"); printf("Operations and results...\n"); printf(" i + j = %d\n", i + j); printf(" i + 1 = %d, j + 1 = %d\n", i + 1, j + 1); printf(" i - j * (i - 7) = %d\n", i - j * (i - 7)); // operator precedence...which operator that compiler execute first? // 5 - 8 * (5 - 7) = 5 - 8 * (-2) = 5 - (-16) = 21 // better to use parentheses: i - (j * (i - 7)) // start from the innermost then to the outermost of the parentheses printf(" i = %d, j = %d\n", i, j); return 0; }

Exercises(Data Types ) i) If we assign a variable a number beyond the range of its data type (int, short int, long etc.) then the number printed is negative. Using

this information, write programs to determine the range of int, short int and long data types on your computer. [hint: you will need use of repetition statement]

Sect.-III.
i)

Let us have a C pseudocode for simple integer iteration program example. In a simple word we are going to print an integer number from -4 to 0. i. Declare an integer variable, j and set an initial value to -4, j = -4. ii. Check the condition for j, j <= 0 true or false? iii. Print the js value. iv. Increment j by 1. v. Repeat the iteration process until j <= 0 is false. vi. If the condition j<=0 is false, stop exit the loop and continue the execution of
the next code if any.

C Repetition: The for Loop, while Loop

#include <stdio.h> void main() { int j; j = -4; for( ; j <= 0 ; ) { printf("%d\n", j); j = j + 1; } } #include <stdio.h> void main() { int j = -4; for( ; j <= 0 ; ) { printf("%d\n", j); j = j + 1; } } #include <stdio.h> void main() { int j; for(j = -4; j <= 0 ; ) { printf("%d\n", j); j = j + 1; Try following program #include <stdio.h> void main() { int i; i = 0; // Statement 1 for( ; i <= 4; ) // Statement 2 { printf("%d\n", i); i = i + 2; // Statement 3

} } #include <stdio.h> void main() { int j; for(j = -4; j <= 0 ; j = j + 1) printf("%d\n", j);

#include <stdio.h> void main() { int j; for( j = -4; j <= 0 ; ) printf("%d\n", j++); } #include <stdio.h> void main() { int j; for( j = -4; j <= 0 ; j++) printf("%d\n", j); }

} }

What is the first value of i? What is the last value of i that is printed? c) Which statement determines the initial value? 1, 2 or 3? d) Which statement determines the final value? e) Which statement determines how the value of i is increased? What happen to the following program output? How to stop it? How would you correct it?
b) #include <stdio.h> void main() { int i; // here we set the initial value to 3, but the condition // is != 2, print and increment the i by 1... // the i != 2 is true forever! for(i = 3; i != 2; i = i + 1) printf("%d ", i); } Compress or simplify the following

code as much as possible

by retaining the output.


#include <stdio.h> void main() { int i = 0; for(; i < 5;) printf("%d ", i); i = i + 1; } ii) The while loop in C is very similar to the for loop. The for statement contains two semicolons, which allows placement of the initialization statement, the negation of the termination condition and the iterative statement in it. However, the while loop allows placement of only the condition so the other two statements must be placed outside the while statement. #include <stdio.h> int main(void) { int i, j; // for loop printf("This is a for loop\n"); for(i = -5; i <= 0; i = i +1) // initial, terminal condition and iteration printf("%d ", i); printf("\n"); printf("\nThis is a while loop\n"); j = -5; // initial condition // while loop while(j <= 0) // terminal condition { printf("%d ", j); j = j + 1; // iteration } printf("\nBoth constructs generate same result...\n"); return 0; }

iii) Program to show the nested while loops #include <stdio.h> int main() { // variables for counter int i = 15, j; // outer loop, execute this first... // for every i iteration, execute the inner loop while(i>0) { // display i== printf("%d==", i); // then, execute inner loop with loop index j, // the initial value of j is i - 1 j=i-1; while(j>0) { // display # printf("#"); // decrement j by 1 until j>10, i.e j = 9 j = j - 1; } // go to new line, new row printf("\n"); // decrement i by 1, repeat until i > 0 that is i = 1 i = i - 1; } return 0;

}
iv) Program to show the nested for loops

#include <stdio.h> int main() { // variables for counter int i, j; // outer loop, execute this first...for every i iteration, // execute the inner loop for(i = 1; i <= 9;) { // display i printf("%d", i); // then, execute inner loop with loop index j, // the initial value of j is i - 1 for(j = i-1; j>0; ) { // display ==j printf("==%d", j); // decrement j by 1 until j>0, i.e j = 1 j = j - 1; } // go to new line printf("\n"); // increment i by 1, repeat until i<=9, i.e i = 9 i = i + 1; } return 0;

}
v) Convert the following programs that using for loop to while loop. #include <stdio.h> int main() { // variables for counter int i, j; // outer loop, execute this first... // for every i iteration, execute the inner loop for(i=15; i>0;) { // display i== printf("%d==", i); // then, execute inner loop with loop index j, // the initial value of j is i - 1 for(j=i-1; j>0; ) { // display # printf("#"); // decrement j by 1 until j>10, i.e j = 9 j = j - 1; } // go to new line, new row printf("\n"); // decrement i by 1, repeat until i > 0 that is i = 1 i = i - 1; } return 0; } vi) The do-while Loop: The following example uses do-while loop, another C/C++ construct that can be used for repetition. The main difference here is the condition is tested after the body of the loop and the statement in the body will be executed at least once whether the condition is true or false. This is not the case with the other two loops where if the condition is false at the beginning, then the body of the loop is not executed at all. #include <stdio.h> int main() { int j = -5; // initialization do { printf("%d\n", j); j = j + 1; } while(j <= 0); // condition return 0; } vii) The EOF Character: A special character called EOF (End Of File) is placed at the end of a file. When a computer system is typing out a file and it encounters this character, it realizes that this is the end of the file and that the typing of the file is complete. In UNIX based OS, this character is CTRL-D and in PC system, it is CTRL-Z. EOF is defined in stdio.h file. Its value is -1. The following shows the usage of EOF. The getchar() function get a character from the user and store it in i. If i is not equal to EOF, then we use the putchar() function, print it on the screen and get another one to place it in i. This is done until EOF is encountered, when the loop stops. Notice that the character is read into i, an integer. It could also have been a char. In the output, a total of 4 is shown because the fourth character, which we cannot see, is the carriage return character.

#include <stdio.h> int main() { int i, j; // read the user input, getchar() can read any char // here we declare int i = getchar(); for(j = 0; i != EOF; j = j + 1) { // display to screen... putchar(i); i = getchar(); } printf("The total count is = %d\n", j); return 0; }

Exercises (Looping) i) Print following patterns:


* ** *** **** * * * * * * * * * * * * * * *

* * * * * * * * * * * * * * *

* * * * * * * * * * * * * * * *

* * * * * * * * * * * * * * * *

1 2 3 4

4 6 8

9 12

16

Sect.-IV.
i)

C Selection: if, if-else, if-else-if

The if, if-else construct and its variation used in C/C++ when we need to make a selection from the given options based on the certain condition. #include <stdio.h> int main(void) { int x; printf("Enter an integer: \n"); scanf ("%d", &x); if(x == 3) { printf("x = %d\n", x); printf("The if condition is fulfilled!\n"); } else { printf("x = %d\n", x); printf("The if condition is not fulfilled!\n"); } return 0; } ii) By expanding the if-else statement, we can build a program with any number of conditions and the respective options. #include <stdio.h> int main(void) { int x; printf("Enter your mark: "); scanf_s("%d", &x, 1);

if(x <= 50) { printf("Your grade is F - FAIL.\n"); printf("You need to repeat the paper\n"); } else if(x <= 60) printf("Your grade is E - CONDITIONAL PASS.\n"); else if(x <= 70) printf("Your grade is D - PASS.\n"); else if(x <= 80) printf("Your grade is C - GOOD.\n"); else if(x <= 90) printf("Your grade is B - VERY GOOD.\n"); else if(x <= 100) printf("Your grade is A - EXCELLENT.\n"); return 0; } iii) Write a complete working program that will ask for a persons name and his/her game score. Then it will ask for a second persons name and score. The program will print the winners name and also print by how many points that person won. The following is a pseudocode example for this question. Write the program in C Declare variables for the amount in float, balance in float and transaction code in char types. float amount, balance=0.0; char transaction; Read & store the amount and transaction code. scanf_s("%f %c", &amount, &transaction, sizeof(float), sizeof(char)); Test the transaction code, if d it is deposit. if(transaction == 'd') Test the balance so that it is not negative. for(;balance >=0;) If the balance is not negative or positive sum-up the balance. balance = balance + amount; And keep reading the next input of amount and code. scanf_s("%f %c", &amount, &transaction, sizeof(float), sizeof(char)); At the same time keep reading the transaction code for withdrawal, w. If the transaction code is w if(transaction == 'w') Minus the withdrawn amount to update the balance. balance = balance - amount; Keep reading and storing the withdrawn amount using the do-while because we need to terminate the loop without printing the last input. That is checking the balance for negative at the end of the loop. do { scanf_s("%f %c", &amount, &transaction, sizeof(float), sizeof(char)); balance = balance - amount; }while(balance >=0); When the balance is negative, stop the loop and print the negative balance. printf("Your account now is %.2f dollars.\n", balance); Program stop. iv) The Conditional Operator (?:), ternary:-- Whenever one value has to be assigned to a variable if a certain condition is true and another has to be assigned to that same variable if it is false, then the conditional operator can be used. Using the conditional operator will simplify your coding. The following if-else example is converted to using ?: operator. #include <stdio.h> int main(void)

{ // initialize with dummy value... char x = 'n'; printf("Enter 'y' or non-'y': \n"); scanf_s(" %c", &x); // the following codes can be converted using ?: operator if(x == 'y') printf("If 'y', answer is = 1\n"); else printf("Else, answer is = 0\n"); return 0; } v) The switch-case-break Statement:-- An organized way to write if statements that depend on the value of one variable is to use the switchcase-break statement. The following example shows how the if program is converted to using the switch statement. The breaks are required for all the cases except for the last one. Also the default case is optional. #include <stdio.h> #include <stdio.h> int main(void) int main(void) { { char code = 'd'; char code = 'd'; float balance = 0.0, amount = 0.0; float balance = 0.0, amount = 0.0; printf("Enter your transaction code, d - deposit, w printf("Enter your transaction code, d withdrawal: \n"); deposit, w - withdrawal: \n"); scanf_s(" %c", &code); scanf_s(" %c", &code); // the following code can be converted to using // switch-case-break statement... // switch-case-break statement... switch(code) if(code == 'd') { { case 'd': printf("Your deposit...\n"); { balance = balance + amount; printf("Your deposit...\n"); } balance = balance + else if(code == 'w') amount; { break; printf("Your withdrawal...\n"); } balance = balance - amount; case 'w': } { else printf("Your printf(" %c code not allowed\n", code); withdrawal...\n"); return 0; balance = balance } amount; break; } default: printf("%c code not allowed. Try again!\n", code); } return 0; }

Exercises (Control Constructs)


i) Men and women are running races. We need to know what was the lowest mens score and the highest womens score. Data are given so that mens scores alternate with those of women: first mens, then womens. The program stops when a time of zero is read for a mans score. A sample input and output are given below. Design and write theprogram.
-----------------Input---------------7.80 5.70

5.80 8.95 0.0 -----------------Output---------------Lowest mens: 5.80 Highest womens: 8.95

ii) In the following practice, we will use the data in Table 3. We will use the rate in the Table to construct the logic for determining the correct rate. r will stand for residential, c will stand for commercial and u stand for unit. Units used Residential Commercial 0 < units <= 200 0.8 0.6 above 200 0.7 0.3 Let us first consider the condition for the case where type is equal to residential only. If the type is residential and unit of consumption are less than or equal to 200, then the rate is 0.8, according to the Table. If the units are not less than or equal to 200, then the rate is made equal to 0.7. Complete the coding for this part of the logic. iii) Write a program that reads an integer and checks whether it is odd or even.

Sect.-V.

C Arrays-

Array is another C/C++ data type. It is an aggregated same data type. i) Need for an Array: Here game scores for four individuals are read in and they are printed in reverse order. Imagine how much more we have to repeat the monotonous steps if scores are in thousands. Just reading and writing like that would take thousand lines let alone doing other processing, such as finding the highest score. #include <stdio.h> void main() { float score1, score2, score3, score4; printf("Enter four floats: \n"); scanf_s("%f", &score1); scanf_s("%f", &score2); scanf_s("%f", &score3); scanf_s("%f", &score4); printf("The scores in reverse order are: \n"); printf("%.2f\n", score4); printf("%.2f\n", score3); printf("%.2f\n", score2); printf("%.2f\n", score1); } Instead, consider the solution using arrays shown below. Feel the difference of extensibility. #include <stdio.h> #define SIZE 4 // the arrays size void main() { float score[SIZE]; int i; // loop to read in the scores into the array printf("Enter %d floats: ", SIZE); for(i = 0; i <= (SIZE - 1); i = i + 1) scanf_s("%f", &score[i]); // loop to write out the scores from the array printf("The scores in reverse order are: \n"); for(i = SIZE - 1; i >= 0; i = i - 1)

printf("%.2f\t", score[i]); printf("\n"); } ii) Searching An Array Element:- Let us take a look at another example of array program, searching an array element. Build and run the following program. #include <stdio.h> void main() { // an array to store a list of scores float score[12], // the array is searched for this score lookup; // used as an index to step through the array int i, // the index of the last score stored in the array max; // read in the scores into the array printf("Enter up to 10 floats, enter 0 when done: \n"); scanf_s("%f", &score[0]); for(i = 0; score[i] != 0; i = i + 1) scanf_s("%f", &score[i + 1]); max = i - 1; // read a score to be searched in the array printf("What score do you want to look up? "); scanf_s("%f", &lookup); // search the array for this score for(i = 0; i <= max; i = i + 1) if(score[i] == lookup) // abandon the loop if element is found break; // if it was found, then a break was executed and "i" was <= "max" if(i <= max) printf("The score of %.2f was number %d in the list.\n", lookup, i + 1); // otherwise, "i" went past the value of "max". else printf("The score of %.2f was not found in the list.\n", lookup); } iii) Arrays allow programmers to group related items of the same data type in one variable. However, when referring to an array, one has to specify not only the array or variable name but also the index number of interest. #include <stdio.h> void main() { char a[11] = "Boring"; printf("Index 0 has %c\n", a[0]); printf("Index 1 has %c\n", a[1]); printf("Index 2 has %c\n", a[2]); printf("Index 3 has %c\n", a[3]); printf("Index 4 has %c\n", a[4]); printf("Index 5 has %c\n", a[5]); printf("Index 6 has %c\n", a[6]); printf("Index 7 has %c\n", a[7]); printf("Numerically, the a[6] is %d\n", a[6]); } a. How many slots/indexes does this array have? b. How many characters, counting the null character at the end, does this array hold?

c. The number of an index is also called an index. What is the lowest index? d. What is the highest index for this array? e. Is the number for the highest index the same as that for the number of indexes? f. What is stored in the last index as a character, that is, in an index number 5?

g. What is stored in the last index numerically? All strings should have this null character stored in its last index to signal the end of the string.
Try the following program. #include <stdio.h> void main() { char a[11] = "sweet girl"; int i; for(i = 0; i <= 9; i = i + 1) a[i] = '1'; printf("%s\n", a); } a. What was stored in each index of the array? b. If the array were initialized to good boy, what would have been printed? iv) Show the content of the arrays for the following a[ ] and b[ ], using the given input data and study the code and the output. #include <stdio.h> void main() { int i, a[12], b[12], k; printf("Enter a sample input data: \n"); scanf_s("%d", &k); for(i = 0; i <= k; i = i + 1) { scanf_s("%d", &a[i]); printf("a[%d] = %d\n", i, a[i]); } for(i = 0; i <= k; i = i + 1) { scanf_s("%d", &b[i]); printf(" b[%d] = %d\n", i, b[i]); } printf("\n"); } To terminate the program you need to press Ctrl + C for PC/IBM compatible. #include <stdio.h> void main() { int i, a[12], b[12], k; printf("Enter a sample input data: \n"); scanf_s("%d", &k); for(i = 0;k != 1; i = i + 1) { a[i] = k; b[i] = k; scanf_s("%d", &b[i]);

printf("a[%d] = %d ", i, a[i]); printf(" b[%d] = %d\n", i, b[i]); } printf("\n"); } v) Let put the 2D array in the real C program. Observe, interpret, execute and verify the output of the following program. #include <stdio.h> // for strcpy_s() #include <string.h> void main() { // array that holds 6 strings, each max 9 characters long char Name[6][10] ={"Mr. Bean", "Mr. Bush", "Nicole", "Kidman", "Arnold", "Jodie"}; // array that holds scores for 6 players of "name[ ][ ]" int Score[6], // a variable to count the number of a's. Count = 0, // index for the largest score while doing the sorting LargestIdx, // used in the for loop i, j, // used to temporarily store a score while doing the swapping Temp; // used to temporarily store a name while doing the swapping char TempStr[10]; // loop and nested loop to count the number of a's in all the names // loop for the rows... for(i = 0; i <= 5; i = i + 1) // loop for the columns for(j = 0; Name[i][j] != '\0'; j = j + 1) // start counting the 'a' and 'A' if(Name[i][j] == 'a' || Name[i][j] == 'A') Count = Count + 1; printf("The number of a's is %d.\n\n", Count); // loop to get the scores of all 6 players for(i = 0; i <= 5; i = i + 1) { printf("Enter score for %s: ", Name[i]); // scanf("%d", &Score[i]); scanf_s("%d", &Score[i], 1); } // nothing here, just to see the entered scores... printf("The entered scores: "); for(i = 0; i <= 5; i = i + 1) printf("%d ", Score[i]); // start the sorting, i is the number of the pass for(i = 0; i <= 4; i = i + 1) { // find index that has the largest number for this pass LargestIdx = i; for(j = i + 1; j <= 5; j = j + 1) if(Score[j] > Score[LargestIdx]) LargestIdx = j; // swap the first score and name for this pass with that of the largest score Temp = Score[i]; Score[i] = Score[LargestIdx]; Score[LargestIdx] = Temp; // strcpy(TempStr, Name[i]);

strcpy_s(TempStr, 9, Name[i]); strcpy_s(Name[i], 9, Name[LargestIdx]); strcpy_s(Name[LargestIdx], 9, TempStr); } // print out the sorted scores and names printf("\nThe descending score:\n"); for(i = 0; i <= 5; i = i + 1) printf("%d\t%s\n", Score[i], Name[i]); } vi) Show the output and answer the questions for the following program #include <stdio.h> void main() { int i, j, a[3][4] = {1,2,3,4,5,6,7,8,9,10,11,12}; for(i = 2; i >= 0; i = i - 1) { for(j = 3; j >= 0; j = j - 1) printf("a[%d][%d] = %d\t", i, j, a[i][j]); printf("\n"); } } a. When i is 2 and j is 3, the element in which row and which column is printed? b. When i is 2 and j is 2, the element in which row and which column is printed? c. When i is 2 and j is 0, the element in which row and which column is printed? d. When i is 1 and j is 3, the element in which row and which column is printed? e. When the last element is printed, what is i and what is j? vii)Strings are read in by the rows. Each row will have one string. Enter the following data: you, my, luv. Remember that after each string, a null character is added. We are reading in strings but printing out only characters. #include <stdio.h> void main() { int i, j; char a[3][4]; printf("Give three 3-characters strings.\n"); for(i = 0; i <= 2; i = i + 1) // scanf("%s", &a[i]); scanf_s("%s", &a[i], 4); for(i = 0; i <= 2; i = i + 1) { for(j = 0; j <= 3; j = j + 1) printf("a[%d][%d] = %c\t", i, j, a[i][j]); printf("\n"); } } a. Show the contents of the array in memory after the three strings are read in the array. b. Does your output agree? c. How is the null character, \0 printed? d. Is there a garbage character in a[1][3]? If so, why?

Exercises (Arrays)

i)

Complete the for loop in the following program so that the characters of the array are printed in reverse order, starting from index number 10 down to slot number 0? #include <stdio.h> void main() { char a[11] = "Hello World"; int i; for(_____; __________________; _______) printf("Index %d has %c\n", i, a[i]);

ii) For the following program, you need to modify the code to see the a[ ] and b[ ]. #include <stdio.h> void main() { int i, a[12], b[12], k; printf("Enter a sample input data: \n"); scanf("%d", &k); for(i = 0;k > 1; i = i + 1) { a[i] = k; scanf("%d", &k); } scanf("%d", &k); for(i = 0; k > 1; i = i + 1) { b[i] = k; scanf("%d", &k); } printf("\n"); } iii) Create a program that read 10 floats into an array and print their average. iv) Initialize an array with 6 integers. Read another integer and add that number to each element in the array. Then print the array. v) Initialize an array with 6 integers. Read another integer and print the value of each array element that is less than this read-in integer and print the number of elements that were not printed. For example, if the array were 40, 80, 20, 50, 90, 30 and an 80 were read in, then the output would be something like: -------Output------40 20 50 30 count = 2 vi) Initialize two integer arrays, a[6] and b[6]. First print their elements in two rows, and then print them out in two columns. vii)Scan floating point numbers into an array until the sum of those numbers exceed 100. At the index where the sum becomes greater than 100, store a -1.0 to denote the end of the array. Now print the number of elements in the array, not including the -1.0. viii) Build, run and show the output for the following program then answer the questions. In this program, i (the row) is fixed, j (column) varies. #include <stdio.h> void main() { int i, j;

for(i = 1; i <= 3; i = i + 1) { for(j = 1; j <= 4; j = j + 1) printf("i = %d\tj = %d\n", i, j); printf("\n"); } } a. There are two loops above, the i loop and the j loop. Which loop is the outer loop? b. Which loop would you call the nested loop? c. Which loop is done only once? Which one is repeated? d. How many times is i set to 1? How many times is j set to 1? e. Which variable varies faster than the other? f. What is the effect of omitting the braces of the i loop? ii) Write program for following b) Taking input one matrix and display its transpose. c) Taking input two Matrices and store and display addition output in third matrix. d) Taking input two Matrices and store and display multiplication output in third matrix. ix) Write program for Selection Sort. Test with your own data.

Sect.-V.
i)

Build, run and show the output for the following example. Answer the questions. #include <stdio.h> // this is function prototype, must appear before function definition... void Funny(void); // main() function void main(void) { // main() calls Funny() Funny(); printf("In main() - Yes it is me!\n"); } // defining Funny... void Funny(void) { printf("In Funny() - Silly me.\n"); } a. Name two user-defined functions (function bodies which you have typed)? b. Name one predefined/system function (a function which is made available to you by the compiler). c. Execution starts at main(). What is the first function that main() calls? d. What is the second function that main() calls after the first one is done? e. What function does Funny() call? f. Number the following events in order from 1 through 3: ______ - Funny() calls printf() ______ - main() calls printf() ______ - main() calls Funny() g. How do we know where the definition of main() starts and ends? h. How do we know where the definition of Funny() starts and ends? i. The void after main() indicates that main() doesnt receive any arguments. Does Funny() receive any values? j. The void before main() indicates that the main() doesnt return any values. Does Funny() return any values?

C Functions

k. All programs must have main(). However, when defining a function other than main(), a prototype should be given, stating the name of the function, what arguments it receives and what item it returns, if any. A prototype can be given inside or outside main() provided that the function definition appear after the prototype statement. Where is the prototype given here? Run the following program, show the output and answer the questions #include <stdio.h> void Funny(void); void main(void) { int i; for(i = 1; i <=3; i = i + 1) { printf("In main(), i = %d\n", i); Funny(); } } void Funny(void) { int i; for(i = 1; i <= 2; i = i + 1) printf("In Funny(), i = %d\n", i); } a. How many times does main() call Funny()? b. Each time that Funny() is called, printf() is called how many times from Funny()? c. The loop in main() is done how many times? d. The loop in Funny() is done a total of how many times? e. The printf() in main() is done how many times? f. What is the total number of times that printf() is called from Funny()? g. Tracing the execution of this program, initially, main() sets i to 1. Then the control of execution goes to Funny(). Here, i is also set to 1. From the output, can you determine whether this is the same i, or are they different? h. Starting again, the i in main() is set to 1 and then the i in Funny() goes from 1 to what value? After that, we go back to main() and now i is incremented to 2 and we come back to Funny(). When we come back to Funny(), i goes from 1 to what value? The third time we come back to Funny(), i goes from 1 to what value? ii) Let us pass arguments (values or data) to Funny(). The difference for this thing when a function receives an argument are shown in bold, an integer represented by parameter num instead of void. #include <stdio.h> // receiving an integer void Funny(int); void main(void) { // first call, 4 will go into num Funny(4); printf("\n"); // second call, 3 will go into num Funny(3); } // num is a formal parameter, acts as a placeholder. // the value or argument of num can change...

void Funny(int num) { printf("In Funny(), the value of variable num = %d\n", num); } a. main() calls Funny() how many times? b. What is the difference in how Funny() is called here compared to how it is called in Experiment 5. c. When Funny() is called by main() for the first time, what argument (an integer) is passed? d. When Funny() is called by main() for the second time, what argument is passed? e. What is the value of num when Funny() is executed the first time? f. What is the value of num when Funny() is executed the second time? g. In the prototype for Funny(), should the data type of the argument be given? h. In the prototype for Funny(), do we have to give the variable name of the argument, that is, num? i. In the definition for Funny(), should we give the data type of the argument? j. In the definition for Funny(), is the variable name of the argument given? k. Number the order of the events execution: iii) Receiving And Returning Values From Functions
#include <stdio.h> // this function receive nothing but // return a char... char JustTesting(void); void main(void) { char x; x = JustTesting(); printf("The returned char is = %c\n", x); } char JustTesting(void) { return ('T'); }

iv) Try Following formats


void main(void) { TestFunct(); ... } void TestFunct() { // receive nothing // and nothing to be // returned } void main(void) { TestFunct(123); ... } void TestFunct(int i) { // receive something and // the received/passed // value just // used here. Nothing // to be returned. } void main(void) { x = TestFunct(123); ... } int TestFunct(int x) { // received/passed something // and need to return something return (x + x); }

void main(void) { x = TestFunct(); ... } int TestFunct(void) { // received/passed // nothing but need to // return something return 123; }

v) Recursion: Recursive Function:-- When a function calls itself, it is called recursion. Try following:
#include <stdio.h> int Product(int a, int b); int Sum(int q, int r); void main(void) { int x; x = Product(3, 4); printf("The product(3, 4) is %d\n", x); } // only adding and subtracting, // multiplication is done int Product(int a, int b) { if(a == 1) return b; else // calls itself, Product() calls Products()... return (Sum(b, Product(a - 1, b))); }

vi) Passing Strings to functions. We are printing out addresses. If two variables are stored in the same memory address, then it is the same location. Otherwise, they are stored in different locations. Show the output and answer the questions.
#include <stdio.h> // function prototype void Call_It(int, char[ ]); void main(void) { int i = 5; char x[ ] = "AYOYO"; printf("i = %d, x = %s, &i = %p, &x[0] = %p\n", i, x, &i, &x[0]); // calling Call_It(), notice the array, just the array name... Call_It( i, x); printf("i = %d, x = %s, &i = %p, &x[0] = %p\n", i, x, &i, &x[0]); } // function definition void Call_It(int i, char z[ ]) { printf("\nIn Call_It(), i = %d, z = %s, &i = %p, &z[0] = %p\n", i, z, &i, &z[0]); i = 0; z[0] = 'M'; printf("In Call_It(), i = %d, z = %s, &i = %p, &z[0] = %p\n\n", i, z, &i, &z[0]); }

vii) When passing an array to a function, the changes the function may make will affect the first array because the function has the address of that array.
#include <stdio.h> // function prototype void AddOne(int, int[ ]); void main(void) { // local to main()... int i, a[4] = {20, 40, 10, 60}; printf("In main(), a = %p, &a[0] = %p\n", a, &a[0]); // call function AddOne()... AddOne(a[2], a); for(i = 0; i <= 3; i = i + 1) printf("a[%d] = %d\n", i, a[i]); } // function definition void AddOne(int one, int x[ ]) { // local to AddOne()... int i; printf("In AddOne(), x = %p, &x[0] = %p\n", x, &x[0]); for(i = 0; i <= 3; i = i + 1)

x[i] = x[i] + one; } a. Was a scalar or an array passed when main() passed a[2] to AddOne()? b. Was a scalar or an array passed when main() passed a to AddOne()? c. What was the array called in main()? d. What was the array called in AddOne()? e. When AddOne() changed the array x[ ] by adding 1 to it, did the array a[ ] change in main()? Why? f. Are the addresses stored in a and x different or the same?

Exercises (Functions)
Write two functions to calculate average of numbers given, one that returns value and another that doesnt return value. Use them in a main function appropriately. ii) Write recursive function to determine addition of two given values. iii) Write recursive function to calculate factorial of n, the given input value. Choose proper data type to handle large values. iv) Write iterative and recursive functions to generate nth number of the following Fibonacci series: 1 1 2 3 5 8 13 21 34 .. v) Write the following function and test it. The function should receive an array of floats and a scalar float (call it scalar). It should then print all the elements in the array greater than scalar. vi) The function should receive a character string. After counting the characters in the string until it finds the null character, it should print that count. For example, if main() passed starlight to the function, it should print its length, 9. vii) Write a function to receive an integer array with one number duplicated. The function should remove duplicates from it. Then print the final array, display the number duplicated. viii) The function called Swap() should receive two strings and exchange them. ix) The function called Swap() should receive two strings and exchange them without using third variable. i)

Sect.-VI.
i)

The information about a mobile contains its make-name as string, and its make year. We would like to store these four items together as one unit and to handle and process them together as a group. In order to do this we can use structure data type. Observe the methods of creation of structure, declaration of structure variables, accessing their member, and passing structure to function.
#include <stdio.h> #include <string.h> // Global definition struct Mobile { char Make[20]; int Year; }; // function prototype with structure return type struct Mobile FindYear(char Name[ ]); // function prototype with structures arguments passed void PrintOldest(struct Mobile Auto1, struct Mobile Auto2); void main(void) {

C Structure Type

struct Mobile Car1, Car2; Car1 = FindYear("Toyota"); Car2 = FindYear("Mustang"); PrintOldest(Car1, Car2); } // this function receives one string that is the make of a car, // reads in its year and returns them both as "struct Mobile" struct Mobile FindYear(char Name[ ]) { struct Mobile Car; printf("What year is the %s? ", Name); scanf("%d", &Car.Year); printf("Car.Year = %d\n", Car.Year); strcpy(Car.Make, Name); return Car; } // this function receives two structures of type "struct Mobile" // and prints the year of the oldest car. It returns nothing. void PrintOldest(struct Mobile Auto1, struct Mobile Auto2) { if(Auto1.Year < Auto2.Year) printf("The oldest car is the %s\n", Auto1.Make); else if(Auto1.Year > Auto2.Year) printf("The oldest car is the %s\n", Auto2.Make); else printf("They are both the same age!\n"); }

Exercises (Structures)
i) In the following program example enter Riders on the Storm and 3.10 for the sample input data. Show the output and answer the questions.
#include <stdio.h> #include <string.h> void main() { struct Song { char Name[25]; float Length; }; struct Song Title1, Title2; strcpy(Title2.Name, "My Teardrops"); Title2.Length = 2.35f; puts("Name your favorite song:"); gets(Title1.Name); puts("How long is it?"); scanf("%f", &Title1.Length); printf("\nMy song is %s\n Your song is ", Title2.Name); puts(Title1.Name); printf("Yours is %.2f min. longer \n", Title1.Length - Title2.Length); }

a. Can you print out both members of Title2 without specifying the b. c.
member names as shown below? Does this work? printf("%s %.2f\n", Title2); Can you assign Title2 to Title1 without specifying their members as shown below? Does this work? Title1 = Title2; Does the following code work? Why or why not? Title1.Name = Title2.Name

Sect.-VI.

C Pointers

Variables that store memory addresses instead of the actual data or values are called pointers. i) An example of the pointer variable and its usage is shown below.
#include <stdio.h> #include <string.h> void main() {

int i, *p; i = 60; // storing an integer value p = &i // storing an address of an integer variable char a[1], *pa; float x, *px; pa = &a[0]; // storing a character address in a character pointer. px = &x; // storing a float address in a float pointer // the following two statements will generate compilation time error; try then remove. pa = &x; // pa is not a pointer variable for floats. px = 3.40; // px cannot store floating point values! // now try following a[0] = r; x = 5.5; printf (i = %d, a[0] = %c, x = %f ,*p, *pa, *px); // accessing values of I, a[0] and x through respective pointers. }

ii) Remember that &i will give the address of variable i. Build and run the following program, show the output and answer the question.
#include <stdio.h> void main(void) { int i = 7, j = 11; printf("i = %d, j = %d\n", i, j); printf("&i = %p, &j = %p\n", &i, &j); }

iii) Arrays And Pointers Relation:-- When arrays are defined, the array name actually holds the starting address of the array.
#include <stdio.h> // function prototype void ReadArr(int *x, int y); void main(void) { // p used to store addresses for array j[ ]. int i, j[5], *p; // q used to store addresses for array x[ ] float x[5], *q = &x[0]; // printing out the addresses of the two arrays. p = &j[0]; // line 1 for(i = 0; i <= 4; ++i) printf("Addresses of j[%d] = %p\tAddresses of x[%d] = %p \n", i, p + i, i, &q[i]); // reading numbers into the integer array. printf("\nEnter 5 integers\n"); // for older compiler may use scanf("%d", &j[4]); etc // notice there is no & scanf_s("%d", &j[4], 4); scanf_s("%d", j, 1); scanf_s("%d", j + 1, 1); // j can't change and it hasn't p = &j[1]; // same as p = j + 1; p = p + 1; // notice there is no & scanf_s("%d", p, sizeof(int)); ReadArr(j, 3); // print the array printf("The array is: \n"); for(i = 0; i <= 4; ++i) printf("j[%d] = %d ", i, j[i]); printf("\n"); } // function definition, to read a number into x[y] // receive a pointer integer and integer arguments // return nothing... void ReadArr(int *x, int y) { x = x + y; scanf ("%d", x); }

Exercises (Pointers)
i) Build and run the following program, show the output and answer the questions.
include <stdio.h> void main(void) { int i = 7, j = 11;

printf("i = %d, j = %d\n", i, j); printf("&i = %p, &j = %p\n", &i, &j); // reassign new values... i = 4; j = 5; // reprint... printf("\ni = %d, j = %d\n", i, j); printf("&i = %p, &j = %p\n", &i, &j); }

ii)

a. After the initialization statement, were we able to change the values of the variables? b. After the assignment statements, were we able to change the addresses of the variables? Try &i = 4; c. Now at the end of main(), add the following statement and try running it: j = &i; Were we able to store the address of i into j? Pointer Arithmetic: Show the output and answer the questions for the following exercise.
#include <stdio.h> void main() { int i = 56, *p1; // Statement 1 p1 = &i; // Statement 2 *p1 = *p1 + 1; // Statement 3 printf("i = %d, *p1 = %d, p1 = %p\n", i, *p1, p1); }

a. b. c. d. e.

p1 has what address in it? p1 points to which variable? p1 points to what value? In Statement 3, the value in which address is changed? In Statement 3, 1 is added to the value in which address?

iii) Show the output of the following questions.


#include <stdio.h> void main(void) { char a = 'Q', *pa; // the F modifier force the value to float // else by default it is a double float x = 7.3F, *px; int i = 2, *m; pa = &a; px = &x; m = &i; printf("pa = %p\npx = %p\n m = %p\n", pa, px, m); }

a. Out of the six variables declared, which may store addresses? b. In the following Figure, show the values of a, x and i. c. From the output, show the (address, values) of a, pa, x, px, i, and m. d. Now that you know the values of pa, px and m, what are the addresses of a, x, and i? Show them in the Figure. e. Must variable that store addresses begin with the letter p? If not, how can we tell from the declaration of these variables that they can store addresses? f. Which variable(s) may store only (single) characters? g. Which variable(s) may store addresses to characters? h. Can you store the address of a float in pa? Can you store the address of an integer in pa? If not, what error or warning message is obtained? For example: pa = &x; pa = &i; i. Can you store a character in pa? If not, what error message is obtained? pa = 'Q';

j. Can you change the address of a variable? If not, what error message
is obtained? &a = 4440;

k. Try storing the addresses of a and i in px. Does px hold the addresses
of floats only? px = &a; px = &i; l. Try storing the addresses of a and x in m. Does m hold the addresses of integers only? m = &a; m = &x; iv) Write a function Swap that takes two addresses and exchanges the values of the locations.

Vous aimerez peut-être aussi