You are on page 1of 9

Department of Mechatronics and Control Engineering

University of Engineering and Technology Lahore

LAB 2: BASIC CONCEPTS IN C LANGAUGE


MCT-242L: Computer Programming-I Lab (Fall-2022)

OBJECTIVE:
This lab will introduce basic concepts of C Language. At the end of this lab, you should be able to:

• Add both types of C language comments in your program


• Familiarize with C Language Pre-processor directives
• Create new Macros and use pre-defined Macros in your program
• Input/Output stream for C Language Program

APPARATUS:
• Laptop\PC with following tools installed o Visual Studio Code with C/C++ and Code Runner
Extensions o C/C++ mingw-w64 tools for Windows 10

COMMENTS IN C:

A comment is an explanation or description of the source code of the program. It helps a developer explain
logic of the code and improves program readability. A simple comment can save a significant amount of
time otherwise wasted on having to re-understand the code. Comments can also be used to display
identifying information: the program name, the date written, the author, the purpose of program, and so
forth. At compilation time, comments are ignored by the compiler.

There are two types of comments in C:

1) Multi-line Comments: A comment that starts with a slash asterisk /* and finishes with an asterisk
slash */ and you can place it anywhere in your code, on the same line or several lines. i.e., anything
between /* and */ will be considered as comment. These comments must be terminated otherwise all the
program will be turned into comments.

2) Single-line Comments: which uses a double slash // dedicated to comment single lines. i.e., anything
after // will be considered as comment till end of line.
/* This is an example of multi-line comments in C Language Program.
This type of comment can span over multiple lines */
// Example of single-line comment in C Language Program

Examples of C Language Comment


PRE-PROCCESSOR DIRECTIVES IN C:

1|Page ComputerProgramming-ILab
Department of Mechatronics and Control Engineering
University of Engineering and Technology Lahore

The C preprocessor is exactly what its name implies. It is a program that processes our source program
before it is passed to the compiler. The preprocessor is a text substitution tool that modifies the source code
before it is compiled. This modification is done according to the preprocessor directives that are included in
the source files. The directives are easily distinguished from normal programming code in that they all start
with a hash sign (#). They must always appear as the first non-whitespace character on a line and do not
need to end with a semicolon. These preprocessor directives extend only across a single line of code. As
soon as a newline character is found the preprocessor directive is considered to end.
The preprocessor directives provide the ability for the inclusion of header files, macro expressions,
conditional compilation, and line control etc. Here we discuss only two important preprocessor directives:

1. #include (including files)

The #include directive inserts the contents of a file into the current source file. Its most common use is to
include header files (.h), both user-defined and library ones. Library header files are enclosed between angle
brackets (<>). This tells the preprocessor to search for the header in the default directory where it is
configured to look for standard header files.
Header files that you create for your own program are enclosed within double quotes (""). The preprocessor
will then search for the file in the same directory as the current file. In case the header is not found there, the
preprocessor will then search among the standard header files.
#include <fileName> /* search library directory */
#include "fileName" /* search current, then default */
Syntax for #include Directive
#include <stdio.h> /* search library directory */
#include "myfile.h" /* search current, then default */
Examples of #include Directive
The double quoted form can also be used to specify an absolute or relative path to the file.

#include "c:\myfile.h" /* absolute path of the file*/


#include "..\myfile.h" /* path relative to the current directory*/
Path Options with Double Quote #include Directive
2. #define (define macros)
Another important directive is #define, which is used to create compile-time constants, also called macros.
After the directive, the name of the constant is specified followed by what it will be replaced by. There are
two kinds of macros: Object-like macros resemble data objects when used, function-like macros resemble
function calls.

Object-like Macros
An object-like macro is a simple identifier which will be replaced by a code fragment. It is called object-like
because it looks like a data object in code that uses it. They are most used to give symbolic names to numeric
constants. To define object-like macros we can use #define directive. Its format is:
#define identifier replacement

2|Page ComputerProgramming-ILab
Department of Mechatronics and Control Engineering
University of Engineering and Technology Lahore

Syntax to Define a Macro


When the preprocessor encounters this directive, it replaces any occurrence of identifier in the rest of the
code by replacement. This replacement can be an expression, a statement, a block or simply anything.

By convention, constants should be named in uppercase letters with each word separated by an underscore.
That way, they are easy to spot when reading the source code. Wherever, DELAY is found as a token, it is
replaced by with 20. (see following example)
#define DELAY 20
Macro Example for a Numeric Value
Example 2.1: Use of an Object-like Macro
/* Example_2_1.c: Use of an Object-like Macro
----------------------------------------------------------------------------
This example program demonstrates the definition and usage of an Object-like
Macro in a C Language Program.
----------------------------------------------------------------------------
Written by Shujat Ali (engrshujatali@gmail.com) on 19-Sep-2021.
IDE: Visual Studio Code 1.60.0
C Compiler: GCC (Rev. 5, Built by MSYS2 Project) 10.3.0 */
#include<stdio.h> // include library file
#define PI 3.141593 // macro definition

int main()
{ printf("The value of Pi is %f", PI); // display the macro
value
Return
0;
}

Program Output The value of Pi is 3.141593

Undefine Macro

A #define directive should not be used to directly override a previously defined macro. Doing so will give a
compiler warning unless the macro definitions are the same. To redefine an existing macro, it first needs to
be undefined using the #undef directive. Attempting to undefine a macro that is not currently defined will
not generate a warning.

#define DELAY 20
#undef DELAY #define
DELAY 10
Example of Redefining a Macro

3|Page ComputerProgramming-ILab
Department of Mechatronics and Control Engineering
University of Engineering and Technology Lahore

Predefined Macros

Macro Description
__FILE__ The name and path of current file
__LINE__ The current line number
__DATE__ The compilation date in MM DD YYYY format
__TIME__ The compilation time in HH:MM:SS format
__func__ The name of the current function. Added in C99
__STDC__ Defined as 1 if the compiler complies with the
ANSI C standard.
There are several macros that are predefined by the compiler. To distinguish them from other macros, their
names begin and end with two underscores. The standard macros that all ANSI C-
compliant compilers include are listed in the following table. A common use for predefined macros is to
provide debugging information.
Example 2.2: Use of Pre-defined Macros
/* Example_2_2.c: Use of Pre-defined Macros
-----------------------------------------------------------------------------
This example program illustrates the use of Pre-defined Macros in C Language.
It will display current function, line, file name and its compilation time.
-----------------------------------------------------------------------------
Written by Shujat Ali (engrshujatali@gmail.com) on 19-Sep-2021.
IDE: Visual Studio Code 1.60.0
C Compiler: GCC (Rev. 5, Built by MSYS2 Project) 10.3.0 */
#include<stdio.h>

int main()
{
// display pre-defined Macros values printf("This statement is in
function %s at line %d", __func__, __LINE__); printf("\nCompilation time
of %s is %s", __FILE__, __TIME__);

return 0;
}

This statement is in function main at line 15


Program Output
Compilation time of Example_2_2.c is 11:41:51
Function-like Macros
Macros can also be used to define compile-time functions that looks like a function call. These are called
function-like macros. To define a function-like macro, the same #define directive is used, but with a pair
of parentheses immediately after the macro name. For example:
#define SUM(a, b, c) a + b + c #define SQR(c) (c)*(c) int
x = SQR(2+3); // x = (2+3)*(2+3) = (5)*(5) =25
int y = SUM(3, 2, 5); // y = 3 + 2 + 5 = 10

4|Page ComputerProgramming-ILab
Department of Mechatronics and Control Engineering
University of Engineering and Technology Lahore

Definition and Use of Function-like Macros


Note the extra parentheses in the macro SQR(c) definition that are used to avoid problems with operator
precedence. Without the parentheses SQR(2+3) would give an incorrect result, as the multiplication would
then be carried out before the addition.

Advantages of Using A Macro


• The speed of the execution of the program is the major advantage of using a macro.
• It saves a lot of time that is spent by the compiler for invoking/calling the functions.
• It reduces the length of the program.

Although macros can be powerful, they tend to make the code more difficult to read and debug. Macros
should therefore only be used when they are necessary and should always be kept short. C code such as
constant variables, enums, and inline functions can often accomplish the same goal more efficiently and
safely than #define directives can.
TASK 2.1: Pre-defined Macros [1 point]
Write a C language program that displays all the predefined macro
values on screen for this file.
The value of __FILE__ macro is Task_2_1.c
The value of __LINE__ macro is 16
The value of __DATE__ macro is Sep 19 2021
Sample Output
The value of __TIME__ macro is 16:11:20
The value of __func__ macro is main
The value of __STDC__ macro is 1
DISPLAYING OUTPUT IN C:
As you know, the printf function, available in stdio.h file, can be used to print values and variables to the
standard output stream. This is done by embedding format specifiers into the string where the value is to be
printed. Each specifier must be matched by a corresponding argument to printf of the correct type, as seen
in the following example
printf("This statement is in function %s at line %d", __func__, __LINE__);
Example of Format Specifiers for printf Function
Pre-defined macro __func__ is a string and __LINE__ is an integer value therefor we have embedded format
specifiers %s and %d to the positions in string where we want to print their values. We will see the complete
list of these format specifiers in our next lab.

READING INPUT FROM TERMINAL IN C:


Input from the command line can also be passed to a program while it is running, using for instance the scanf
function. The first argument to this function is a formatting string that uses the same placeholders as printf,
such as %d for accepting an int type. The second argument is the address to a variable that will hold the value
of the expected input type.
scanf("format_specifier", variable_address);
scanf("%d",
&var);

5|Page ComputerProgramming-ILab
Department of Mechatronics and Control Engineering
University of Engineering and Technology Lahore

Syntax of scanf Function

Let’s discuss an example program to see the scanf function in action.


Example 2.3: Sum of Two Input Numbers
/* Example_2_3.c: Sum of Two Input Numbers
-----------------------------------------------------------------------
This example program takes two numbers as user input and display their
sum on the screen.
-----------------------------------------------------------------------
Written by Shujat Ali (engrshujatali@gmail.com) on 19-Sep-2021.
IDE: Visual Studio Code 1.60.0
C Compiler: GCC (Rev. 5, Built by MSYS2 Project) 10.3.0 */
#include<stdio.h>

int main()
{ int num1, num2; // define two int
variables
printf("Enter 1st number >> "); scanf("%d",
&num1); // take 1st input number
printf("Enter 2nd number >> "); scanf("%d", &num2);
// take 2nd input number
printf("The sum of %d and %d is %d", num1, num2, num1 +
num2); return 0;
}

Enter 1st number >> 27


Program Output Enter 2nd number >> 31
The sum of 27 and 31 is 58

TASK 2.2: Double the Input Number [1 point]


Write a C language program that takes a number as user input and
returns it double.
Enter any number you like >> 43
Sample Output
Double of the value you entered is 86

TASK 2.3: Double the Input Number (Updated) [1 point]


Modify Task 2.2 such that it shows both values at the output i.e., the
value user entered and double of that value.
Enter any number you like >> 76
Sample Output
Double of 76 is 152

6|Page ComputerProgramming-ILab
Department of Mechatronics and Control Engineering
University of Engineering and Technology Lahore

TASK 2.4: Quote the Input Number [1 point]

7|Page ComputerProgramming-ILab
Department of Mechatronics and Control Engineering
University of Engineering and Technology Lahore

Write a C program that a number as input from user and displays it with
a double quote on it.
Enter any number you like >> 25
Sample Output
You entered "25"

TASK 2.5: Mini Calculator [1 point]


Write a program that takes two inputs from user and displays their sum,
difference, product, and quotient.
Enter 1st number >> 20
Enter 2nd number >> 5
Sum of 20 and 5 is 25
Sample Output Difference of 20 and 5 is 15
Product of 20 and 5 is 100
Quotient of 20 and 5 is 4

TASK 2.6: Properties of a Square [1 point]


Write a program that takes the length of a side of a square and returns
its perimeter and area. P = 4x and A = x2
Enter length of side of Square >> 8
Sample Output Perimeter of the square is 32 units
Area of square is 64 sq. units

TASK 2.7: Properties of a Sphere [2 points]


Write a program that takes the radius of sphere and returns its surface
=4
area and volume. A = 4 𝜋𝑟2 and 𝑉 𝜋𝑟3 (Define macro for value of π)
3
This program calculates area and volume of the sphere.
Enter radius of the Sphere >> 2.5
Sample Output
Surface are of the sphere is 78.539825 sq. units
Volume of the sphere is 49.087391 cubic units

TASK 2.8: Temperature Units Converter [2 points]


Write a C language program to convert user input temperature value in
degree centigrade into Fahrenheit. Formula for conversion is C = (F
32)/1.8
This program converts centigrade into Fahrenheit.
Sample Output Enter temperature in degree Centigrade >> 27
Value of temperature in Fahrenheit is 80.600000 F

Create a Visual Studio Code Workspace, Lab_2 and c files (Task_2_1.c to Task_2_8.c) for individual tasks
and add them to Lab_2 workspace. You need to submit all these files on Google Classroom as part of this
lab evaluation.

|Page ComputerProgramming-ILab
Department of Mechatronics and Control Engineering
University of Engineering and Technology Lahore

|Page ComputerProgramming-ILab

You might also like