LABORATORY 01

Introductory Concepts for the C/C++ Languages

Duration: 2 hours Language: C / C++ Environment: Code::Blocks / Visual Studio / GCC PDF handout RO versiunea română

The first session clarifies what happens between the moment we type text into an editor and the moment the computer executes a program. Understanding the four stages - writing, compiling, linking, execution - explains most of the errors you will run into for the rest of the semester.

1Lab objectives

  • Installing and configuring a C/C++ development environment
  • Following the four stages through to a working executable file
  • Telling compilation errors apart from linking errors
  • Recognizing syntactic units: identifiers, keywords, operators, constants
  • Writing, compiling, and running your first program

2Working environment

  • IDE Code::Blocks or Visual Studio
  • C GCC / MinGW compiler
  • C++ G++ compiler
  • alt. Text editor + command line
Compiling from the command line If you want to see the stages explicitly, use the terminal: gcc program.c -o program.exe then ./program.exe

3The stages of producing an executable

Source program .c / .cpp Compiler + preprocessor Object code .obj / .o Linker + libraries Executable .exe A compile error stops the process before the object code; a link error only shows up at the next step.
Fig. 1 - The main stages gone through to produce an executable program
StageWhat it doesResultTypical errors
Writingwriting the code in an editor or IDE.cpp file-
Preprocessingexpands #include and #defineexpanded source codeheader file not found
Compilationtranslates the source into machine code.obj filewrong syntax, incompatible type, undeclared variable
Linkinglinks object modules and libraries together.exe filefunction declared but not defined, missing main
Executionloads the program into memory and runs it-division by zero, invalid memory access
How to tell which stage you got wrong in A message pointing to a line number in your file is a compilation error. A message like undefined reference to ..., with no line number, is a linking error: the function was declared, but its body was not found anywhere.

4Basic elements of the language

Writing a program uses syntactic units that fall into a few categories:

CategoryDescriptionExamples
Identifiersnames given to types, variables, functionsradius, _maxx, a5, A_B_C
Keywordsreserved identifiers, with predefined meaningint, while, return, class
Punctuation marksdelimit regions of code[ ] ( ) { } , : ; #
Whitespaceseparators, improve readabilityspace (32), tab (9), newline (10)
Operatorsspecify the operations performed+ - * / % = == &&
Constantsfixed values, numeric or strings23, 3.14, 'A', "text"

Rules for identifiers

IdentifierValid?Reason
Radiusyesstarts with a letter
radiusyesdifferent from Radius - the language is case sensitive
_maxxyescan start with an underscore
a5yesthe digit is not in the first position
5anothe first character is a digit
A%Bno% is not an allowed character
Case sensitiveC/C++ distinguishes between uppercase and lowercase. Total, total, and TOTAL are three completely distinct variables. This is a frequent source of "undeclared variable" errors for beginners.

5Program structure

The general structure of a program is made up of three zones:

ZoneContentsMandatory?
I - preprocessing directives#include, #defineoptional
II - global declarationstypes, function prototypes, global variablesoptional
III - function definitionsfunction bodies, including main()mandatory
The main() functionProgram execution always starts with main(). It is unique and cannot be overloaded. Unlike Pascal, in C/C++ functions cannot be defined one inside another.

6The first program

first.c - the C version
#include <stdio.h>        // zone I: preprocessing directives

#define PI 3.14159         // symbolic constant

int runCount = 0;          // zone II: global variable

int main(void)             // zone III: definition of the main function
{
    float radius, area;    // local declarations

    printf("Enter the radius: ");
    scanf("%f", &radius);

    area = PI * radius * radius;

    printf("Circle area = %.2f\n", area);

    return 0;              // 0 = program finished successfully
}
first.cpp - the C++ version
#include <iostream>
using namespace std;

const double PI = 3.14159;   // in C++, const is preferred over #define

int main()
{
    double radius, area;

    cout << "Enter the radius: ";
    cin >> radius;

    area = PI * radius * radius;

    cout << "Circle area = " << area << endl;

    return 0;
}
The key differenceIn C, input/output is done with functions (printf, scanf) that take an explicit format. In C++, streams are used (cout, cin), and the type is deduced automatically by the compiler - safer and more convenient.

7Code workshop

Here you can write and run C code directly on the page. The program runs in the browser, with no compiler installed: press Run and watch the output below. The Step by step button executes the program instruction by instruction and shows, on the right, the value of each variable at that moment.

The structure of a C program - run it, then change it
#include <stdio.h>

int main(void)
{
    printf("Hello, world!\n");
    printf("My name is %s and I am %d years old.\n", "Ana", 19);
    return 0;
}
Try thisTry removing \n from the first printf and run it again. Notice that the two lines end up on the same line - \n is the only thing that moves the cursor to the next line.
Exercise - print a business card
#include <stdio.h>

int main(void)
{
    /* Complete the program so it prints exactly what you see
       in the "expected output" column.
       You will need four printf calls. */

    printf("+----------------------+\n");

    return 0;
}

8Exercises with automatic checking

This is where you write the code. The ✓ Check button runs your program on several data sets and shows you right away where the result differs. At the end you submit the track you chose, and the instructor grades it automatically.

Every exercise has the program already started, and the comments tell you what is left to add. Write the code, press ✓ Check and read what each failed test says. If you get stuck, open the hints one at a time. You may also print messages for the user (such as Enter n:); the test looks at what you print at the end.

P1

Your first program

Print the message Hello, world!, followed by a newline.

outputHello, world!
#include <stdio.h>

int main(void)
{
    /* Write a printf here. The text goes between double quotes,
       and the \n at the end moves to the next line. */

    return 0;
}
P2

The sum of two numbers

Read two integers and print their sum.

input2 3
output5
#include <stdio.h>

int main(void)
{
    int a, b;
    scanf("%d %d", &a, &b);

    /* Reading is done: a and b already hold the typed values.
       Print a + b with printf("%d\n", ...); */

    return 0;
}
P3

The area of a circle

Read the radius r of a circle (a real number) and print its area with two decimals. Use the constant PI from the skeleton.

input1
output3.14
#include <stdio.h>

#define PI 3.14159265

int main(void)
{
    double r;
    scanf("%lf", &r);

    /* Area = PI * r * r.
       A real number is printed with %f; %.2f keeps two decimals. */

    return 0;
}
P4

The rectangle

Read the length and width of a rectangle (integers). Print the perimeter and the area on one line, separated by a space.

input4 3
output14 12
#include <stdio.h>

int main(void)
{
    int L, l;
    scanf("%d %d", &L, &l);

    /* The perimeter is 2 * (L + l), the area is L * l.
       A single printf can print two values: printf("%d %d\n", ..., ...); */

    return 0;
}
P5

Celsius to Fahrenheit

Read a temperature in degrees Celsius (a real number) and print it in degrees Fahrenheit, with one decimal: F = C · 9 / 5 + 32.

input100
output212.0
#include <stdio.h>

int main(void)
{
    double c, f;
    scanf("%lf", &c);

    /* Compute f. Careful: in C, 9 / 5 between two integers gives 1, not 1.8!
       Write the formula so that it works with real numbers. */

    printf("%.1f\n", f);
    return 0;
}

Problems start from an empty main. The output format must be followed exactly (spaces and newlines do not matter unless the statement says otherwise), so do not print prompts. The visible tests cover only the simple cases; grading also runs hidden tests chosen to catch the edge cases.

A1

Seconds to hours, minutes and seconds

Read a whole number of seconds s (0 ≤ s < 1 000 000). Print the duration in the format hh:mm:ss, each field with at least two digits.

input3661
output01:01:01
#include <stdio.h>

int main(void)
{
    /* write your solution here */

    return 0;
}
A2

Distance between two points

Read the real coordinates x1 y1 x2 y2 of two points in the plane. Print the distance between them, with three decimals.

input0 0 3 4
output5.000
#include <stdio.h>

int main(void)
{
    /* write your solution here */

    return 0;
}
A3

Change in coins

Read an amount s in cents (integer, 0 ≤ s ≤ 100 000). Print the minimum number of 50, 10, 5 and 1 cent coins that make it up, in that order, on one line.

input87
output1 3 1 2
#include <stdio.h>

int main(void)
{
    /* write your solution here */

    return 0;
}
A4

Average with and without truncation

Read three integers. On one line, print their average computed with integer division and the real average, with two decimals.

input7 8 10
output8 8.33
#include <stdio.h>

int main(void)
{
    /* write your solution here */

    return 0;
}

9Work tasks

  • Install the development environment and create a new console application project.
  • Write, compile, and run the program that computes the area of a circle.
  • Intentionally delete a ; character and read the error message - note the line indicated.
  • Call a non-existent function (for example compute();) and observe that the error occurs at link time, not at compile time.
  • Check that the language is case sensitive: declare int sum; and use Sum.
  • Test which of the identifiers in the table above are accepted by the compiler.
  • Write the same program in both versions, C and C++, and compare the size of the resulting executable.

10Extended application

ExtensionWrite a program that reads the radius and prints, in an aligned table, the circle's area and circumference, and the sphere's surface area and volume. Use #define for PI and %8.3f formatting for alignment. Compare the results with those obtained using M_PI from <math.h> and explain any differences.

11Review questions

12Resources