Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

CSC103 - LabManual (For Students)

Download as pdf or txt
Download as pdf or txt
You are on page 1of 20

Course: CSC141-Introduction To Computer Programming (With Solutions)

List of practices/Lab Tasks


WEEK Topics Page no.
Week 1 & 2 The Programming Environment 3
Week 3&4 Basic Decision Constructs and for loop 8
Week 5 while Loops & Sentinel Controlled Repetition 13
Week 6&7 Functions 17
Week 8 Manipulating Arrays 22
Week 9 Pointers Notations and Arrays 25
Week 10 Pointers 28
Week 11 Strings 31
Week 12&13 structs 34
Week 14&15 File management 36

CSC141 Introduction to Computer Programming -Lab Page 2 o


CSC 103 – Programming Fundamentals Lab
Week1&2: The Programming Environment

Learning Objectives:

The objectives of this first experiment are:

1. To make you familiar with the Windows programming environment and the "C"
compiler. For this purpose you will use DevCPP/Code Blocks. You will write, compile and
run a (it may be your first) program in "C"
2. To get you to write several simple algorithms using flowcharts

Your lab report is expected to contain the following for each exercise:

• Flowcharts
• C Source Code

Exercise 1: Print following shape using simple printf statements

(1) (2) (3) (4) (5) (6)

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


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

Exercise 2: Write a C-Program to perform the simple arithmetic operations (addition,


subtraction, multiplication, division, remainder).

Exercise 3: Write a C-Program to swap two integer numbers without and with using third
variable.

CSC141 Introduction to Computer Programming -Lab Page 3 o


Exercise 4: Write a C-Program to calculate area and Perimeter of the triangle and rectangle.
[Area of triangle= ½ x base x vertical height , Perimeter of triangle = a + b + c]
[Area of rectangle= width x height , Perimeter of rectangle = 2( a + b)]

Start

Declare variable base, vh


and tarea

Calculate area of triangle


tarea = 0.5 * base * vh

Print area of triangle


triangle

End

CSC141 Introduction to Computer Programming -Lab Page 4 o


CSC 103 – Programming Fundamentals Lab
Week 3&4: Basic Decision Constructs and for loop

Learning Objectives: The objective of this exercise is to get you to write, compile and run a
number of simple programs in C which make use of basic decision constructs and for loops.

OBS: For each exercise you need to write the flowchart before translating it to your C
program. Your programme should print “Programme written by <your name>” at the end of
the programme on the screen.

Exercise 1: Write a program that reads 10 positive numbers from the keyboard and determines
and displays the sum and average of the numbers.

CSC141 Introduction to Computer Programming -Lab Page 5 o


Exercise 2: Print the following series using for loop

a. Print numbers from 1 to 100 with increment of 1


b. Print numbers from 100 to 1 with decrement of 1
c. Print numbers from 20 to 2 in steps of -2
d. Print sequence of numbers: 2, 5, 8, 11, 14, 17, 20
e. Print sequence of numbers: 99, 88, 77, 66, 55, 44, 33, 22, 11, 0

Exercise 3: Write a program that reads in five integers and then determines and prints the
largest and smallest integers in the group. Use only the techniques you have learnt so far, and
make sure that the program only uses three variables. (Hint: use two of the variables to hold
the current largest and smallest integers.)

Exercise 4: Write a program that reads a number and determines and prints whether it is odd
or even. (Hint: use the modulus operator. Any even number is multiple of two, and any multiple
of two gives a remainder of zero when divided by two.)

Exercise 5: Write a program which asks the user to enter 10 numbers and prints out the
message “even” if the number is even and “divisible by three” if the number is divisible by
three.

Exercise 6: A person invests $1000.0 in a savings account yielding 5% interest. Assuming that all
interest is left on deposit in the account, calculate and print the amount of money in he account
at the end of each year for 10 years. Use the following formula for determining these amounts:
a = p(1+r)n
where
p is the original investment(i.e. the principal)
r is the annual interest rate
n is the number of years
a is the amount on deposit at the end of the nth year.

Sample output

Year Amount on deposit


1 1050.00
2 1102.50
3 1157.63

CSC141 Introduction to Computer Programming -Lab Page 6 o


4 1215.51
5 1276.28
6 1340.10
7 1407.10
8 1477.46
9 1551.33
10 1628.89

CSC141 Introduction to Computer Programming -Lab Page 7 o


CSC 103 – Programming Fundamentals Lab
Week 5: while Loops & Sentinel Controlled Repetition

Learning Objectives: The objective of this exercise is to get you to write, compile and run more
complex programs in C which make use of while loops and sentinel-controlled repetition.

OBS: For each exercise you need to draw the flowchart before translating to your C prog ram.

Exercises: For each question:


(a) Read the problem statement
(b) Write a C program
(c) Test, debug, and execute the C program.

Exercise 1: Because of the high price of petrol, you are concerned with the fuel consumption of
your car. As a result you have a record of the kilometres driven and litres used for each tank of
petrol you purchase. Write a program that will display the kilometres driven, litres used, and
consumption (in litres/100km) for each tankful. After processing all the input information, the
program should calculate the overall average consumption:

Enter the litres used (-1 to end): 57.6


Enter the kilometres driven: 459
The litres/100km for this tank was 12.5
Enter the litres used (-1 to end): 45.3
Enter the kilometres driven: 320
The litres/100km for this tank was 14.2
Enter the litres used (-1 to end): -1
The overall average consumption was: 13.4

Exercise 2: Write a C program that uses a while loop to calculate and print the sum of the even
integers from 2 to 30.

Exercise 3: Write a C program that uses a while loop to calculate and print the product of the
odd integers from 3 to 19.

CSC141 Introduction to Computer Programming -Lab Page 8 o


Exercise 4: Write a program that reads in a four-digit number, separates the number into its
individual digits and prints them separated by three spaces. Thus given the number 4233, the
program should print:
4 2 3 3

Exercise 5: Write a C program that will determine if a department store customer has exceeded
the credit limit on a charge account. For each customer, the following facts are available:
1. Account number
2. Balance at beginning of month
3. Total of all items charged by the customer this month
4. Total of all credits applied to the account this month
5. Allowed credit limit
The program should input each of these facts, calculate the new balance (initial balance +
charges - credits) and determine if the new balance exceeds the credit limit. If it does, a suitable
message should be displayed.

Enter account number (-1 to end): 100


Enter initial balance: 5394.78
Enter total charges: 1000
Enter total credits: 500.00
Enter credit limit: 5500.00
Account: 100
Credit limit: 5500
Balance: 5894.78
Credit Limit Exceeded

Enter account number (-1 to end): 200


Enter initial balance: 1000.00
Enter total charges: 123.45
Enter total credits: 321.00
Enter credit limit: 1500.00
Account: 200
Credit limit: 1500
Balance: 802.45

Exercise 6: A large chemical company pays its sales staff on a commission basis. They receive
£200 per week plus 9% of their gross sales for that week. For example, someone who sells
£5000 of chemicals in one week will earn £200 plus 9% of £5000, a total of £650. Develop a C
program that will input each salesperson’s sales for the previous week, and print out their
salary. Process one person’s figures at a time.

CSC141 Introduction to Computer Programming -Lab Page 9 o


Enter sales in pounds (-1 to end): 5000.00
Salary is: 650.00
Enter sales in pounds (-1 to end): 00.00
Salary is: 200.00
Enter sales in pounds (-1 to end): 1088.89
Salary is: 298.00
Enter sales in pounds (-1 to end): -1

CSC141 Introduction to Computer Programming -Lab Page 10


CSC 103 – Programming Fundamentals Lab
Week 6&7: Functions

Learning Objectives: The objective of this exercise is to get you to write, compile and run a
number of programs in C which make use of simple functions.

OBS: For each exercise you need to write the C program and after running your program you
need to show the screen results to the instructor.

Exercise 1: Recall the programme you wrote to implement a simple calculator now rewrite the
same programme using functions.

Exercise 2: Write a program that uses six calls to the function rand() to generate six random
integer numbers, num1, num2, num3, num4, num5, and num6, and then print them out.
num1 should be in the range 1 to 2 (inclusive), num2 should be in the range 1 to 100 (inclusive),
num3 should be in the range 0 to 9, num4 should be in the range 1000 to 1112 (inclusive),
num5 should be in the range -1 to 1, and num 6 should be in the range -3 to 11.

Exercise 3:A car park charges a £2.00 minimum fee to park for up to 3 hours, and an additional
£0.50 for each hour or part hour in excess of three hours. The maximum charge for any given
24-hour period is £10.00. Assume that no car parks for more than 24 hours at a time.
Write a C program that will calculate and print the parking charges for each of 3 customers who
parked their car in the car park yesterday. The program should accept as input the number of
hours that each customer was parked, and output the results in a neat tabular form, along with
the total receipts from the three customers:

The program should use the function calculate_charges to determine the charge for each
customer.

Exercise 4:Implement the following functions. The functions return a real number:
(a) Function Celsius returns the Celsius equivalent of a Fahrenheit temperature (Hint: 0 Celsius
is equal to 32 Fahrenheit and 100 Celsius is equal to 212 Fahrenheit).

CSC141 Introduction to Computer Programming -Lab Page 11


(b) Function Fahrenheit returns the Fahrenheit equivalent of a Celsius temperature. Use these
functions to write a program that prints charts showing the Fahrenheit equivalent of all Celsius
temperatures between 0 and 100 degrees, and the Celsius equivalent of all Fahrenheit
temperatures between 32 and 212 degrees. Print the output neatly in a table.

Exercise 5:The greatest common divisor of integers x and y is the largest integer that divides
both x and y. Write a recursive function GCD that returns the greatest common divisor of x and
y. The GDC of x and y is defined as follows: If y is equal to zero, then GDC(x, y) is x; otherwise
GDC(x, y) is GDC(y, x % y) where % is the remainder operator.

CSC141 Introduction to Computer Programming -Lab Page 12


CSC 103 – Programming Fundamentals Lab
Week 8: Manipulating Arrays

Learning Objectives: The objective of this exercise is to get you familiar with the collection of
data of same type and manipulate it using arrays.

OBS: For each exercise you need to write the C program and after running your program you
need to show the screen results to the instructor.

Exercise 1:Write a program to declare an integer array of 50 elements.

A. Write a function getArray() to get array input from the user that will be used to initialize the first
thirty five (35) elements of the array by getting input from the user. The rest of the 15 entries would
be set to zero (0).
B. Write a function FindEven() to find the total numbers of even numbers in the given array.
C. Write a function ModifyArray() to make the each array element to a multiple of four(04).
D. Write a function named ‘FindMin()’ that will find the smallest element in the given array and return
the smallest element.

Exercise 2: Develop a program to calculate the basic salary of 5 employees where the hourly rate and
the no. of hours worked by each employee are given by the user.

Note: Formula for calculating the basic salary = no. of hours worked * hourly rate.

Exercise 3: Develop a program to input the marks of 10 (ten) different subjects of a student through the
keyboard, find out the aggregate marks and percentage marks obtained by the student. Assume that the
maximum marks that can be obtained by a student in each subject is 100.

CSC141 Introduction to Computer Programming -Lab Page 13


CSC 103 – Programming Fundamentals Lab
Week 9: Pointers Notations and Arrays

Learning Objectives: The objective of this exercise is to get you familiar with pointers, different
pointer referencing techniques and array traversing using pointers
OBS: For each exercise you need to write the C program and after running your program you
need to show the screen results to the instructor.
Exercise 1. Given the following piece of code

int i = 10;
char c= 'A';
double f = 25.5;
int *iptr = &i;
char *cptr = &c;

You are expected to display the result of following statements in the given format.

Value of i Address of i Value of Address Derefrenced Size of iptr Size of i


iptr of iptr Value of *iptr

Value of c Address of c Value of Address Derefrenced Size of cptr Size of c


cptr of cptr Value of *cptr

Note: The format specifier for displaying address of any data item is %x

Exercise 2

Implement the swap function to exchange the contents of the two variables using pointer
notation for parameter passing.

CSC141 Introduction to Computer Programming -Lab Page 14


Exercise 3

Consider the following array of integers:

Array of integers, named ‘arr’


2 6 -4 8 10 -12 14 16 18 20
num[0] num[1] num[2] num[3] num[4] num[5] num[6] num[7] num[8] num[9]

Implement the following pointer notations to traverse and display the given array ‘arr’.
1. Printing array using array[i] notation.
2. Printing array using ptr[i] notation.
3. Printing array using *(array+i) notation.
4. Printing array using *(ptr+i) notation.
5. Printing array using *ptr notation.

CSC141 Introduction to Computer Programming -Lab Page 15


CSC 103 – Programming Fundamentals Lab
Week 10: Pointers

Learning Objectives: The objective of this exercise is to get you to write, compile and run a
number of simple programs in C which make use ofpointers.

OBS: For each exercise you need to write the C program and after running your program you
need to print the screen results.

Exercise 1: When variables are declared, are they located in memory contiguously? Write a
program with the declaration: char a, b, c, *p, *q, *r;
And print out the locations (addresses) that are assigned to all these variables by your
computer. Are the locations in order? If the locations are in order, are they increasing or
decreasing? Is the address of each pointer variable divisible by 4? If so, this probably means
that each pointer value gets stored in machine word. Double check the results using sizeof() for
char and for char*. (Hint: if you want to see addresses printed as decimal numbers rather than
hexadecimals, it is usually safe to cast an address as unsigned long and use the %lu format).

Exercise 2:Write, compile and execute the program below. Explain why the function swap does
not work properly. Using pointers, change the program to make the function swap to work
properly.

CSC141 Introduction to Computer Programming -Lab Page 16


#include <stdio.h>
#include <stdlib.h>
void swap (int a, int b);
int main()
{
int c = 10, d = 25;
printf("\nBefore calling the function swap, c=%d and d=%d", c, d);
swap(c,d);
printf("\nAfter calling the function swap, c=%d and d=%d\n", c, d);
return 0;
}
void swap(int a, int b)
{
int temp;
temp = a;
a = b;
b = temp;
}

Exercise 3: Write a program that reads 8 floating point values into an array and then prints out
the second, fourth, sixth and eighth members of the array, and the sum of the first, third, fifth
and seventh, using pointers to access the members of the array.

CSC141 Introduction to Computer Programming -Lab Page 17


CSC 103 – Programming Fundamentals Lab
Week 11: Strings

Learning Objectives: The objective of this exercise is to get you to write, compile and run a
number of simple programs in C which make use ofstrings.

OBS: For each exercise you need to write the C program and after running your program you
need to print the screen results.

Exercise 1: Write a programme which should take an organization name from the user and then
print the abbreviation on the screen.

E.g. Organization Name is Pakistan Steel and its abbreviation is PS

Exercise 2: Write code forthe following functions:

1. int strlen(const char *s); [returns string length]


2. char* strcpy(char *s1, const char *s2); [Copies string s2 into array s1. The value of s1 is
returned.]
3. char* strcat(char *s1,const char *s2); [Appends string s2 to array s1. The first character
of s2 overwrites the terminating nullcharacter of s1. The value of s1 is returned.]

Use above function in your program to get and print length of a string, copy str1 to str2 and
append str2 at the end of str1. Do not use string.h header file in your programme.

CSC141 Introduction to Computer Programming -Lab Page 18


CSC 103 – Programming Fundamentals Lab
Week 12&13: Structures
Learning Objectives: The objective of this exercise is to get you to write, compile and run a
number of simple programs in C which make use ofstructure.

OBS: For each exercise you need to write the C program and after running your program you
need to print the screen results.

Exercise 1: Write a C Program to create the data for some students (roll, name, mark1, mark2,
mark3) and then find the total marks for each student and average mark of each student:

CSC141 Introduction to Computer Programming -Lab Page 19


CSC 103 – Programming Fundamentals Lab
Week 14&15: File management

Learning Objectives: The objective of this exercise is to get you to write, compile and run a
number of simple programs in C which use file management.

OBS: For each exercise you need to write the C program and after running your program you
need to print the screen results.

Exercise 1: Write a C Program to open a file named “DATA” and write a line of text in it by
reading the text from the keyboard.

Exercise 2: Write a C Program to read the contents of file ‘File1’ and paste the contents at the
beginning of another file ‘File2’.

Exercise 3: Write a C Program to count the number of characters and spaces in the input
supplied from a file.

CSC141 Introduction to Computer Programming -Lab Page 20

You might also like