Lab 3

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

Lab 03

Objectives

To Learn about compiler installation, basic C program, basic data types, basic input or output and the
use of variables.
Instructions
• Read, the text provided in bulleted form in different paragraphs, with proper attention.
• Perform all examples as shown.
• First complete the examples and tasks then try and test your own programs.

1. Programming
A programming language is a formal language designed to communicate instructions to a machine,
particularly a computer. Programming languages can be used to create programs that control the behavior
of a machine and/or to express algorithms precisely
1.2 Compiler
A compiler is a computer program (or set of programs) that transforms source code written in a
programming language (the source language) into another computer language (the target language, often
having a binary form known as object code). The most common reason for wanting to transform source
code is to create an executable program.
1.3 IDE
An Integrated Development Environment (IDE) is a software that provides comprehensive consolidated
environment to computer programmers to develop software applications. An IDE consists of various
components such as a code editor, build automation tools, debuggers, and sometimes visual designers. We
will use the Dev-C++ IDE to develop C programs. Dev-C++ is a free, open-source, lightweight IDE for C and
C++ programming that uses the MinGW (Minimalist GNU for Windows) port of the GCC compiler,
supporting efficient program development on the Windows platform.
1.3.1 Basic Components of an IDE
• Code Editor (CE):
A code editor is a specialized text editor designed for writing and editing the source code of computer
programs. It is an essential part of an IDE, providing features like syntax highlighting and code formatting
to make programming easier and more efficient. In Dev-C++, the built-in code editor supports both C and
C++ languages, allowing you to write, edit, and organize your code within a single interface.
• Build Automation Tools (BAT):
Build automation tools streamline the process of creating software builds. This involves compiling source
code into object code, linking libraries, and generating the final executable file. In Dev-C++, the build
automation process is handled using the MinGW compiler, which compiles and links your code into a
runnable program. These tools simplify the process, allowing for easy building and testing of software
without manual intervention.
• Debugger:
The debugger is a critical component of an IDE that assists in testing and identifying bugs in software. Dev-
C++ integrates with the GDB (GNU Debugger) to help developers test their code, set breakpoints, inspect
variables, and track down issues in complex applications. This makes debugging an efficient process,
allowing you to find and fix errors directly within the IDE.
1.3.2 Few Features of Dev-C++
• Syntax highlighting
• Code completion
• Debugging
• Code searching
• Project templates
• Single-platform compilation

1.4 Install Compiler


Step#1: https://www.embarcadero.com/free-tools/dev-cpp/free-download

Step#2: After downloading Extract the folder

Figure 1: Zipped Setup of Dev C++

Step#3: Now run the Embarcadero_Dev-Cpp_6.3_TDM-GCC_9.2_Setup

Step#4: After running the setup, follow the on-screen instructions:


• Choose the language (English or any other preferred language).
• Click Next and accept the License Agreement.
• Choose the installation path or leave it as default.
• Click Install and wait for the installation to complete.

Step#5: Creating a New File:


After installation, open Dev C++ from your desktop or start menu.
To start a new project:
• Click File > New > Source File.
• Write your C code in the editor.
• To save your file, go to File > Save As, and save it with a .c extension (e.g., main.c).
Figure 2: Front View of Dev C++

Figure 3:Select a new project


Figure 4: Creating a new project by selecting console application option

Figure 5: Write the project name and click “OK”


Figure 6: Save your project in non- C drive and create a folder and create your all labs in that folder

Figure 7: After saving, your file main.c is created


Figure 8: Save your file with .c extension to run the program

Before writing a program following points should be kept in mind.


1. Comment your code properly by enclosing the statements in % signs.
2. Each statement should be terminated by a semi-colon (;).
3. Indent your code properly.

Step#6: A Simple Program

Figure 9: Program on console


How does this program work?
• All valid C programs must contain one main() function. The code execution begins from the start
of main() function.
• Compiler reads source code from top to bottom and left to right.
• printf() is a library function, which is used to print to standard output stream.
• The printf() function is declared in "stdio.h" header file.
• A header file is a file that contains C/C++ functions declarations and macros and constants definitions.
• stdio.h is a header file for input and output operations.
• # include is a preprocessor directive whose main job is to include the code from another file, in this case stdio.h.
• Preprocessor directives are instructions to the compiler unlike program statements which are instructions to CPU.
• In most cases, compiler generates error messages when it encounters printf() or any other library function
and it does not find its respective header file included in the source code
• The return 0; statement is the "exit status or code" of the program. Usually 0 is considered as successful
clean exit.
• String enclosed /* ... */ is a comment. Compiler ignores comment. There are two types of comments
in C language i.e. single line and multiline comment.
• Every program statement must be terminated by ’;’..

Step#7: Seeing the Output:


Compile and run the program by clicking on the small square option of the Dev C++ or press F11a from
keyboard to see the output. A black screen will appear showing your output

Figure 10: Output of Program


1.5 Input/Output (I/O) Operations In C
1.4.1 Input/Output (I/O) Operations in C
C programming has several built-in library functions to perform Input/Ooutput tasks. Two
commonly used functions for Input/Output are printf()and scanf().
The scanf() function reads formatted input from input entered from keyboard by the user
whereas the printf() function sends output to the screen.

Program # 2 displaying output

Figure 11: Program


Figure 12: Output

1.6 Escape Sequence in C Language


Escape sequence is a special character that causes "escape" from the normal way of characters
are being interpreted or managed. For example, if you want to have a newline then you will
need to use escape sequence \n. Here \ will invoke ’escape’ from the normal execution and alter
the output behavior. Escape sequences are special characters that cannot be typed but have
special meanings in programming. Table. 1 displays some commonly used escape sequence in
practice.

Table 1: Commonly used Escape Sequences

Escape Sequences Character


\b Backspace
\n Newline
\r Return
\t Horizontal tab
\v Vertical tab
\\ Backslash
\’ Single quotation mark
\” Double quotation mark
\? Question mark
\0 Null character

1.7 Format Specifiers and Formatted I/O Operations


Format specifiers in C language are used to specify the format of data to be input via standard
input stream or the output to be displayed on standard output or error streams. They
are generally used with printf(), fprintf(), scanf(), etc. functions and their variants. These
functions are used to produce output in a controlled fashion. Here are some of the most commonly
used conversion specifiers:
• %d ,%i: Print an integer in decimal
• %o , %x: Print an integer in octal, hexadecimal
• %c: Print a character
• %s: Print a string
• %f: Print a floating point (single precision) number
• %e: Print a double precision number, in fixed format
• %g: Print a double in a general format

1.8 American Standard Code for Information Interchange (ASCII)


Computers can only understand numbers (binary). ASCII code is the numerical representation
of a character such as ’a’ or ’@’ or an action of some sort. American Standard Code for Information
Interchange (ASCII) consists of 1 byte or 8 bits. So there can be 256 possible characters
in the character set. The entire character set is divided into 2 parts i.e. standard ASCII and
extended ASCII. Figure. 13 shows standard and extended ASCII characters set.

Figure 13: ASCII Chart

1.9 Character Sets


A character is a basic element of a word, sentence or paragraph. Using characters, words, expressions
and statements can be formed. In order to interact with the computer, each character
is represented by a unique numeric value. List of character set is shown in Table. 2. The table
covers only selected special characters and Whit spaces, for further reading please see the
course text book.

Table 2: Basic Character Sets in C

Types Character Sets


Lower case a-z
Upper case A-Z
Digits 0-9
Special Character #$%ˆ&_{}˜
White space Tab or new lines or
1.10 Tokens
A token is a smallest unit of a statement in a program. C language contains different types of
tokens, which are as follows:

1.10.1 Keywords
Keywords are the reserved words by the compiler. Every keyword has assigned a fixed special
meaning and therefore, cannot be used as a variable name. There are 32 keywords available in
C which have been listed in Figure 14.

Figure 14: List of Keywords in C

1.10.2 Identifiers
Identifiers are the symbolic names of Arrays, functions, structures, variables etc. (all will be
covered in later sections). In simple words, identifiers are user defined names. There are
certain rules to be followed for using identifiers as a names of variables, arrays, functions etc.
• An identifier must start with an alphabet (a-z or A-Z).
• After the first alphabet, the remaining letters may be a sequence of alphabets and/or digits.
• digits (0 − 9), ’_’ and $ are allowed in identifiers
• An identifier can not start with digit.
• Constants only cannot be used as identifiers.
• identifiers, ABC, abc and AbC are all different.
• In C compiler, maximum length allowed for an identifier is 31 characters.
• An identifier should not be a C keyword.

1.10.3 Data types


Generally, data is present in form of numbers (whole/integer or decimal/floating) and characters.
Data types distinguish characters, integers or real numbers from each other. It enable
programmers to select appropriate data type of variables as per the requirements. Specifying
data type of a variable determines how much space it occupies in memory and how the bit
pattern is stored. Data types that are supported in C compilers are shown in Figure 15
Figure 15: Data types in C

Here we only cover basic/primitive data types. As shown in Figure. 15, the basic data types of
C language are Integer (int), character (char), floating point (float), and void. Brief explanation
of each data type is given below:

1. Integer (int)
C compilers offer short, long, signed and unsigned integer data types. Table. 3 and Table. 4
outline brief description of these data types.

Table 3: Short and Long Integer Data type

Short Integer Long Integer


Occupies 2 bytes in Occupies 4 bytes in
Memory Memory
Range is -32768 to Range is -2147483648
32767 to 2147483647
Format specifier is Format specifier is
%d %ld

2. Character (char)
C compilers offer signed and unsigned character data types. Table. 5 outlines brief description
of character data type.

3. Floating Point (float):


In floating point C compilers offers floating and double floating data types. Table. 6 outlines
brief description of floating point data types.

Table 4: Signed and Unsigned Integer Data Type

Signed Integer Unsigned Integer


Occupies 2 bytes in Occupies 2 bytes in
Memory Memory
Range is -32768 to Range is Range is 0 to
32767 65535
Format specifier is Format specifier is
%d or %i %u
Table 5: Signed and Unsigned Character Data types

Signed Character Unsigned Character


Occupies 1 byte in Occupies 1 byte in
memory Memory
Range is -128 to 127 Range is 0 to 255
Format specifier is Format specifier is
%c %c

Table 6: Floating and double floating data type

Floating Double Floating


Occupies 4 bytes in Occupies 8 bytes in
Memory Memory
Range is 3.4e-38 to Range is 1.7e-308 to
3.4e38 1.7e-308
Format specifier is %f Format specifier is
%lf

1.10.4 Constants
Constant meaning in C is the value, which remains the same during the execution process of a
program. C language offers several types of constants, which have been explained below:
1. Numerical constants:
Numerical constants are of two types:
• Integer constants:
Integer constants are the constants, which are in whole numbers form (without decimal)
and require 2 to 4 bytes place in memory to store. These include decimal,
hexadecimal as well as octal numbers and can be found in both positive and negative
forms. Examples of integer constants are: 13 (decimal), 0171 (octal) and 0x 54
(Hexadecimal) etc.
• Real constants:
Real constants are also known as floating point constants. These are the numbers,
which contain decimal. Examples of real constants are: 2.1, 1.342, 30.03 or 3.7e-5 etc.

2. Character constants:
Character constants are also of two types:
• Single character constants:
Single character constants are based on single character only. If a single character,
single digit or a single special character is enclosed in pair of single quotation
marks(’ ’) , it represents a character constant. Examples of character constant are:
’A’, ’b’, ’4’, ’-’ etc.
• String constants:
When a sequence of characters is enclosed in double quotetion marks (" "), it represents
a string. A string can be a combination of all possible types of symbols.
Examples of strings are: "Pakistan", "123a", "333" etc.

Syntax of Constant
const data_type variable_name ;

Examples of Constant
const double PI = 3.14;
const int a = 2;
1.10.5 Variables
A variable is a container (storage area) to hold data. To specify the storage region, a distinctive
name should be provided to each variable. Variable names are just the symbolic representation
of a memory location. In the program, a variable’s value can be changed, hence the name of
the variable.
Syntax of Variable
data_type variable_name ;

Example of Variable

Figure 16: Variable initialization

Note: A variable is declared, anywhere in the program. If it is declared outside main function
it is called global variable. Such variable can be used anywhere in the program. If it declared
inside the main function it is called local variable. Such variable cannot be used outside main
function.

When a variable is declared but not initialized with some value it stores a garbage value.

1.10.6 Programs Using Variables, User defined I/O operations, Format specifiers and Escape sequence

Program # 3: Integer Variable Input/Output with User Defined Input


Output #3:

Program # 4: Variable Declaration


Output #4:

Note: sizeof() is an operator which tells about the size of data types depending upon on your
OS.

Program # 5: Variable Declaration and Initialization


Output #5

Program # 6: Format Specifiers


Output #6:

Program # 7: Escape Sequence


Output #7:
Lab # 1 Task
1) Write a C program to display “your name 3 times in separate lines” in C.

2) Develop following program and show the output and discuss

3) Develop following program and show the output and discuss

4) Create a C program to print formatted output as below. (Hint: use printf() field-width specifier)

5) Write a C program to take the user’s name, age and salary as input and display them using formatted output.

6) Write a C program to calculate the area of a rectangle. Take the length and width as input from the user.

7) Write a C program to take the user’s name and age as input and display them using formatted output.

8) Write a C program that prompts the user to input an integer, a floating-point number, and a character.
Assignment # 1
1) Write a C program to convert temperature from Celsius to Fahrenheit. Use the formula:
Fahrenheit = (Celsius * 9/5) + 32

2) Write a C program to calculate the volume of a cube. The volume of a cube is given by:
Volume = side * side * side

3) Write a C program to take three numbers as input and calculate their sum and average.

4) Write a C program to convert a given number of days into years, weeks, and days.

5) Study what is Steganography and create a program to generate below output using
ASCII codes

You might also like