0% found this document useful (0 votes)
23 views10 pages

PI Practical 01 2324

This practical introduces students to programming in C language on Linux. The main goals are to practice editing, compiling, and running C programs; learn keyboard input and screen output functions like scanf() and printf(); and work with basic data types in C. Students will complete 10 exercises that involve writing, compiling, and running short programs that perform tasks like calculating the square root of a number, converting characters to uppercase, finding the length of a string, and calculating the area and perimeter of a triangle based on user input dimensions. The practical also provides optional advanced tasks for students to further study Linux commands, experiment with emacs features, and design algorithms and flowcharts.

Uploaded by

jaka18
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views10 pages

PI Practical 01 2324

This practical introduces students to programming in C language on Linux. The main goals are to practice editing, compiling, and running C programs; learn keyboard input and screen output functions like scanf() and printf(); and work with basic data types in C. Students will complete 10 exercises that involve writing, compiling, and running short programs that perform tasks like calculating the square root of a number, converting characters to uppercase, finding the length of a string, and calculating the area and perimeter of a triangle based on user input dimensions. The practical also provides optional advanced tasks for students to further study Linux commands, experiment with emacs features, and design algorithms and flowcharts.

Uploaded by

jaka18
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

Computer Programming I

Practical #1 Academic year 2023-2024 1st year

Getting started with C

In this practical, we will continue working with the tools available Aims
in the Linux operating system. •••
The main goals of this prac-
We will also keep on learning how to use the basic tools for coding
tical are:
our programs in C language: emacs and gcc.
- Keep on getting familiar
In addition, we will start to handle the basic mechanisms provided with the laboratory work-
by the C language libraries for: space.
- Keep on learning how to
• Entering information from the keyboard, by means of the scanf() use the most basic Linux
function, and Operating System com-
• Displaying information to the screen, by means of the printf() mands.
function. - Consolidate the necessary
steps for editing, compiling
Finally, we will introduce some of the data types in C: the integer and executing a C program.
types and the strings of characters. - Get acquainted with C in-
put/output mechanisms.
- Get familiar with some C
data types.

Scheduling

Laboratory Session #1 (6 hours):


1. Carry out the exercises #1 and #2.
2. Carry out the exercises #3 and #4.
3. Carry out the exercises #5 and #6.
4. Carry out the exercise #7.
5. Carry out the exercises #8 and #9
6. Carry out the exercise #10
Outside the classroom work:
- Finish those exercises that were not completed in the laboratory.
- Carry out the flowcharts indicated in Appendix I.
- Design and code the programs indicated in Appendix II.

1
Coding a basic program in C

Modifying a program

In order to modify the behaviour of a program we must modify the file containing its source code (using
the editor) and, after that, compile it again (using the compiler).

Exercise #1:
Create a directory called pr01 in your account (if not previously created).

Move to that directory and use the shell cp command to make a copy of ex3.c exercise from the previous
practical:

user@machine:~/pr01$ cp ../pr00/ex3.c ex1.c

Modify the previous exercise program by eliminating the final "\n".

Run it and check the meaning of those characters.

We can also use a program’s source code as the basis for creating a new one.

Exercise #2:
user@machine:~/pr01$ cp ../pr00/ex3.c ex2.c

Modify your program so it prints two lines. The first one must say "Goodbye", and the second one "See
you".

Compilation errors

When we make a coding mistake in our source code, the executable file will not be generated and the
compiler will point out the error or errors it has found, that have stopped the compilation.

Exercise #3:
user@machine:~/pr01$ cp ex2.c ex3.c

Erase the final ";" in one statement in the previous exercise source code. Test what happens when you try
to compile the program.

2
Type conversion

In these exercises we will start practicing with the automatics conversions among the numerical data
types (double, float, int and short) and their implications: what if we assign to a given type variable a
value from another type?

Exercise #4:
Carry out the following steps:

1. Write a program:

user@machine:~/pr01$ emacs ex4.c &

with the following code:


#include <stdio.h>

int main (void) {

int integer;
float real;

integer = 4;
real = integer/5;
fprintf (stdout, "Quotient = %.2f\n", real);

real = (1.0*integer)/5;
fprintf (stdout, "Division 1 = %.2f\n", real);

real = integer/5.0;
fprintf (stdout, "Division 2 = %.2f\n", real);

real = 4.7;
integer = real;
fprintf (stdout, "Integer = %d\n", integer);

return 0;
}

2. Run the program and justify the results.

3
Exercise #5:
Carry out the following steps:

1. Write a program:

user@machine:~/pr01$ emacs ex5.c &

with the following code:


#include <stdio.h>

int main (void) {


short short_integer = 30000;
int integer = 3000000;
float real = 3e9;

fprintf (stdout, "short_integer: %d\n", short_integer);


fprintf (stdout, "integer: %d\n", integer);
fprintf (stdout, "real in floating point: %.2f\n", real);
fprintf (stdout, "real in scientific notation: %.2e\n\n", real);

short_integer = integer;
fprintf (stdout, "short_integer: %hd\n", short_integer);

integer = real;
fprintf (stdout, "integer: %d\n\n", integer);

integer = 3000000;
real = integer;
fprintf (stdout, "integer: %d\n", integer);
fprintf (stdout, "real: %.2f\n\n", real);

integer = 1234567892;
real = integer;
fprintf (stdout, "integer: %d\n", integer);
fprintf (stdout, "real: %.2f\n", real);
fprintf (stdout, "real: %.9e\n", real);
return 0;
}

2. Run the program and justify the results.

4
Exercise #6:
Carry out the following steps:

1. Write a program:

user@machine:~/pr01$ emacs ex6.c &

with the following code:


#include <stdio.h>

int main (void) {


float real;
double real_double;

real = 25.50;
real_double = 25e+100;
real = real_double * real;
fprintf (stdout, "Using float: %.2f\n\n", real);

real = 25.50;
real_double = real_double * real;
fprintf (stdout, "Using double: %.2f\n", real_double);
fprintf (stdout, "In scientific notation: %.4e\n\n", real_double);
return 0;
}

2. Run the program and justify the results.

5
Developing simple programs

Data reading and writing

In these exercises, we will learn the use of the basic functions for keyboard data input, fscanf(), and
screen data output, fprintf().

In addition, we will learn how the use of library functions facilitates the fulfilment of many operations.

Exercise #7:
Write a program:

user@machine:~/pr01$ emacs ex7.c &

This program, first, asks the user to enter an integer number, for which it makes use of scanf() or
fscanf() function:

Enter an integer: 75

And, then, calculates the square root of the number (this will be a real number) and prints the result in
the screen, with the following format, for which it makes use of printf() or fprintf() function:

ROOT: 8.66

That is, right aligned, in a 10-character wide field, and with 2 decimal digits.

In order to solve this exercise, we need to make use of the sqrt() (square root) function from the mathe-
matical function library. Read the manual page for this function:

user@machine:~/pr01$ man sqrt

Exercise #8:
Write a program:

user@machine:~/pr01$ emacs ex8.c &

This program, first, asks the user to enter a character:

Enter a character: w

And, then, converts it to uppercase and displays it in the screen:

Letter w capitalised is W

In order to solve this exercise, we need to make use of the toupper() function from the string library.

user@machine:~/pr01$ man toupper

6
Exercise #9:
Write a program:

user@machine:~/pr01$ emacs ex9.c &

This program, first, asks the user to enter a string of characters:

Enter a string: Programming

And, then, calculates its length and prints the result in the screen:

The string is 11 characters long

In order to solve this exercise, we need to make use of the strlen() function from the string library.

user@machine:~/pr01$ man strlen

Exercise #10:
Write a program:

user@machine:~/pr01$ emacs ex10.c &

This program first asks the user to enter the base and height of a right-angled triangle:

Enter the base: 15


Enter the height: 9

And then, calculates its area and perimeter and prints the result in the screen, with the following format:

Height: 9 cm
Base: 15 cm
Area: 67.50 cm x cm
Perimeter: 41.49 cm

Make sure that all the results are correctly aligned. The base and the height must be positive integers.

This exercise is greatly simplified using the sqrt() function from the mathematical function library.

Summary

The main results expected from this practical are:


- To edit, compile and run programs in C.
- To know the keyboard input and screen output mechanisms in C.
- To work with the basic data types in C language.

Optional advanced tasks for the student:


- Try to study in more depth the basic Linux commands.
- Experiment with the different functionalities provided by emacs via its menus.
- Practise the elaboration of flowcharts and the coding of simple programs, as the ones proposed in Annexes I and II.

7
Appendix I. Exercises on algorithms and flowcharts
Point out the algorithm steps and sketch the flowchart1 for the following problems (in all cases, the input
data are requested by keyboard to the user and the result is shown in the screen):

1. Average value of 2 integers.


2. Calculation of the area and the perimeter of a right-angled triangle.
3. Addition of 10 numbers.
4. Multiplication of 2 positive integers by means of additions.
5. Division of 2 positive integers by means of subtractions. Calculation of quotient and remainder.
6. Writing of the first N even numbers. The N value is the input data of the problem.
7. Calculation of 2N, being N an integer ≥ 0.
8. Calculation of maximum of an undetermined size set of positive numbers. The user indicates the end by typing a
negative number.
9. Given 3 numbers, show them sorted from biggest to smallest.
10. Calculation of the percentage of even numbers in a set of N positive numbers.
11. Average of an undetermined size set of positive numbers. The user indicates the end by typing a negative number.
12. Reading of 10 integer numbers and calculation of the product of the odd ones.
13. Given a year, determine if it is a leap year or not.
14. Given a 3 digits number, determine if it is a palindrome.
15. Calculation of the VAT included price of a given item, from the VAT excluded price. Write the result with 2 deci-
mal digits.
16. Given a character, determine if it is a letter, a digit, or none of them.
17. Calculation of a triangle’s hypotenuse given both cathetus.
18. Given the midterm tests grade (NPP) and the final theory test grade (ETF) in Computer Programming I, calculate
the minimum grade needed in the final laboratory test (EFL) to pass the subject.
19. Given 2 integer numbers, determine if the first one is a multiple of the second one.

1 You can use a tool like DIA (http://live.gnome.org/Dia/), or PowerPoint, or you can even draw it by hand.
8
Appendix II. Programming exercises
Write C programs that perform the necessary operations to solve the following problems (in any of
them, before starting coding, sketch the flowchart):

Ask the user to enter a real number and show double its value and half its value in the screen, with the pertinent
messages.

1. Ask the user to enter a character and show the previous and the following character in the screen, with the pertinent
messages.
2. Given 2 points (ask the user to enter the pairs (x1, y1) and (x2, y2)) calculate the distance between them. For doing
so, you can use the sqrt() function from the mathematical functions library. Print the result, according to the fol-
lowing format:

(X1,Y1) = (5,6)
(x2,y2) = (5,4)

Distance = 2

3. Ask the user to enter an integer number between 1 and 10 and show the multiplication table for that number correctly
aligned
4. Ask the user to enter an amount in euros and calculate its equivalent in pesetas, dollars and pounds. Make sure that
all the results are correctly aligned.

Version 1: Using integer numbers.

#define PTSINEACHEURO 166


#define PTSINEACHPOUND 213
#define PTSINEACHDOLAR 123

Version 2: Using real numbers.

#define PTSINEACHEURO 166.386


#define EUROSINEACHPOUND 1.285
#define EUROSINEACHDOLAR 0.737

5. Ask the user to enter 2 real numbers and show the addition, subtraction and product of those numbers. Make sure
that all the results are correctly aligned.
6. Ask the user to enter the cost of a sold item and the amount of money handed over by the customer. Calculate and
show the change that must be returned. Show the result with 2 decimal digits.
7. Ask the user to enter the radius of a circle (real type variable), calculate and show both its area and its circumference
length. Show the result with 3 decimal digits. What if the user types an alphabetic word instead of a number?
8. In the winter Olympics the time spent by the participants in the track speed skating competition is measured in
minutes, seconds and centesimal. The course distance is expressed in meters. Calculate the average speed of the
participants in kilometres/hour from the data previously indicated. Show the result with 2 decimal digits. What if the
user types more than one space between the numbers?
9. Solve a linear equations system (ask the user to enter the values for A1, A2, B1, B2, C1 y C2):
𝐴! 𝑥 + 𝐵! 𝑦 = 𝐶!
𝐴" 𝑥 + 𝐵" 𝑦 = 𝐶"
We will use the Cramer’s rule:

9
𝐶 𝐵! 𝐴 𝐶!
$ ! $ $ ! $
𝐶 𝐵" 𝐴 𝐶"
𝑥= " 𝑦= "
𝐴 𝐵! 𝐴! 𝐵!
$ ! $ $ $
𝐴" 𝐵" 𝐴" 𝐵"
Thus, the values to be computed are:
𝑥 = ((𝐶1 ∗ 𝐵2 ) − (𝐶2 ∗ 𝐵1 )) / ((𝐴1 ∗ 𝐵2 ) − (𝐴2 ∗ 𝐵1 ))
𝑦 = ((𝐴1 ∗ 𝐶2 ) − (𝐴2 ∗ 𝐶1 )) / ((𝐴1 ∗ 𝐵2 ) − (𝐴2 ∗ 𝐵1 ))

10. Ask the user to enter a number of days. Calculate and print the number of hours, minutes and seconds in the given
number of days. Make sure that all the results are correctly aligned. What if the user types an alphabetic word instead
of a number?
11. Ask the user to enter a 4 digit integer, and generate the following printing pattern (if the typed number is 1234):
1234
234
34
4
What if the user types an alphabetic word instead of a number?

12. Ask the user to enter the edge of a cube (real variable), calculate the base area, the lateral area and the total surface
area. What if the user types letters instead of digits?
13. Ask the user to enter a date (year, month, day) and calculate the number of seconds elapsed from January 1, 1970 to
the given date. Consider in both dates that the starting hour is 00:00.
14. Ask the user to enter the successive ales revenues of a department store from Monday to Saturday. Calculate the
weekly average.
15. A runner participating in Vig-Bay (21.5 km) wants to know his/her statistics after the race. The program must ask
the user to enter the following data:
• Starting time: hour, minutes, seconds.
• Finish time: hour, minutes, seconds.
The program must show as a result:
• His/her average speed, expressed in km/h, with 1 decimal digit (example: 11.3 km/h)
• His/her average running pace, expressed as minutes per km, with the MIN:SEC format (example: 5:19
min/km).

10

You might also like