You are on page 1of 10

Class 1 - C Language Overview

In this class we will cover C basics to quickly get to a point where you can write useful
programs: variables, constants, operators, control flow. The best way to learn a new
programming language is by writing programs in it. Therefore, we will use plenty of examples.

1.1 Getting Started


Example 1.1. Write a program that outputs the following sentence: "Hello, world!".

#include <stdio.h>

int main()
{
printf("Hello, world!\n");
return 0;
}

Comments:

● Format the source code in https://codebeautify.org/c-formatter-beautifier


● Run this program:
○ Online in https://www.online-cpp.com/online_c_compiler, or
○ In zeus.cec.gmu.edu:
■ Use vi or other text editor to create file 1_1_hello_world.c
■ gcc 1_1_hello_world.c
■ ./a.out
● Note import of standard input/output library to support a built-in printf function
● Note a special main function to execute your program
○ The program returns an integer to represent the program's return code
■ echo $?
■ 0

Example 1.2. Write a program that converts from Fahrenheit to Celcius for temperatures from 0
to 300 in 20-degree increments.

#include <stdio.h>

/*
Print Fahrenheit-Celsius table for 0, 20, ..., 300
*/
int main()
{
for (int i=0; i<=300; i+=20) {
printf("%d\t%d\n", i, 5 * (i-32) / 9);

1
}
}

Which statement will output Celsius in a floating point format?

● printf("%f\t%d\n", i, 5.0 * (i-32) / 9);


● printf("%d\t%.2f\n", i, (float) 5 * (i-32) / 9);
● printf("%d\t%d\n", i, 5 * (i-32) / 9.0);
● printf("%d\t%f\n", i, 5 * (i-32) / 9);

Answer: the second option. You can specify precision (2 points after decimal) as follows:
printf("%d\t%.2f\n", i, (float) 5 * (i-32) / 9);

We now use symbolic constants to enhance the above program to avoid the use of "magic
numbers", which is considered bad practice.

#include <stdio.h>

#define LOWER 0.0


#define UPPER 100.0
#define STEP 10.0

/*
Print Fahrenheit-Celsius table
*/
int main()
{
printf("%s\n", "Fahrenheit to Celsius");
for (float temp=LOWER; temp<=UPPER; temp+=STEP) {
printf("%.2f\t%.2f\n", temp, 5 * (temp-32) / 9);
}

printf("\n%s\n", "Celsius to Fahrenheit");


for (float temp=LOWER; temp<=UPPER; temp+=STEP) {
printf("%.2f\t%.2f\n", temp, temp * 9 / 5 + 32);
}
}

Example 1.3. Write a program that outputs the number of lines in a file.

#include <stdio.h>

#define EOL '\n'

/* Count lines in input */


int main()

2
{
int c, nl;
nl = 0;
while ((c = getchar()) != EOF)
if (c == EOL)
++nl;
printf("%d\n", nl);
return 0;
}

Comments:

● A symbolic constant EOL represents an end of line character


● A symbolic constant EOF is a part of the stdio standard library to represent an end of file
character
● Function getchar obtains one character from standard input
● Run the program on Unix
○ gcc 1_3_lc.c
○ cat 1_3_lc.c | ./a.out [Pipe source code]
○ 15
○ wc 1_3_lc.c [Unix utility]
○ 15 1_3_lc.c

Example 1.4. Future value (FV) is the value of a current asset at a future date based on an
assumed rate of growth. One example is putting money into a certificate of deposit (CD) for a
certain number of years to earn a simple interest paid annually. In such cases the FV formula is:

𝐹𝑉 = 𝐼 × (1 + (𝑅 × 𝑇))

where:

● I = Investment amount
● R = Interest rate
● T = Number of years

For example, assume a $1,000 investment is held for 5 years in a CD account with 10% simple
interest paid annually. In this case:

𝐹𝑉 = $1000 × (1 + 0. 1 × 3) = $1300

We write a program that computes future value given the above parameters.

#include <stdio.h>

double fv(double amount, double rate, int years);

3
int main()
{
double amount, rate;
int years;
scanf("%lf", &amount);
scanf("%lf", &rate);
scanf("%d", &years);
printf("FV=%.2lf for amount=%.2lf, rate=%.2lf, years=%d\n", fv(amount,
rate, years), amount, rate, years);
return 0;
}

/* Compute future value */


double fv(double amount, double rate, int years)
{
return amount * (1+rate*years);
}

Comments:

● Function fv is defined and implemented in the same file


● Built-in scanf function reads a number from the standard input
● Run on Unix as follows
○ gcc 1_4_fv.c
○ echo "1000.0 0.1 5" | ./a.out
○ FV=1500.00 for amount=1000.00, rate=0.10, years=5

Why do you think a function's definition is needed before main (choose the best answer)?

● To inform a compiler about the function's signature


● It can work without the definition, just based on its implementation
● A function may be implemented in a different file
● There may be multiple functions with the same name

Answer: the first answer - a compiler needs to know about the function's signature before it's
used. Other answers are incomplete or incorrect.

1.2 Types, Operators, and Expressions


In the next set of examples we will further develop the concept of value of money to
demonstrate different variable types, operators, and expressions.

4
Example 1.5. With simple interest, it is assumed that the interest rate is earned only on the initial
investment. With compounded interest, the rate is applied to each period's cumulative account
balance. For example, investing $1,000 into a savings account with 10% compounded interest
for 3 years will work as follows.
● Year 1
○ $1000 × 1. 1 = $1100
● Year 2
○ $1100 × 1. 1 = $1210
○ Note: the new balance (investment amount)
● Year 3
○ $1210 × 1. 1 = $1331
○ This is the future value using compounded interest

The formula for the FV of an investment earning compounding interest is:

𝑇
𝐹𝑉 = 𝐼 × (1 + 𝑅)

where:

● I = Investment amount
● R = Interest rate
● T = Number of years

Modifying the program in example 1.4 to use compounding interest:

#include <stdio.h>

#include <math.h>

float fv(float amount, float rate, unsigned int years);

int main() {
float amount, rate;
unsigned int years;
printf("Enter amount, rate, years: ");
scanf("%f", & amount);
scanf("%f", & rate);
scanf("%u", & years);
printf("FV=$%.2f for amount=$%.2f, rate=%.2f per cent, years=%d\n",
fv(amount, rate / 100, years), amount, rate, years);
return 0;
}

/* Compute future value */


float fv(float amount, float rate, unsigned int years) {
return amount * pow(1 + rate, years);
}

5
Comments:

● We use pow function from the standard math library


● Note that the amount and rate are represented as floats, while the number of years is
unsigned integer
● Interest rate is accepted in percentage and converted to a decimal format

You invest $x for one year earning 10% interest. In one year you receive $100. What is x closest
to?

● $110
● $89
● $101
● $91

Answer: 4th choice: 𝑥 × 1. 1 = 100 ⇒ 𝑥 = 100/1. 1 ≈ 90. 9

Example 1.6. Write a program that computes future value of multiple yearly investments. For
example, an investor is planning to allocate predefined amounts into a savings account.

This program implements the above by obtaining multiple inputs.

#include <stdio.h>

#include <math.h>

#define MAX_YEARS 10

float fv(float amount, float rate, unsigned int years);

int main() {
float amount[MAX_YEARS], rate[MAX_YEARS];
unsigned int num_years;
float total_fv = 0;
printf("Enter number of years for investments: ");
scanf("%u", & num_years);
for (int year = 0; year < num_years; year++) {
printf("Enter amount, rate in year %d: ", year);
scanf("%f", & amount[year]);
scanf("%f", & rate[year]);
total_fv += fv(amount[year], rate[year] / 100, num_years - year);
}
printf("FV=$%.2f\n", total_fv);
return 0;

6
}

/* Compute future value */


float fv(float amount, float rate, unsigned int years) {
return amount * pow(1 + rate, years);
}

Comments:

● Using the following inputs (verified in


https://www.calculator.net/future-value-calculator.html?cyearsv=3&cstartingprinciplev=0&
cinterestratev=6&ccontributeamountv=100&ciadditionat1=beginning&printit=0&x=44&y=
14):
○ Number of years: 3
○ Year 0: $100 6%
○ Year 1: $100 6%
○ Year 2: $100 6%
○ FV=$337.46
● Note the use of arrays pre-allocated to the defined symbolic constant MAX_YEARS

Is using arrays necessary in this program?

● Yes
● No

Answer: No. Even though we store input numbers in arrays, only one value is used at a time,
which can be a simple variable.

1.3 Types, Operators, and Expressions


We demonstrate control flow concepts by carefully tracing a program in the following example.

Example 1.7.1 Depict a pyramid for a given number of rows.

Program:

#include <stdio.h>

int main() {

1
Hal Greenwald, CS531 Lecture Notes, Week 1

7
int num_rows, temp;
printf("Enter the number of rows in pyramid:");
scanf("%d", & num_rows);
printf("\n");
for (int row = 1; row <= num_rows; row++) {
for (int space = 1; space <= num_rows - row; space++)
printf(" ");
for (int star = 1; star <= 2 * row - 1; star++)
printf("*");
printf("\n");
}
return 0;
}

Output:

Enter the number of rows in pyramid: 3

*
***
*****

Comments:

● The number of stars is increasing by 2 in each row: 1, 3, 5


○ 𝑠𝑡𝑎𝑟𝑠 = 2 × 𝑟𝑜𝑤𝑠 − 1
● The middle star in the last row is in the following position:
○ 𝑚𝑖𝑑𝑝𝑜𝑠 = (2 × 𝑛𝑢𝑚𝑟𝑜𝑤𝑠 − 1 − 1)/2 = 𝑛𝑢𝑚𝑟𝑜𝑤𝑠 − 1
■ Total number of stars: 2 × 𝑛𝑢𝑚𝑟𝑜𝑤𝑠 − 1
■ Less the middle star: − 1
■ Half of the remaining stars will be preceding the middle star
● The number of spaces before the middle position forms the following sequence:
○ 𝑛𝑢𝑚𝑟𝑜𝑤𝑠 − 1, 𝑛𝑢𝑚𝑟𝑜𝑤𝑠 − 2, ... , 0

Trace:

row #spaces #stars

1 2 1

2 1 3

3 0 5

Suppose we modify one line in the code as follows.

8
#include <stdio.h>

int main() {
int num_rows, temp;
printf("Enter the number of rows in pyramid:");
scanf("%d", & num_rows);
printf("\n");
for (int row = 1; row <= num_rows; row++) {
for (int space = 1; space <= num_rows - row - 1; space++)
printf(" ");
for (int star = 1; star <= 2 * row - 1; star++)
printf("*");
printf("\n");
}
return 0;
}

What will be the output?

● A pyramid shifted to the left


● A pyramid shifted to the right
● A pyramid except for the last row
● No change

Answer: third choice - observe by running.

Exercise 1.1 (20 minutes). Modify the pyramid code to display it upside down.

Solution (note one line change):

#include <stdio.h>

int main() {
int num_rows, temp;
printf("Enter the number of rows in pyramid:");
scanf("%d", & num_rows);
printf("\n");
for (int row = num_rows; row >= 1; row--) {
for (int space = 1; space <= num_rows - row; space++)
printf(" ");
for (int star = 1; star <= 2 * row - 1; star++)
printf("*");
printf("\n");
}
return 0;
}

9
10

You might also like