Skip to content

section5_exercises

João Dias Conde Azevedo edited this page Jan 18, 2019 · 22 revisions

Exercises

The 'if' statements

  1. Write a program that reads a number and tells if it's odd or even.
Insert a number? 50
50 is even.
  1. Write a program that asks the weight (Kg) and height (m) of a individual. Then calculate the Body Mass Index (BMI) and print the category according with the table below.

IBM = weight (kg) / heigth^2 (m)

Category BMI (kg/m^2)
Severely underweight [0,16)
Underweight [16,18.5)
Normal [18.5,25)
Overweight [25,30)
Moderately obese [30,35)
Severely obese >= 35
Height ? 1.75
Weight ? 72

Normal
  1. Write a program that calculates the roots of a second-degree polynomial.

💡 So far you are including stdio.h on your programs to use printf() and scanf(). To solve this exercise you need to calculate the square root of a number. You could implement your own algorithm, but there's a match library that has a function to calculate the square root of a number. Check the math.h library and particularly the sqrt() function. As a developer you need to see documentation all the time.

Enter the second degree polynomial coefficients (a*x^2 + b*x + c).

a ? 1
b ? 0
c ? -4
x = 2.000000  v  x = -2.000000
Enter the second degree polynomial coeficients (a*x^2 + b*x + c).

a ? 5
b ? 1
c ? 1
No real roots!
Enter the second degree polynomial coeficients (a*x^2 + b*x + c).

a ? 1
b ? 0
c ? 0
x = -0.000000

Loops

  1. Write a program that reads a number and presents you the sum of its digits.
Number ? 75
The digits sum of 75 is 12.
Number ? 9
The digits sum of 9 is 9.
Number ? 205
The digits sum of 205 is 7.
  1. Write a program to determine the prime factors of a number.
Number? 10
Factors: 2 5 
Number? 15
Factors: 3 5 
Number? 36
Factors: 2 2 3 3 
Number? 124
Factors: 2 2 31 
  1. Write a program that takes in a number of grades from a class of students and determines the average grade.
Number of students? 3
Grade? 15
Grade? 16
Grade? 16
Average grade is 15.666667
Number of students? 5
Grade? 15
Grade? 10
Grade? 13
Grade? 14
Grade? 18 
Average grade is 14.000000
  1. Write a program that reads out two integer values, let's call them N and K. Given a set of integers from [1, N], and considering 2 integers of this set, let's call them A and B, where A < B, find:
    • the maximum value of A & B which is less than K
    • the maximum value of A | B which is less than K
    • the maximum value of A ^ B which is less than K

Remember that these are bitwise operators:

  • & - bitwise and
  • | - bitwise or
  • ^ - bitwise xor (exclusive or)
N? 5 
K? 4
Max a & b: 2
Max a | b: 3
Max a ^ b: 3