IntroductionToCh For ENME2CF Computer Fundamentals
IntroductionToCh For ENME2CF Computer Fundamentals
com
Programs in Ch
Note: If asked to save your program, be sure to save it as a .ch file (e.g. ProgramName.ch). Once the
file is saved as .ch, Ch will be able to find and run your program. Additionally, Ch will know to
automatically color code your program for easier readability!
Program add.ch
Read through and run the program below to improve your understanding of how Ch stores values in
variables. Notice what happens when the same variable name is used to store more than one value.
1a) Predict the answer to the sum of x+y+z below. Then run the following program to test your
prediction:
/* File: add.ch */
int x, y, z; // initialize variables
Code Explanation
1
http://www.softintegration.com
z = 6; e)
z = 2; f)
printf("%d\n", x+y+z); g)
Note:
● In the final line of program add.ch we also introduced notation \n, which tells Ch that we would
like it to start a new line before printing out the statement that follows.
● Use the format specifier “%d” in function printf() integer numbers.
2
http://www.softintegration.com
Program product.ch
Predict and run the program below, and work through the related tasks to improve your programming
skills.
Note: Quotation marks and commas are NOT optional in Ch. If Ch gives you an error message,
double check to make sure you included all quotation marks and commas!
2a) Predict what the program below will do. Then run the program to test your prediction:
/* File: product.ch */
int firstnumber, secondnumber, product; // declare variables
printf("enter the first number: "); // prints to the screen the message
scanf("%d", &firstnumber); // reads user input and stores into variable
printf("enter the second number: ");
scanf("%d", &secondnumber);
Code Explanation
scanf("%d", &firstnumber); b) Store the value that the user enters into the
variable called firstnumber
scanf("%d", &secondnumber); c)
product = firstnumber*secondnumber d)
e)
printf("%dx%d=%d\n", firstnumber,
secondnumber, product);
Note:
● Use the format specifier “%d” in function scanf() for integer numbers.
Task 1: Create new variable names for ‘firstnumber’, ‘secondnumber’, and ‘product’. Be sure to
replace the variables ‘firstnumber’, ‘secondnumber’, and ‘product’ with your own variable names
each time they appear in the program.
Task 2: Change the program to multiply 3 input numbers and print the result.
3
http://www.softintegration.com
Program tall.ch
Predict and run the program below, and work through the related tasks to improve your programming
skills.
Note: On line 12 of the code we divided by 12.0 because if we divide by 12, Ch will cut off the decimal
part of the answer.
3a) Predict what the program below will do. Then run the program to test your prediction:
/* File: tall.ch */
// declare variables
int feet, inches;
double totalinches, totalfeet;
Note:
● Use int and double types to declare variables to hold integer and decimal numbers,
respectively.
● Use the format specifiers “%d” and “%lf” in functions printf() and scanf() for integer and
decimal numbers, respectively.
Use the table below as a guide to analyze Program 3:
Code Explanation
scanf("%d%d", &feet, &inches); a) Store the first value entered into a variable
called feet and the second value into a variable
called inches
totalinches = feet*12 + inches b) Multiply the value stored in feet by 12 and add
the product to the value stored in inches; the sum
is stored in a variable called totalinches
totalfeet = feet+inches/12.0 c)
printf("You are %lf inches tall.\n", d) Print out the specified height in inches
totalinches);
4
http://www.softintegration.com
Task 1: Add a line of code that will calculate how many centimeters tall the user is, and a print statement
that will print out the result (note: there are 2.54 cm in one inch).
Program average.ch
Predict and run the program below, and work through the related tasks to improve your programming
skills.
a) Predict what the program below will do. Then run the program to test your prediction:
/* File: average.ch */
// declare variables
double first, second, third, average;
// compute average
average = (first+second+third)/3.0;
Code Explanation
scanf("%lf%lf%lf", &first, &second, a) Store the first value entered in a variable called
&third); first, the second value in a variable called
second, and the third value in a variable called
third
average = (first+second+third)/3.0 b)
printf("average: %lf\n", average); c) Print out the average of the three specified values
Task 1: Change the program so that it asks the user to enter the three numbers one line at a time, e.g.:
5
http://www.softintegration.com
Arithmetic and Parentheses in Ch
Parentheses can change the result of an arithmetic expression. Write a short program, to allow you to
output the following expressions to understand how parentheses affect the order of operations.
Exercise 4 Exercise 5
4a) 5a)
Step 1: Divide 70 by 5 Step 1: Multiply 5 by 3
Step 2: Multiply the result by 3 Step 2: Add 6 to the product
Step 3: Subtract 12 from the product
Step 3: Multiply the sum by 4
Step 4: Subtract 8 from the product
Step 5: Divide the result by 4
4b) Write the expression described above: 5b) Write the expression described above:
_________________________ _________________________
Type the expression into the interpreter. If correct, Type the expression into the interpreter. If correct,
Ch should tell you that the answer is 30. Ch should tell you that the answer is 19.
6
http://www.softintegration.com
Mathematical Notation in Ch
Ch uses several symbols for mathematical operations that vary from what we usually see in math class.
Test the examples below while looking for patterns that indicate the meaning of each symbol.
Exercise 6
For each of the operations below, enter the four examples into the Ch IDE program to figure out what
each operation does. Use the last column to comment on what you have learned about the operation.
Note:
The function pow(x, y) is used as the power function for the expression xy.
Unless the result of a division operation is a whole number, to get the correct numerical result,
one of the numbers must be a decimal.
Equality in Ch
Ch has three different symbols to represent different types of equality. In the exercises below, test out the
‘=’, ‘==’, and ‘!=’ symbols looking for patterns that indicate what each one means.
Exercise 7
Write a program in Ch that will output the values of the expressions below, starting with 7a). Use the last
column to comment on what you have learned about that symbol.
Note:
● Be sure to complete 7a) before entering in the other expressions; Ch cannot evaluate an
expression involving a variable until that variable is defined.
● If Ch gives you an error message on any of the above exercises, try defining x again by entering
x=7, and then proceeding.
7
http://www.softintegration.com
7a) 7e)
> int x > x == 7
>x = 7
7b) 7f)
> 4*x > x == 9
7c) 7g)
> pow(x,2) >x != 9
7d) 7h)
>x >x != 7
Note:
1. The symbol int is used to declare a variable to store integers.
2. The symbols ‘=’, ‘==’, and ‘!=’ represent assignment, equal to, and not equal to,
respectively.
Inequality in Ch
Exercise 8
Ch also understands inequalities ‘<’, ‘<=’, ‘>’, and ‘<=’. Enter the expressions below, beginning with 8a),
and record the results.
8a) 8g)
> x=3 > x>=8
8b) 8h)
> x<8 > x>1
8c) 8i)
> x<=8 > x>=1
8d) 8j)
> x<1 > x == 3
8e) 8k)
> x<=1 > x<=3
8f) 8l)
> x>8 > x<=3
Note: The symbols ‘<’, ‘<=’, ‘>’, and ‘>=’ represent less than, less than or equal to, greater than,
and greater than or equal, respectively.
8
http://www.softintegration.com
Logical Operations in Ch
Exercise 9
Ch also understands logical operations. Enter the expressions below, beginning with 9a), and record the
results.
9a) 9d)
> x=3 > x>1 && x<8
9b) 9e)
> x<2 || x>8 > x>5 && x<8
9c) 9f)
> x<5 || x>8 > x<=3 && x<8
Note: For the logical OR (||), either one or both of its operands must be true for the operation to
be true. The logical AND operator (&&) can be used to check whether both the conditions of its
two operands are true.
9
http://www.softintegration.com
Conditional Logic in Ch
Ch uses conditional logic to ‘branch out’ and handle all possible scenarios to solve a problem. Run the
program below three times:
● The first time, enter a number that is less than 2272
● The second time, try a number that is greater than 2272
● The last time, enter 2272
Program 5: guess.ch
Predict and run the program below, and work through the related questions and tasks.
5a) Based on the results and the code below, explain what an ‘if, elif, else’ statement appears to
do in the space below:
/* File: guess.ch */
int guess;
printf("Guess the average number of texts an American teen sends and receives
each month: ");
scanf("%d", &guess);
if (guess == 2272)
printf("You got it!\n");
else if (guess < 2272)
printf("Too low; the average American teen sends 2272 texts per
month\n");
else
printf("Too high; the average American teen sends 2272 texts per
month\n");
Code Explanation
scanf("%d", &guess); a)
else if (guess < 2272) c) If the user did not guess 2272, Ch checks to see
printf("Too low; the average if the value they guessed is less than 2272. If it is,
American teen sends 2272 texts per Ch prints out the words “Too low, try again”
month\n");
else d)
printf("Too high; the average
American teen sends 2272 texts per
month\n");
5f) In the space below, complete the program so that Ch will run as follows:
10
http://www.softintegration.com
● Ask the user how many hours she slept last night.
● If she slept 7 - 9 hours, print out ‘You are right on schedule’.
● If she slept less than 7 hours, print out ‘You need a nap’.
● If she slept more than 9 hours, print ‘Time to set the alarm’.
/* File hour.ch */
int hours;
Type your completed program into the ChIDE editor and run it to check your work.
Program guess2.ch: Blastoff outside of the loop Program guess3.ch: Blastoff inside of the loop
Describe the results of this program: How do the results of the program differ now that
the second print statement is inside the braces?
11
http://www.softintegration.com
Program count.ch: We can have Ch count the total number of multiples of 3 between zero and one
hundred by adding a variable that we chose to call counter to our program.
/* File: count.ch */
// initialize variables
int x, counter;
12
http://www.softintegration.com
Code Explanation
counter = 0; b)
Note:
● We set counter equal to zero at the beginning of the program. We ‘initialize’ all variables before
using them in a loop. This tells Ch that it will need to save some space for the variable before it
runs through the loop that follows.
Once we learn how to program, we can create a personalized calculator that can do our work for us. In
the program below, we used a while loop to create a calculator that will solve a word problem:
Program earnings.ch: Mai earns $5.50 per hour Program earnings2.ch: Notice that this is the same
at her after-school job. How many hours does she program, with a print statement is included in the
have to work to earn $132? while loop. Compare the results to those of Program
earning.ch.
13
http://www.softintegration.com
Note:
● In these final programs, hours does the same thing that counter does in Program count.ch.
● Use the format specifier “%.2lf” for the function printf() to display a decimal number with two
digits after the decimal point, instead of the default 6 digits after the decimal point.
Program game.ch
Ch has a function called randint() that will pick a random number between any two values that you
want. Type the guessing game below into the ChIDE editor and then fill out the table below to help you
understand how this program works.
/* File game.ch */
int guess, x;
printf("I'm thinking of a number between 10 and 25. Guess my number: ");
scanf("%d", &guess);
scanf("%d", &guess); a)
while (guess != x) c)
scanf("%d", &guess); d)
Program game2.ch
We can improve our guessing game by providing hints about whether the user’s guess is too high or too
low. We do this by including conditional logic inside a loop. Fill in the two blank lines of code to tell Ch
under what condition it should print out ‘too low, try again:’
14
http://www.softintegration.com
/* File game2.ch */
int guess, x;
Did you know: If a person has to guess a number between 1 and 100, it is possible to
guess the number within 7 tries! This might be an exercise to try during lectures if time
permits.
Adapt the code to restrict the user with only a certain number of tries, with the use fo the
WHILE loop.
Can FOR loops be used to allow the user only a restricted number of tries? Give it a try.
15
http://www.softintegration.com
Arrays
Arrays are used for storing data as a string of characters, or in a matrix formation. Some
examples with the use of arrays are given below. More details on the use of strings will be
discussed in lectures.
/* Example 1:
An array qualified by type qualifier 'array' is called computational
array.
A computational array is treated as a first-class object as in Fortran
90.
*/
#include <stdio.h>
#include <array.h>
int main() {
array double A[2][3] = {1, 2, 3,
4, 5, 6};
array double B[3][2];
printf("A= \n%f \n", A+A);
B = 2*transpose(A);
printf("B= \n%f \n", B);
}
B=
2.000000 8.000000
4.000000 10.000000
6.000000 12.000000
/* Example 2:
A function can return a computational array as well.
*/
#include <stdio.h>
#include <array.h>
16
http://www.softintegration.com
}
Arrays can be used to perform matrix arithmetic. Complex numbers can also be implemented in
Ch.
#include <stdio.h>
#include <numeric.h>
int main() {
complex z;
array double A[3][3], C[3][3] = {1, 2, 3,
4, 5, 6,
7, 8, 9};
A = C*4 + sin(C);
printf("A= \n%f \n", A);
A = C * transpose(C)* inverse(C);
printf("A= \n%f \n", A);
z = complex(3,4);
z = sin(2*z);
printf("z = %f\n", z);
}
A=
64.000000 0.000000 32.000000
128.000000 0.000000 -64.000000
256.000000 0.000000 128.000000
z= complex(-416.462982,1431.113525)
17
http://www.softintegration.com
Plotting in Ch
Ch can plot data conveniently. The relation between Fahrenheit and Celsius are given in a table below.
Program points.ch
Predict and run the program below, and work through the related questions and tasks.
/* File: points.ch
Plot the temperature relationship between Fahrenheit and Celsius
using five points */
#include <chplot.h> // for CPlot
CPlot plot; // declare the variable plot
18
http://www.softintegration.com
Code Explanation
#include <chplot.h> a) Include the header file chplot.h where all the
plotting information is stored
plot.label(PLOT_AXIS_Y, "Celsius"); f)
plot.point(20, -6.67); h)
19
http://www.softintegration.com
1. Write a program that allows you to enter a distance in miles, and that would calculate the
distance in kilometers. 1 mile is equivalent to 1.609 kilometers.
2. Write a program that allows a user to determine the surface area of a washer. Use error
checking, to make sure that the inner diameter is not entered to be larger than the outer
diameter of the washer. Consider having a range of values that are suitable for the inner and
outer diameters.
3. Write a program that will be able to calculate the factorial of a number. Modify the program to
calculate the factorial of a number, using only the even OR odd numbers in the series.
4. There are 9870 people in a town whose population increases by 10 percent each year. Write
a program that will display the annual population and determine how many years it will take for
the population to surpass 30 000.
6. Write a program that estimates the temperature in a freezer (in °C) given the elapsed time
(hours) since a power failure. Assume that this temperature (T) is given by:
Where t is the time period since the power failure. The user must enter the exact number of
hours and minutes that the power failure has occurred – you are required to use this information
to perform the calculations.
7. Write a function that will return a 1 for true if a string argument ends with the substring OH.
Try the following data: KOH, H2O2, NaCl, NaOH, C9H8O4, MgOH
8. Write a program that will plot the following functions with a legend. Use different values for
the variables of the Chplot library functions:
S1(t) = 5 sin (2πt)
S2(t) = 3 sin (πt + π)
S = S1 + S2
Re-write the code to use sub-plots.
20
http://www.softintegration.com
Summary
In this lesson we covered several key programming topics that are directly applicable to math curriculum
and computational thinking. These include:
The content of this lesson is licensed under the Creative Commons Attribution 3.0 License, and code
samples are licensed under the Apache 2.0 License.
The majority of the material in this document was obtained from SoftIntegration, either through
documentation, websites, or shared files. The layout and flow of the document was drastically
altered, with additional examples and comments, to be presented in the course Computer
Fundamentals, presented by Riaan Stopforth.
21