Lab 04

Download as pdf or txt
Download as pdf or txt
You are on page 1of 8

4.

Lab# 04 C Programming Introduction


In this lab, we study the C programming introduction. C is a general-purpose programming
language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a prevalent language,
despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX
operating system.

4.1 Learning Outcome


After completing this lab, the student will be able to:
 Compile the C program in gcc compiler
 Difference between C and C++
 Explain the compilation process

4.2 Why Learn C?


 It is one of the most popular programming languages in the world.
 If you know C, you will have no problem learning other popular programming
languages, such as Java, Python, C++, C#, etc, as the syntax is similar.
 C is faster than other programming languages, like Java and Python.
 C is very versatile; it can be used in applications and technologies.

4.3 Difference between C and C++


 C++ was developed as an extension of C, and both languages have almost the same
syntax.
 The main difference between C and C++ is that C++ supports classes and objects,
while C does not.

To start using C, you need two things:

 A text editor like notepad writes C code.


 A compiler, like GCC, translates the C code into a language that the computer will
understand

Programs written in C are compiled with the gcc compiler in a Linux environment. A C file
should have extension .c e.g. test.c. The general format to compile a C program by gcc compiler
is given below:

$ gcc first.c -o first


Here first.c contains the source code, and first is the resultant executable file. If the name of
the output file is not specified with -o, gcc names the output file as a.out by default. The file is
executed as:

$ ./first

Here’s your first program in this lab; give it a try.

40
Example 1
#include <stdio.h>
int main()
{
printf(“\n\t One OS to Rule Them All !! \n”);
return 0;
}
4.4 Step-by-Step Compilation Using gcc:
The compilation is a multi-stage process involving several tools, including the GNU Compiler
itself (gcc), the GNU Assembler as, and the GNU Linker id. The sequence of commands
executed by a single invocation of GCC consists of the following stages:

1. Pre-processing (to expand macros)


2. Compilation (from source code to assembly language)
3. Assembly (from assembly language to machine code)
4. Linking (to create the final executable)
You are encouraged to look at the intermediate versions of our program ‘first.c’ as we go
through various stages of compilation.

4.4.1 The pre-processor


The first stage of the compilation process is using the pre-processor to expand macros and
included header files. To perform this stage, GCC executes the following command:
$ gcc –E first.c –o first.i
The result is a file ‘first.i’ containing the source code with expanded macros. By convention,
pre-processed files are given the file extension ‘.i’ for C programs.

4.4.2 The Compiler


The process's next stage is the compilation of pre-processed source code into assembly
language. The command-line option -S instructs gcc to convert the pre-processed C source
code to assembly language without creating an object file.

$ gcc -S first.i
However, we didn’t specify a ‘–o’ option. This is because gcc would automatically name the output
file ‘first.s.’

4.4.3 The Assembler:


The purpose of the assembler is to convert assembly language into machine code and generate an
object file. When there are calls to external functions in the assembly source file, the assembler
leaves the addresses of the external functions undefined, to be filled in later by the linker. The
assembler can be invoked with the following command line:
$ gcc -c first.s

4.4.4 The Linker:


The final stage of compilation is linking object files to create an executable. An executable requires
many external functions from system and C run-time (crt) libraries. Consequently, the actual link
commands used internally by GCC are complicated. Fortunately, though, the entire linking process
is handled transparently by gcc when invoked as follows:

41
$ gcc first.o –o first
This links the object file ‘first.o’ to the C standard library and produces an executable file ‘first.’

4.5 C Output
In C programming, printf() is one of the main output function. The function sends formatted
output to the screen. For example

Example : C output
#include <stdio.h>
int main()
{
//Displays the string inside quotations
printf("C Programing");
return 0;
}

How does this program work?

 All valid C programs must contain the main() function. The code execution begins
from the start of the main() function.
 The printf() is a library function to send formatted output to the screen. The
function prints the string inside quotations.
 To use printf() in our program, we need to include stdio.h header file using
the #include <stdio.h> statement.
 The return 0; statement inside the main() function is the "Exit status" of the
program. It's optional.

4.6 C Input
In C programming, scanf() is one of the commonly used functions to take input from the
user. The scanf() function reads formatted input from the standard input, such as
keyboards.

Example 2
#include <stdio.h>
int main()
{
int testInteger;
printf("Ënter an integer");
scanf("%d", &testInteger);
printf("Number = %d", testInteger);
return 0;
}

42
Here, we have used %d format specifier inside the scanf() function to take int input
from the user. When the user enters an integer, it is stored in the testInteger variable.

Notice that we have used &testInteger inside scanf(). It is because &testInteger gets
the address of testInteger, and the value entered by the user is stored in that address.

4.7 Format Specifiers for I/O


As you can see from the above examples, we use:

 %d for int
 %f for float
 %lf for double
 %c for char
Here's a list of commonly used C data types and their format specifiers.

4.8 I/O Multiple Values


Here's how you can take multiple inputs from the user and display them.

43
Example 3

#include <stdio.h>
int main()
{
int a;
float b;
printf("Ënter an integer and then a float");
//Taking multiple inputs
scanf("%d %f",&a,&b );
printf("You entered %d and %f", a , b);
return 0;
}

4.9 C malloc()
The name "malloc" stands for memory allocation. The malloc() function reserves a
memory block of specified bytes. And it returns a pointer of the void, which can be casted
into pointers of any form.

The above statement allocates 400 bytes of memory. It's because the size of the float is 4
bytes. And the pointer ptr holds the address of the first byte in the allocated memory.

The expression results in a NULL pointer if the memory cannot be allocated.

4.10 C free()
Dynamically allocated memory created with malloc() doesn't get freed independently.
You must explicitly use free() to release the space.

44
This statement frees the space allocated in the memory pointed by ptr.

Example 4:

In this code, we dynamically allocate memory using the malloc() function based on the
integer value entered by the user. The allocated memory is released using free()function at
the end of the code execution.

#include <stdio.h>
#include <stdlib.h>
int main()
{
int a;
int i;
int *ptr;
int sum=0;
int n;
printf("Ënter number of elements:");
scanf("%d", &n);
ptr = (int*)malloc(n * sizeof(int));
//If memory cannot be allocated
if(ptr == NULL){
printf("Error! memory not allocated,");
exit(0);
}
printf("Enter elements: ");
for(i=0; i<n; ++i){
scanf("%d", ptr + i);
sum +=*(ptr + i);
}
printf("Sum = %d", sum);
printf(“\n”);
//Deallocating the memory
free(ptr);
return 0;
}

45
Here, we have dynamically allocated the memory for n number of int.

4.11 Null-Pointer Check


Always do a null-pointer check to see if malloc allocated memory successfully. After
allocating memory, a null value returned to your program should display an error message and
exit gracefully. Not checking for the NULL pointer is the major source of programs crashing.

46
Lab Task
Write a C program that:
Prints a welcome message and then prompts the user to enter an integer (e.g., age) and a float (e.g., height
in meters) and displays the entered values back to the user with appropriate labels.

Extend the program to Prompt the user to enter the number of elements for a float array (e.g., temperatures
recorded over a week). Next you will dynamically allocate memory for this array using malloc() and
perform a NULL pointer check after allocation. If the allocation fails, display an error message and exit the
program gracefully. Prompt the user to enter values to populate the array. Calculate and display the
maximum and minimum values from the array and then Free the dynamically allocated memory at the end.
Ensure the program includes a check for NULL pointers after every dynamic memory allocation

Provide screenshots for each stage of compilation, ie Preprocessing, compilation, assembly and linking.

You might also like