LP 2
LP 2
2.1 Introduction
In this module, we will delve into the fundamentals of C programming and equip
you with the necessary knowledge to create basic C programs.
2.2 Topics/Discussion
This module covers the following topics:
2.2.1 Variables
In C programming, a variable is a named storage location in the computer's memory
that is used to hold a value. Variables allow programmers to store and manipulate data
during the execution of a program. Each variable has a specific data type, which determines
the size and type of data it can hold (e.g., integer, character, floating-point number, etc.).
To use a variable in C, you must first declare it, specifying its data type and giving it a
name. The general syntax for declaring a variable is:
data_type variable_name;
1 | Computer Programming 1 8
Variable name may be consist of letter, digits and under line(_) with following the below
rules - 1) They must begin with a letter. 2) Upper case & lower case are significant mean
total is differ. 3) Variable name should not be a keyword.
In some languages, you can create variables as you go along and put whatever data you
want into them. C isn’t like that: to use a variable in C, you need to have created it first, and
at the time you create it, you have to set what type of value it’s going to store. By doing
this, a block of memory of the correct size can be allocated by the compiler to hold the
variable. This process of creating a variable is known as declaration.
The top three lines inside the main function here are declarations. They tell the
compiler that we would like to use variables called a, b, and c respectively, and that each
one is of type int, i.e. an integer.
In the second line, we see an example of an initialization at the same time as a
declaration:
This stores an initial value of 3 in the variable b. Note that the values of a and c at this point
are undefined; you might assume that a variable which hasn’t had a value stored in it is
always 0, but that isn’t the case in C. Before reading the value from a variable or using it in
a calculation, you must store a value in it; reading a variable before initializing it is a
common error in C.
The next two lines do some actual work with the variables we have declared.
a = 2;
This stores a value of 2 in the variable a, which will now have this value until it’s changed.
The reason a is called a variable is that it can vary: you can change its value as often as you
like, but only to another integer. The value of a variable can change, but its type is fixed
when it is declared.
c = a + b;
This line adds a to b, and stores the result in c.
Naming variables
Every variable has an identifier or a name. A variable name is an identifier; function
names are identifiers. We will encounter other kinds of identifiers that are used in many
different contexts. An identifier, or name, in C is a sequence of capital letters (A..Z) and
small letters (a..z), digits (0..9), and the underscore (_) character. An identifier may not
begin with a digit. Upper and lowercase letters are different from each other, so achar,
aChar, AChar, and ACHAR would identify different variables. An identifier may not have
the same spelling as a C keyword.
As you can see, all lowercase names are somewhat difficult to read. However, these
are not nearly as difficult to read as all-uppercase names. The other two ways are quite a bit
easier to read. Therefore, we prefer to use either of the last two. If you choose one identifier
naming convention, stick to it throughout your program. Do not mix different identifier
naming schemes as this makes remembering the exact name of a thing, function identifiers,
and other identifiers much more difficult and error-prone.
2. Floating-Point Types:
o float: Represents single-precision floating-point numbers, typically 32 bits in
size.
o double: Represents double-precision floating-point numbers, usually 64 bits
in size.
o long double: Represents extended-precision floating-point numbers,
implementation-specific, and larger than double.
3. Character Type:
o char: Represents a single character, such as 'A', 'b', or '$'. It has a size of 1 byte.
Please note that there is not a Boolean data type. C does not have the traditional
view of logical comparison. Actually, data types in C are listed under three main
categories:
(a) Primary data type (b) Derived data type (c) User-defined data type
Unsigned integers have a larger positive range than their signed counterparts
because they do not need to reserve one bit for representing the sign. For example, an
unsigned int can represent values from 0 to UINT_MAX, where UINT_MAX is the maximum
value that can be represented by an unsigned int.
The exact range of values that can be represented by each unsigned integer type
depends on the platform and the compiler. However, the standard guarantees certain
minimum ranges:
The printf function allows you to display text and values on the screen or write them
to a file. It uses a format string that specifies the layout of the output and includes optional
format specifiers to indicate how to display variables of different data types.
The format parameter is a string that contains the text to be printed, along with
format specifiers (%) that define the output format for variables.
After the format parameter, you can pass additional arguments that correspond to
the format specifiers in the format string. These arguments will be displayed
according to their respective format specifiers.
Format specifiers are placeholders in the format string that determine how different data
types should be printed. For example, %d is a format specifier for an integer, %f for a
floating-point number, %s for a string, etc.
Here's an example of using printf to display text and the value of a variable:
In this example, the format string contains the text "The value of num is " along with
the format specifier %d, which indicates that an integer value will be printed at that
position. The actual value of num is passed as an argument to printf to be displayed in the
output.
The printf function is a powerful tool for formatting output, and you can customize
the display in various ways using different format specifiers and additional options.
However, be cautious when using it with user-supplied data to avoid security
1 | Computer Programming 1 12
vulnerabilities such as format string vulnerabilities. Always validate and sanitize user input
to ensure the safe use of printf and other similar functions.
In C, scanf is a standard library function used for formatted input. It stands for "scan
formatted" and is part of the stdio.h header file, which provides functions for input and
output operations.
The scanf function allows you to read data from the user or a file based on a
specified format. It uses a format string that contains format specifiers (%) to indicate how
to read data of different types.
The format parameter is a string that contains format specifiers for the data you
want to read.
After the format parameter, you can pass pointers to variables where the read data
will be stored. The scanf function will attempt to parse the input according to the
format specifiers and store the values in the provided variables.
Format specifiers are placeholders in the format string that determine how different data
types should be read. For example, %d is a format specifier for an integer, %f for a floating-
point number, %s for a string, etc.
In this example, the format specifier %d in the scanf function indicates that an
integer should be read from the user's input. The address of the variable num is passed as
an argument to scanf, allowing it to store the user's input in that variable.
It's important to be careful when using scanf, as it can be prone to input errors or
buffer overflow issues. Always ensure that the input matches the specified format and
consider using safer input functions like fgets for reading strings. Additionally, when using
scanf, be mindful of how it handles characters such as spaces and newline characters,
which can affect the reading of input.
In C, "formats" typically refer to format specifiers used in formatted input and output
functions like printf and scanf. Format specifiers are placeholders in the format strings that
determine how different data types are displayed (in the case of printf) or read (in the case
of scanf).
2.2.4 Operators
In addition to variable and types, all programming languages support the concept of
operators. C has over 40 different operators, but hardly all of them are used. There are eight
C operators that turn up in almost every program. Right now the concentration will be on
following operators.
Arithmetic operators.
Assignment operators
Modulus operators
Increment and decrement operators.
Relational operator
Logical Operator
Conditional Operator
Bitwise Operator
Special Operator
Before, we discuss about operators, let us discuss about expression. An expression consists
of references to previously defined values such as identifiers and constants. Expression
1 | Computer Programming 1 14
usually contain one or more operators. These operators and expressions are evaluated,
according to the standard C language rules. An operator may take one or more operands
and operands in turn can consist of previously declared identifiers, constants, functions etc.
The statement has two operators, Arithmetic operators + and assignment operator =,
and three operands a, 1 and 2. The effect of this statement is to add the constants 1 and 2
together and assign the result to the variable a, which must have declared as int in the
beginning of program. Thus, the assignment operator = in C is not used like the equal sign
of algebra. Following are the selected standard mathematical functions. Here, while
describing the functions, it has been assumed that variable x and y are declared as double
except in trigonometric and hyperbolic functions, where they are defined as radians. All
these functions return a double value.
1 | Computer Programming 1 15
We first add 1 to 2, then we assign the result to a. But how do we know that C will
carry out the operations in that exact order. It is because C has a built-in set of rules that
govern the order in which operations are evaluated. Also C provides the facility to assign a
value to a series of variables in the same statement. Consider the following example :
a = b = c = d = 1;
A series of assignment like this is always performed one at a time from right to left. Thus C
executes the statement as follows:
If Statement
The if statement may be implemented in different forms depending on the complexity of
conditions to be tested.
Simple if statement
if........else statement.
Nested if........ else statement.
else if ladder.
1 | Computer Programming 1 17
Simple If Statement
The general form of a simple If statement is
The statement group could have a single statement or a group of statements. The
condition is defined as entity and it can have two values - true or false. If the test condition
is true, the statement group is executed, otherwise, the statement group is skipped and the
execution will jump to next statement. If the condition is true both statement group is
executed followed by the Next Statement. The following figure represent flow chart for the
If statement:
The above part of the program test whether the deposited amount is greater than
4000 or not. If yes, the interest @ of 15% is calculated & then it is printed.
Here the difference is that another set of instructions has been added for false
condition using else. If the test condition is true, the true statements are executed,
otherwise, the control moves to false statements. Thus here one of the two group of
statements are executed. In no case, both the sets of instructions can be executed
simultaneously. This flow chart is illustrated in the figure:
As you can see from the flow chart, only one set of instruction are being executed on
the basis of true or false condition. In both the cases, the control is transferred subsequently
to next statement.
Here each case is labeled by one or more integer-valued constant or constant expressions. If
a case matches the value, the statement group associated with the case is executed. The
break statement at the end of each statement group indicates the end of execution and
causes exit from the switch statement. At the bottom, the default switch is given which is
optional. If value of expression doesn’t matches with any of the case value, the default
statement is executed, if it is present, otherwise no action takes place and control goes to
next-statement.
goto Statement
The goto statement in C is used to transfer the control of the program to a labeled
statement within the same function. However, the use of goto is generally discouraged in
modern programming practices because it can lead to hard-to-read and hard-to-maintain
code. In most cases, structured control flow constructs like if, else, for, while, and switch
provide better alternatives.
2.2.6 Looping
Looping consists of series of statements that are executed until some conditions for
termination of loop are satisfied. A program loop consist of normally two segments.
body of the loop
Control statement.
The control statement tests the conditions and then directs the repeated execution of the
series of statements contained in the body of the loop. Thus, a loop is defined as a block of
processing steps repeated a certain number of times. An endless loop repeats infinitely and
is always the result of an error. Looping can be classified into two categories; Entry-
controlled loop or Exit-controlled loop. Entry controlled loop first testify the condition and
then executes the series of statements whereas Exit controlled loop first executes the
statements and then testify the condition. Or in other words, Entry controlled loop starts
with the testing condition and Exit control loop ends with the testing condition.
The general method of looping is by using counters and then testing it using the if
statement. Every time the series of statement are executed, the counter increases or
decreases its value by a fixed number. And the value of this counter is tested after every
execution of series of statements. If the testified condition is not met, the series of
statements are executed again and this process continues till the condition is met.
e.g. Write a program for calculating the salary of 100 workers in a factory.
In figure given below, step 2 is for initialization of the value of COUNT where
COUNT is an active variable. Step 7 is the increment. Step 3 is for the EXIT test. Steps 4 to 6
are the repetitive steps in the loop to input the NAME, WAGE and HOURS and then
calculate the value of PAY in step 5 and print the name and pay in step 6. In step 7, the
value of COUNT is increased by 1 and the current value of COUNT is compared with 100
in step 3. If it is more than 100, the process is halted.
1 | Computer Programming 1 22
For Loop
In C programming, a for loop is a control flow statement used to repeatedly execute
a block of code based on a condition. The syntax of the for loop in C is as follows:
initialization: This part is executed only once before the loop starts. It initializes
the loop control variable.
condition: This is the condition that is evaluated before each iteration. If the
condition is true, the loop continues; otherwise, it terminates.
update: This part is executed after each iteration and is usually used to modify
the loop control variable.
Here's a simple example to print the numbers from 1 to 5 using a for loop:
1 | Computer Programming 1 23
In this example, the loop control variable i is initialized to 1. The condition checks if i
is less than or equal to 5. If true, the loop body is executed, which prints the value of i. After
each iteration, the update i++ increments the value of i by 1, and the loop continues until
the condition becomes false.
While Loop
In C programming, a while loop is another type of control flow statement used to
repeatedly execute a block of code as long as a certain condition is true. The syntax of the
while loop in C is as follows:
condition: This is the condition that is evaluated before each iteration. If the
condition is true, the loop continues; otherwise, it terminates.
Here's a simple example to print the numbers from 1 to 5 using a while loop:
In this example, the loop control variable i is initialized to 1. The while loop checks if
i is less than or equal to 5. If true, the loop body is executed, which prints the value of i.
After each iteration, the value of i is incremented by 1 using i++, and the loop continues
until the condition becomes false.
It's important to ensure that the loop control variable or the condition inside the while loop
is modified within the loop to avoid infinite loops, where the condition is always true, and
the loop never terminates.
Do While Loop
In C programming, a do-while loop is another type of control flow statement used to
repeatedly execute a block of code at least once, and then continue executing it as long as a
certain condition is true. The syntax of the do-while loop in C is as follows:
condition: This is the condition that is evaluated after each iteration. If the
condition is true, the loop continues; otherwise, it terminates.
1 | Computer Programming 1 24
The key difference between a do-while loop and a regular while loop is that the do-while
loop guarantees that the code inside the loop will be executed at least once, regardless of
the initial condition.
Here's a simple example to print the numbers from 1 to 5 using a do-while loop:
In this example, the loop control variable i is initialized to 1. The do-while loop
executes the code inside the loop, which prints the value of i, and then increments i by 1
using i++. After each iteration, the do-while loop checks if i is less than or equal to 5. If true,
the loop continues; otherwise, it terminates.
Since the condition is evaluated after each iteration, the loop body is executed at
least once before the condition is checked. This makes the do-while loop useful in situations
where you want to ensure that a certain block of code runs at least once before the loop
condition is evaluated.
ASSESMENT