0% found this document useful (0 votes)
22 views28 pages

Tut & Prac Exercises PT 1

Uploaded by

weixiaohan001
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)
22 views28 pages

Tut & Prac Exercises PT 1

Uploaded by

weixiaohan001
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/ 28

EE1005 From Computational Thinking to Programming

Tutorial and Practical Lesson 1 (Week 2)


Introduction to Computers and Programming

1. Answer the following short questions: calculation and


other Computational
(a) CPU stands for Central Processing Units .
they act as fast Volatile
(b) What are registers in a CPU? →access volatile vs Non
-

memory for
(c) Which CPU component performs calculations? Expensive cheaper
(d) Which CPU component makes logical decisions? / computation Reading
(e) What are the differences between RAM and ROM? storing
because main memory critical
(f) Why is secondary storage needed? -
is volatile and expensive information
(g) Name three commonly used operating systems.
(h) The only language that the computer can directly “understand” is called
that computer's machine language .
(i) What does IDE stand for? error in logic
in different
.

Integrated development resulting


output from desired
environment →

outcome
2. (a) Explain syntax error, logical error, and runtime error. the
→ will compiler
(b) grammatical
What processes are needed to transform a C source program into athe code translate
we
machine language program that is ready for execution? write -10 Machin

(c) If you have the .exe file of a program you have written yourself, dolanguage for the
Pc to understand
210--1024 you need to keep the source program and the .o file? Discuss. the linker will then
proceed to link

210 bytes3.→ K (a) Write an algorithm to find the maximum of three numbers a, b and c. component
the
together with
220bytes → in(b) Modify your algorithm so that it finds the minimum of three numbers.
the other Hb
230bytes → Gi (c) Repeat parts (a) & (b) for four numbers. Do you think your algorithm
is satisfactory for more numbers (e.g., 100 numbers)? If not, how
[RAM] should you modify it?
random (d) Write an algorithm to solve the quadratic equation ax 2 bx c 0, given
access a
memory the coefficients a, b, and c.
store holds CPU
1. instructions
Hardware located

2. Data to manipulate →at motherboard
3-
Processing results Main
memory
-

/
1
-

Secondary memory _ outside


byte = 8
bits of motherboard

Address
hell = unique
> address Buses act as a middleman
>
can hold 1 byte to interconnect hardware
data
address
control
t g- ×

{
Arithmetic
= -

ALU =

fast access logic


= And OR

using register 1 control = Control flow of data


instructions and
Unit
a

(1)
b. Registers are the memory cells the CPU that allow rapid access of instructions and data
by the ALU and the control unit .

c. Arithmetic logic unit


d. Arithmetic logic Unit
e. RAM → Random access memory
ROM → Read only memory
Differences
-
ROM
-
RAM
1. stores Data
1. stores Data
temporarily [ volatile ]
permanently
2. Cannot be modified 2. High speed for storing instructions and data
3. Usually used for boot
easily
instructions
up and critical system

f. Secondary storage is needed to store permanent data and because RAM is expensive
g. Linux window Mac 0s
, ,

h Machine
.
language
b. Integrated
development Enviro merit

2a. Syntax error →

Logic error →
Runtime error →

b. the compiler will divide the code into 2 Separate


4) programs
Preprocessor whichreads the source code and prepares it for translator
liilTranslator is meant to convert the program into machine language
Liii) lastly , the Linker assembles I/O functions certain
' '
functions and thefunctions that are part of source
library
Executable program .
,
program into an
c. you only keep the executable file as an executable files have all references resolve and is easily understand as it is in

human language which makes it easy to improve /debug .


2 Tutorial & Practical Exercises

PRACTICAL EXERCISES
All the laboratory computers run Windows 10. You are required to complete the
following essential tasks in this practical Lesson:

1. Login and Logoff.


2. Download files from the NTULearn EE1005 course-site.
3. Load, compile and run a simple C program.

1. Login/Logoff

To login:
At the login screen, enter your Username of your NTU Network account, and
enter your password:

Username:
Password:
Domain: Student

Remember to logoff at the end of the session.

2. Copying Files from NTULearn EE1005 Course-site

Files in Windows 10 are organized as objects residing in folders (also known as


directories). Folders may also contain sub-folders. You are required to create and
run your C program files in your specific working folder, i.e., the Documents
directory of your computer. In the first few Practical lessons, you are also required
to copy some C program files from the Handson folder of the NTULearn EE1005
course-site.
Tutorial & Practical Exercises 3

Exercise 1
Copy the file SIMPLE.C from the Handson folder of the NTULearn EE1005 course-
site to your local Documents folder.

Steps
(a) Access the NTULearn EE1005 course-site.
(b) Click on “Content” on the left panel. Then click on “Handson” folder on the
right.

(c) A list of files will then be shown on the Handson page. Click on the file
SIMPLE.C.
(d) The content of SIMPLE.C as shown below will then appear on the next
browser tab. Right-click on this browser tab and select “Save as”. Save this
file to the Documents folder of your PC.
4 Tutorial & Practical Exercises

(e) Launch the File Explorer. To launch File Explorer, double click on the File
Explorer icon shown on your computer screen.
(f) Click on the Documents folder on the left window to access the downloaded
SIMPLE.C file.

3. Compiling and Running C programs

You will now practise compiling, linking, and running a C program. Double click
on the CodeBlocks icon. CodeBlocks as shown below will be displayed.
Tutorial & Practical Exercises 5

CodeBlocks is an Integrated Development Environment (IDE) containing

(a) an Editor for creating/modifying program source code files,


(b) a Compiler for converting C source code into an object file,
(c) a Linker for constructing stand-alone executable files that can be run
directly.

To Load a File:

To load a file into CodeBlocks environment, click on File from the Menu Bar
and choose Open. Select the Documents folder. Look for the file SIMPLE.C and
double click on it. You may also load SIMPLE.C by clicking the Open button on
the CodeBlocks Toolbar:


Open button
6 Tutorial & Practical Exercises

Compiling, Linking, and Running a C Program:

Now, go through the two steps in compiling, linking and executing a C program:

(i) Compilation and Linking


Select Build from the Menu Bar and then choose Build or click the Build
button on the Build Toolbar as shown below.


Build button

If this step is successfully carried out, some new files are created in the
Documents folder. Use the File Explorer to view the names. Note the files
with the extensions: .o and .exe.

(ii) Executing (Running)


Select Build from the Menu Bar and then choose Run or click the Run
button on the Build Toolbar as shown below.


Run button

To Close a File:

To close the file, click on File from the Menu Bar and choose Close file.

Exercise 2: Modifying SIMPLE.C


Add the following three statements to SIMPLE.C before the statement “return
0;”

printf("Name: <Your_Name> \n");


printf("Tutorial group: <Your_Tutorial_Group_Number>\n");
printf("My tutor is: <Your_Tutor’s_Name>\n");

Replace <Your_Name>, <Your_Tutorial_Group_Number.> and


<Your_Tutor’s_Name> with your name, tutorial group number and tutor’s name
respectively. Then repeat steps (i) and (ii) above to compile, link and run this modified
program.
Tutorial & Practical Exercises 7

EE1005 From Computational Thinking to Programming


Tutorial and Practical Lesson 2 (Week 3)
An Overview of C

1. Write a C statement to do each of the following:

(i) Declare 2 variables, sum, and product, of type double.


(ii) Repeat (i) and initialize the variables to 0.
(iii) Prompt the user to enter an integer. End your prompting message with
a colon (:) followed by a space and leave the cursor positioned after
the space. How do you leave the cursor positioned at the beginning of
the next line?

2. Study the program below and answer the following questions. State the line
numbers that instruct the computer to:
(i) create variables in memory.
(ii) obtain input from the user.
(iii) display messages on the computer screen.
(iv) execute instructions based on some conditions.
(v) store value to an identifier (name of a variable).

#include <stdio.h>

int main(void) /* line 1 */


{
int number1, number2, smaller; lil /* line 2 */ lil
printf("Enter the first integer: "); /* line 3 */ Ciii)
scanf("%d", &number1); /* line 4 */ Iii )
"
printf("Enter the second integer: "); /* line 5 */
iiii
Q,
scanf("%d", &number2); /* line 6 */

}
if (number1 > number2) /* line 7 */
smaller = number2; /* line 8 */ Itv1
else /* line 9 */
smaller = number1; /* line 10 */

printf("%d is the smaller integer.", smaller);/* line 11 */ till


return 0;
}
# include < stdio.tn>
Ia : Void main C)
{

double sum , product ;

}
2am # include < stdio.tn>

Void main C)
{

double sum 0
product
=
,
= 0 ;

}
2aii # include < stdio.tn>
Void main C)
{

double sum 0
product
=
,
= 0 ;

" "
lprintflPlease enter an integer : In ) ;
int number't = Scant/ "
Yod ,
& number't ) ;
"

}
8 Tutorial & Practical Exercises

PRACTICAL EXERCISES
This Practical Lesson involves creating, compiling and running C programs. In
Exercises 1 to 4, you are to create source programs using the editor in CodeBlocks,
then compile, link, and run them. In the last exercise, you will learn about logical
errors in programs.

Exercise 1minimum.c
Start up CodeBlocks. Click the New file button on the CodeBlocks Toolbar:

 
New file button Save button

Then choose Empty file from the pop-up menu. You are now in the editor. Type
in the program from Tutorial 2 Question 2 (but leave out all the comments involving
line numbers such as: /* line 1 */) and save it as minimum.c using the Save
button as shown above) in the Documents folder. Pay attention to the different
colours that are associated with different program elements. This is known as syntax
highlighting/colouring.

(a) Compile, link and run the program. Check that it gives correct answers.
(b) Modify the program to find the smallest of three given numbers.
(c) Modify the program to find the smallest of four given numbers.

To close the file, click on File from the Menu Bar and choose Close file.

Exercise 2bugs.c
The program given below has many errors (bugs). Type it as given and try to
compile the program.

(a) Correct all the errors.


(b) Rewrite it so that
(i) meaningful variable names are used;
(ii) it has proper indentation and is easy to read.
(c) After all errors are corrected in (a), what output does it display?
(d) Will the computer complain that the comment statement says something
different from what the program actually does?
Tutorial & Practical Exercises 9

/* Calculate and display the difference of two input values /*

include <stdio.h>

int Main(void)
{
int X, x, sum;
scanf("%d", & X);
scanf("%f", & x);
X + x = sum;
printf("The sum of %d and %d is %d\n", X, x, sum);
return 0;

Exercise 3quadratic.c
(a) Type Program 2.4 from the lecture notes. Save the contents in
Documents folder using the filename quadratic.c.
(b) Compile, link, and run the program using the following input:
a = 2, b = 6, c =1
and verify that you get the same result as given in the lecture notes.
(c) Then run it again using

(i) a = 0, b = 1, c = 2
(ii) a = 3, b = 1, c = 2 Dividing 0
anything by
ins
What is the name given to the type of error in case (i)? Runtime error/
is

negate
Can you explain why you get the strange-looking result for case (ii)?→ root
(d) Program 2.5 in the lecture notes is a modification of Program 2.4 to overcome
the problem as demonstrated in part (c)(i). Try it. You should keep a copy
of this program for use later in the course.

Exercise 4series_circuit.c
Write a C program to solve for the current in a series circuit consisting of three
resistors (R1, R2 and R3) and a voltage source V. You can choose to modify
Program 2.4. The user must enter the input value of each resistor and the voltage
source. The current I is given by:

I = V/(R1 + R2 + R3).
10 Tutorial & Practical Exercises

Exercise 5 Hours to Minutes


(a) Copy the file HRS_TO_MIN.C from the Handson folder of the NTULearn
EE1005 course-site to your work folder, i.e., Documents folder.
(b) Run the program using hours = 3. Do you get the correct result?
"
83min ≠ 3hr3
(c) The program does not produce correct results because it has a logical error.
Locate this error, make the appropriate modification to the source code, and
compile/link/run it again. ↓ *
Mh
minutes = hours HR TO
_
-
Tutorial & Practical Exercises 11

EE1005 From Computational Thinking to Programming


Tutorial and Practical Lesson 3 (Week 4)
Fundamental Data Types

1. What data type would you use to represent each of the following items?
double/ float

(i) the average height of all students in a class,
(ii) the number of students in a class, → int
(iii) the letter grade obtained for a course,
→ char
(iv) your matriculation number, the computer can only
(v) the mass of an electron.
-
string Understand machine language

double / float
1 which is in 1s and 0s
the and 088
to
rep rent
on
2. (a) Why is the computer limited to a binary number system?
Staten
(b) How are characters represented in a computer?
← (c) In the ASCII coding scheme, P is binary 1010000. What are Q and R in binary?
character are (d) What is the integer value of each of the following expressions? accurate
represented>using (i) 'A' + 1
1 byte 861-1 of
(ii) 'A'+32 (iii) 'Z' – 'A' up
jialpodp
What do you get if you print 'A' + 1 and 'A'+32 using %c?
1
!pF¥ap
data
3. (a) What are the main differences between the float data type and the double

data type?
(b) Explain under what circumstances the conversion specifier %e (or %E) should
be used instead of %f when outputting floating-point numbers.

4. Explain why the following code does not work properly. How do you fix the
problem?
int i = 300000;
float f; 3×105 ✗ 3×105 would the variable
be greater than
f = i*i; allows hence it
type
printf("The value of f is %e\n", f); changing
be would
to double
better .
I.
lil Float / Double
Iii) Integer
liii ) char
Civ ) string
( v1 Double /Float

The computer can only understand machine which is


>
read in 1s and 0s , which represent the 2 States
2 ✓ off & on which correspond to the binary
(a) The computer can only understand 1,0s hence a binary system is needed
(b) Char binary string of 7 bits , or 8 bit when extend ASCII code and extended UNICODE
(C) Q = 1010001 R = 1010010
"
65D -11 D= 66 D
"

( di ) A =
"
ldiiu) A = 6513 -132
"
D= 97 D

(diii ) 2- = 90 D- A' = 90 D- 65D=


' ' '

25B¢
3 Float
(a) Double uses 8 bytes of data as compared to Float which uses 4 bytes -4 bytes [ I sign bit , 8 exponent , 23 mantisa bit ]
'
1.234 e 3- 0000
lower Eg
'
(b) %e → Scientific Notation , with a e .
-6 -7 digit precision
%E → Scientific Notation , with a upper
'
E
'

Eg 1.2341=-3.0000 -
-1038-10-10-38 and 10-38 to 1038
number /
% F A Floating point to 6 decimal place )

up
Double
4
into 300000 ;
-
8 bytes 11 sign bit ,
11 Exponent bits , 52 mantisa bits]
=
( int )
-14 15 digit
precision
-

Float f ; 6*0 bigger than 4


g * ,
/
o.ua#g bytes -
-10308+0-10-308 and 1-0308-10 10308
f)
"

Prin If The value of f is %f In ,


"
- i
#include <stdio.h>

:
int main(void)
{
double time = 0, initialVelocity = 1, max_time = 4, interval = 0.5;
double acceleration = 9.8, distance;
printf("Time Elapsed Distance Travelled\n" );
printf("--------------------------------\n" );
while (time <= max_time)
{
distance = initialVelocity*time + 0.5*acceleration*time*time;
printf("%8.2f %8.2f\n", time, distance);
time = time + interval;
}
return 0;
}

#include <stdio.h>
int main(void)
{
double time = 0, initial_Velocity = 1, max_time, interval;
double acceleration = 9.8, distance;
printf("Please input the maximum time\n");
scanf("%lf", &max_time);
printf("Please input the time interval\n");
scanf("%lf", &interval);
printf("Time Elapsed Distance Travelled\n" );
printf("--------------------------------\n" );
while (time <= max_time)
{
distance = initial_Velocity*time + 0.5*acceleration*time*time;
printf("%8.2f %8.2f\n", time, distance);
time = time + interval;
}
return 0;
}

1C . #include <stdio.h>
#define ACCEL 9.8
int main(void)
{
double time = 0, initial_Velocity = 1, max_time, interval, distance;
printf("Please input the maximum time\n");
scanf("%lf", &max_time);
printf("Please input the time interval\n");
scanf("%lf", &interval);
printf("Time Elapsed Distance Travelled\n" );
printf("--------------------------------\n" );
while (time <= max_time)
{
distance = initial_Velocity*time + 0.5*ACCEL*time*time;
printf("%8.2f %8.2f\n", time, distance);
time = time + interval;
}
return 0;
}
12 Tutorial & Practical Exercises

PRACTICAL EXERCISES
Exercise 1Particle Falling under Gravity
(a) Type Program 2.6 from the lecture notes. Save it using a suitable name and
test run it.
(b) Modify Program 2.6 assuming that the particle has an initial velocity u that
will be entered by the user. The formula is
1
s ut  at 2
2
where s is the distance travelled, a is the acceleration due to gravity and t is
time elapsed thus far.
(c) Modify the program in (b) so that max_time and interval are both user-
input values as well.
(d) Modify the program in (c) so that a symbolic constant ACCEL is used to
represent the acceleration due to gravity.

Exercise 2—PRINTF.C
The C conversion specifiers (%d, %c, %f, etc.) have many variations. Copy the
program PRINTF.C from the Handson folder of the NTULearn EE1005 course-
site. Compile and execute the program. Read the output carefully. Note the use
of %-5d, %1d, and %.8f, and the corresponding output. For your convenience, the
output has been saved in the file named Printf.txt. Get it from the Handson folder,
and Study it!

Exercise 3
A variable of type char can be used to store small integer values (from –128 to 127).
What happens if a large value is assigned to a char variable? Consider the code:
nonsense values

char c = 128; /* greater than max of 127 */ 128 -

printf("c = %d\n", c); /* print integer value of c */

Fill in the necessary C statements to make the above a complete program. Test run
it. The unexpected output is a direct result of how integers are represented in
computing. The details are not covered in this course. Adding 1 to the maximum
possible integer value (in this case, it is 127) has the effect of “wrapping around”
to the negative end, i.e. 127 + 1 becomes -128 (beginning of the range for char type).
Hence, it is very important to make sure that your calculations involving integers do
not exceed the limits.

Q ¥ to ¥27
What will be printed if the value of c is changed to 129, 255, 256, -129?

-127
Tutorial & Practical Exercises 13

Exercise 4 Temperature conversion


Write a program TEMPCONV.C to convert temperature readings from degrees
Celsius (C) to degrees Fahrenheit (F). The program should print both the value of
degree Celsius and its Fahrenheit equivalent, with appropriate identifying messages.
The formula is
F = (9/5) C + 32
Make sure that your result is correct.

Exercise 5 Drawing picture


Write a program PICDRAW.C that uses 6 printf() statements to produce the
following picture on the screen. Be careful when you need to print \, % and ".

( )
(oo)
/-------\/
/ | %% ||
* ||----||
"" ""
Ex 4 .

#include <stdio.h>

int main(void)
{
double celsius, fahrenheit;
printf("This program is to convert from degree celsius to fahrenheit\n");
printf("------------------------------------------------------------\n" );
printf("Please input temperature in degree celsius\n");
scanf("%lf", &celsius);
printf("--------------------------------\n" );
fahrenheit = (9.0/5.0*celsius)+32;

t
printf("Degree fahrenheit = %.2f\n", fahrenheit);
return 0;
} *
Celsius 915 Cause order of
operants and
*
Celsius 9 Double Value !

Ex 5 .

#include <stdio.h>

int main(void)
{
printf("%10( )\n");
printf("%10(OO)\n");
printf("%3/-------\\/ \n");

9
printf("%2/ | \%\% ||\n");
printf("* ||----||\n");
printf("%3\"\"%5\"\"");
} Return 0
if
%%%% also accepted!
14 Tutorial & Practical Exercises

EE1005 From Computational Thinking to Programming


Tutorial and Practical Lesson 4 (Week 5)
C Operators and Standard Library Functions

1. Suppose that x = 3, y = 4, and z = 10 (all integer variables). What is the


value of each of the following expressions?
(a) x + y/z*x ° (b) x*-(y+z) double
(c) x%(z/y) =L (d) !-¥.s
y%x +1.5/x
(e) x/2 + 3.5 = 4.5 (f) (double)x/2 + 3.5 5 =

(g) x/2.0 + 3.5 = 5.0

2. What is the output of the following program fragment?

int i = 3, j = 10;

printf("%d\n", i++); 3
printf("%d\n", ++i); 5
printf("%d\n", j--); 10
printf("%d\n", --j); 8
printf("%d\n", (--j + 2)); 9
printf("%d\n", (i-- + ++j)); 13
5 1- 8

3. Assume that int x = 10, y = 2, z = 3. Complete the following table:

Expression Equivalent to Result


x += y x = x + y x = 12
x %= z 0C = ✗% 7- oc = 1
y /= z y =
y / 2-
y = 0
#
y *= x/y =
y pay ) y
= 10
y
x %= x/(y+z) oc =
sc%4c.ly-17-1 sc =
2

5-13--8
10%8=2
4. Assume the following declarations and initializations:
int i = -15, j = 5;
double x = -1.5, y = 4.0;
char ch = 'a';

(a) Determine the value of each of the following expressions:


2*5=10
✗ =L -5
(i) abs(i+2*j) -151-10=-5 (ii) fabs(x)
(iii) ceil(x+y) abs C-5) (iv) floor(x+y)
=5

-1-5-14.0
= -12-5
call-12.51=3
3
5
10

&
( I 12

la .
xty1z*x b. ✗
*
ly -12 )-
g.sc/2.0 -13.5 /
3-14110*3 3*-141-101 = 03/2-01-3.5 ( tttj = 13
*
3*-114 )
=/ 454
3-10 3
b-
44
- =

3
=3
3*-14 V
3.0/2.0
= yz
t
-

-42g duet promotion


= 1.5 -13.5
=
5.0¢
c. 00%12/y ) d. y%x -11.510C
3% 4%3+1.513
3%1311
into )
I
+00g
=
1--1
= 0
3%2 -5¢ 0.5
due -10
If
=
promotion

e.sc/2 -13.5 f. (double)xl2 -13.5


= 3/21-3.5 3121-3.5
= 1 +3.5 1.5-13.5
= 4.5 =
5g

x =x%Z ✗ =/
y =
y l z y = O

y =y*&c / y ) y -10
-

x=x%(x/ ly -12) ) x= 0

Hai .
absl-151-2*5 ) 4aiifabs.lk)
= (-15-110) =fabsl -1.51
= 1.50000
= I -
5)
absl -5 )
= (5)

4aiii .

Ceillxty ) 4aiv.floorlxt.gl
floor (-1.5-14.0)
Cell (-1.5-14.0)
=
=

= Ceil / 2.5 )
= floor ( 2.51


=

3.0¢
=
Tutorial & Practical Exercises 15

(b) For each of the following, state whether the return value is zero or
nonzero :

(i) isalnum(5) non (ii) isalnum('5') non


(iii) isalpha('A') non (iv) isalpha(65) zero
(v) isupper(ch) zero (vi) isdigit(ch) Zero

Write printf statements to output the return value of each case in part (b).

Note: You do not need to know the actual non-zero values returned as it is only
important to know whether it is zero or non-zero.
check ASCII
bi
table bi
iflisalnumls ) )
lloutput bewill false Iflisalnuml 's 'll lloutput will be true
{ " {
Prints / This character alphanumeric ! );
"

is "

alphanumeric ! ) ;
an
Prints /
"

This character is an

I 1
else
else
{ " {
Prints / alphanumeric ! ) ;
"

This character is not "

alphanumeric ! ) ;
an
Prints /
"

This character is not an

I I

biii . biv .

'A 'll lloutput lloutput Will


iflisalphal will be true
Iflisalphalbs ) ) be true

{ "
{
alphabet ! )
"
Prints / alphabet ! )
"

Prints /
"

This character is an , This character is an


,

I 1
else else

{ "
{ "
Prints / alphabet ! ) ; alphabet ! ) ;
"

Prints /
"

This character is not an This character is not an

I I
biv . biv .

iflisupperlch )) lloutput Will be false Iflisdigitlch) ) lloutput will be false


{ {
Prints /
"
" "
Prints /
"
This character is an
uppercase character ! ) ,
This character is a decimal digit ! ) ,

I 1
else else

{ { "
Prints / digit ! )
"
"
) Prints / decimal
"
This character is not an
uppercase character ! ,
This character is not a )

1 I
16 Tutorial & Practical Exercises

PRACTICAL EXERCISES

Exercise 1 Program Style


The style issue has no effect on the meaning of the program as far as the computer
is concerned. However, they can make reading and understanding of the program
easier for humans. Copy the program STYLE.C from the Handson folder of the
NTULearn EE1005 course-site and do the following:

(a) Debug this program.


(b) Rewrite the program completely, making use of blank spaces and appropriate
indentations to make it more readable. Also, choose suitable names for
variables.

take in character
Exercise 2 →
Write a C program CHK_CASE1.C that accepts a character using the scanf()
function and determines if the character is a lowercase letter. Use a standard library
function to do the character checking.

Exercise 3
Write a program to calculate the length of the third side c of a triangle given the
other two sides a and b, and the included angle . Assume that is entered in
degrees.

Exercise 4  rand() and srand()


(a) Test run Programs 5.3 and 5.4 several times and note the results.
(b) Write a program to simulate the outcome from the rolling of a six-sided dice
(i.e., the output should only be integers from 1 to 6). Use a while loop that
runs 100 times.
Tutorial & Practical Exercises 17

EE1005 From Computational Thinking to Programming


Tutorial and Practical Lesson 5 (Week 6)
Decision Making
I > I && ✗ < =/ 04
1. (a) Express the mathematical condition 1 < x <= 10 in C where x is an
integer.
(b) Rewrite the statement below using an if-else structure:
salary = basic + (sales > 10000.0 ? sales*0.02 : sales*0.01);

2. Assuming that
x = 11, y = 6, z = 2, c = 'k', d = 'y',

fill in the missing entries in the following table:

Expression11 I =L Value of Expression


0
x == 5 || y != 3 =/ I
' GE I

!(x > 9 && y != 23) 0
x <= 1 && y == 6 || z < 4 "
c >= 'A'8dg|| c <=0 'Z'
0 I 11 1=1
5 && y !=8 || 0
x >= y >= z

3. Incorrect use of the assignment operator (=) and the equality operator (==)
often gives unexpected results in C. What is the output in each of the following
cases?
(a) x = 3;
if (x = 4)
printf("Will this line be printed?\n");

(b) x = 3;
if (x == 4)
printf("Will this line be printed?\n");

4. Rewrite the following if-else structure (where i is an integer) using a


switch statement.

if (i==0) printf("bad");
else if (i>=1 && i<3) printf("good");
else if (i==4 || i==5) printf("excellent");
else printf("Sorry!");
la . intx ;

K >
148×4=10 ;

lb Ifl sales > 10000.01 A


{ can be omitted non zero
-
.
.

{ zero

basic 1- Sales -1×0.02


salary =
; non -
zero

} non -
zero
else if / Sales 410000.0 )
non zero
{
-

}
Salary = basic -1 Sales
#
0.015
Could be
undefined non-÷.&
( x= = 5)
ly ! =3 )
=

=
O

,
100 = nonzero
Leg ☐

Switch lil
3A . {
Case 0 :

"
Prints l bad )i
"
Yes , this line will be
printed However, no matter , the
.

Value of x , this line will be printed as x=4 will break ;


value
always return a non zero
-
.

Case 1 :
" "
Prin-15-1 good );
break ;
3. b.
Case 2 :
" ' '
Prints ( good ) ;
No this line will not be printed as the value of x is 3
, break ;
while the condition to print is that x must equal -104
case 4 :
" "

Prints ( Excellent ) ;
break 's
case 5 :
" "

Prints ( Excellent ) ;
break 's
default : " "
Prints ( sorry ) ;
break's

}
18 Tutorial & Practical Exercises

PRACTICAL EXERCISES

Exercise 1 — Bank Account Interests

Copy the program BankInterest.c from the Handson folder of the NTULearn
EE1005 course-site. This program computes and displays the simple interest paid
by a bank on customer deposits. Input parameters are: the principal amount (in $),
the basic annual interest rate (in %), and the period of the deposit in months. The
interest amount is computed using:

_ ( %) _ ( )
interest = _ ( $) ∗ ∗
%

Run this program and check the output.

Suppose the annual interest rate is now


(a) 1% higher than the basic annual interest rate if the deposit period is
>=15 months but < 24 months, and
(b) 1.25% higher than the basic annual interest rate if the deposit period
is at least 24 months.
Modify the program to take these into account.

Exercise 2 — Calculator

Write a program that acts as a simple calculator (with operators + - * /) as described


below.

First prompt the user with the following message:

Enter two numbers and an operator in the form


number1 operator number2 (e.g. 4.5 - 2.9)

Suppose the user enters:


23.2 + 12
Program responds with

23.2 + 12 is 35.2

Write this program in 2 ways: first by using nested if and then by using switch.
Check for invalid operators.
Tutorial & Practical Exercises 19

EE1005 From Computational Thinking to Programming


Tutorial and Practical Lesson 6 (Week 7)
Loops
into -_ I
1. What is the value of x when the following loop ends? do
1 "
Printfl "%dln ,x ) ;
for (x = 0; x < 50; x++);49 / Printed) x -1=3 ;
50 ( Valueofx ) } while lx< = 100 ) ; intro -_ I
return Oi while Coch -400)
{
2. Write a for loop to count from 1 to 100 in steps of 3, i.e. display 1, 4, 7, 10, Prints ( %d1n.sc); "

13…, where the difference between a number and its immediate neighbor is 3. 3 -1=3 ; x

Repeat using a while loop and then a do while loop. into return on ,

for (x -4 ;x< -400 ;X -1=3)


{ "
Prin-181 "%d\n
3. What is wrong with the following code fragments? ,X ) ;
(a) }
count = 0; returned ;

!
always true
while (count < 10) forever
{ ✓ looping
printf( "count= %d\n", count);
printf( "Continuing..." );
}
will

"¥:÷%
loop
the
*
(b) *
would start
for (count = 1; count < 10; ++count);
{
printf("Counting up from 1, count = %d", count);
}
20 Tutorial & Practical Exercises

PRACTICAL EXERCISES

Exercise 1 — Approximating the value of e

The value of the mathematical constant e, the base of natural logarithm, can be
approximated by calculating partial sums of the infinite series:

1 1 1 1
= = 1+ + + +⋯
! 1! 2! 3!

Write a program that asks the user for the last value of n to use, and then sums
the above series accordingly. For example, when user enters the last value of n as 3,
you program will output the result of 1 + ! + ! + !. Try n = 3, 4, 5, …. to see how
well partial sums of the series approximate the value of e. How many terms are
needed to get accuracy to 5 decimal places?

Exercise 2

Write a program that creates the following pattern, given the height (number of
rows) and the width (print characters per line) which are to be entered by the user.
A sample screen display is as follows:

Enter two integers for height and width: 7 12


============ for ( L = 1 ; o <= height ; it-1 )
* * {
if (b== I 11 G- = height)
* * {
=L ; j < = width ; jtt )
* * for Lj
Printf l
''
=
"
);
* * Else
* * { width ; ; -1-1 )
for Cj =L ; j<
=

============ l width)
if (; ==L 11J
= =
"

f ( A "
);
print "

"
);
sprint f(

} "
"
);
Prints 1 in

3
0:
return

----------------------------------------------------------------------------------

You might also like