Module 1-1
Module 1-1
Operating systems: C is extensively used in developing operating systems like Windows, Linux,
and macOS.
Embedded systems: C is the language of choice for developing firmware and software for
various embedded systems, such as microcontrollers and IoT devices.
System Utilities: Many system utilities, such as text editors, compilers, and interpreters, are
written in C.
Game development: C is used to develop games due to its ability to handle complex calculations
and graphics.
Database systems: The core components of databases and their management systems are often
built using C.
Networking: C is used for developing network protocols and applications.
Importance of C programming language over other languages
C programming language offers several advantages over other programming languages,
including:
MODULE 1
2 CSC3C03- PROBLEM SOLVING USING C
Efficiency: C allows for direct memory manipulation and low-level access to system resources.
This results in highly efficient code execution.
Portability: C code can be easily ported to different platforms without major modifications,
thanks to its wide availability of compilers and libraries.
Speed: C is known for its fast execution speed, making it suitable for developing performance-
critical applications.
Control: C gives programmers fine-grained control over memory management and system
resources.
Compatibility: C code can be easily integrated with code written in other languages like C++,
Java, and Python.
Advantages of C Programming Language
Apart from the benefits mentioned above, there are several advantages of using C programming
language, including:
Complexity: C can be difficult to learn for beginners due to its low-level nature and the need to
understand concepts like pointers and memory management.
Lack of safety features: C does not have built-in features like garbage collection, which can lead
to memory leaks and other runtime errors if not managed properly.
Vulnerabilities: The low-level nature of C makes it prone to security vulnerabilities like buffer
overflows if not correctly handled by the programmer.
What Function Does the C Language Play in Everyday Life?
MODULE 1
3 CSC3C03- PROBLEM SOLVING USING C
Even though most people may not directly interact with C programming language in their daily
lives, its impact is widespread. Many everyday devices and technologies rely on software
developed using C, including:
Operating systems: All modern operating systems, such as Windows, Linux, and macOS, have a
significant portion of their codebase written in C.
Embedded systems: Devices like washing machines, smart TVs, and medical equipment often
run on embedded systems programmed using C.
Mobile applications: Some parts of mobile applications, including high-performance tasks and
system-level operations, may be implemented in C for efficiency.
Gaming consoles: Popular gaming consoles’ core software and engines are often developed using
C.
Network infrastructure: Routers and networking devices rely on software written in C to handle
complex networking protocols.
MODULE 1
4 CSC3C03- PROBLEM SOLVING USING C
The document section of the program is made up of a set of comment lines containing details
like the name of the program, author, etc.
The link section contains instructions to the compiler on how to link functions from the system
library.
Variables that are used in multiple functions are known as global variables. These variables are
declared in the global variables section.
Every C program should have a main() function section. It is a special function used by the C to
tell the computer where the program starts. The main() section is divided into two parts: the
declaration part and the executable part. The declaration section declares all variables. The
executable section contains at least one statement. These two parts must be written inside the
opening and closing braces. All statements in the declaration and executable sections are
followed by a semicolon (;).
All user-defined functions that are called in the main function are written in the subprogram
section.
Except for the main function section, all sections may be skipped when they are not required.
#include<stdio.h>
main()
{
printf("Hello World!");
}
Executing a C Program
MODULE 1
5 CSC3C03- PROBLEM SOLVING USING C
Character Set
The set of alphabets, digits and special characters that are valid in the C language is called the
character set.
Alphabets
Both lowercase(a – z) and uppercase(A – Z) alphabets are accepted by C.
Digits
C accepts all digits from 0 to 9.
Special Characters
C supports the usage of the following special characters.
White spaces
Blank spaces, horizontal tab, carriage return, newline and form feed characters are allowed in C.
White spaces may be used to separate words, but they are not permitted between keywords and
identifiers.
MODULE 1
6 CSC3C03- PROBLEM SOLVING USING C
C tokens
The smallest individual units in a C program is known as C tokens. C has six types of tokens as
shown in the figure.
Keywords
Predefined reserved words with fixed meanings are called keywords. Since keywords are the
building blocks for program statements, they cannot be used as identifiers. Since C is case
sensitive, all keywords must be written in lowercase. The list of all keywords available in C is
given below:
auto extern sizeof
break for signed
case float struct
char if switch
const goto typedef
continue int union
default long void
do register unsigned
double return volatile
else short while
enum static
Identifiers
The names of variables, functions, and arrays are referred to as identifiers. These are user-
defined names consisting of a sequence of letters and digits. Identifiers must be unique.
MODULE 1
7 CSC3C03- PROBLEM SOLVING USING C
int age;
float mark;
Here age and mark are identifiers.
Variables
A variable is a data name that can be used to store data. A variable may take different values at
different times during the execution of a program. A variable name can be meaningfully chosen
by the programmer, subject to the conditions listed below:
Variable names can be made up of alphabets, digits, and the underscore character.
They must begin with an alphabet. Some systems allow underscore as the initial
character.
Uppercase and lowercase letters are significant. That is, the variable Mark is not the same
as mark or MARK.
It should not be a keyword.
White space is not allowed.
Some examples of valid variable names include
Value
,
score
,
mark1
,
phone_number
,
Counter_1
, etc.
Invalid examples include
MODULE 1
8 CSC3C03- PROBLEM SOLVING USING C
123
,
(area)
,
22nd
,
char
, etc.
Declaration of Variables
Declaration tells the compiler what the variable name is and what type of data the variable will
hold. In C, variables can be declared using the following syntax:
datatype variable1;
Multiple variables can be declared by separating them with commas as follows.
int x;
float a, b, c;
Here
int
and
float
are the keywords used to represent integer and real numbers respectively.
Initializing variables
int x = 5;
The following ways are also acceptable.
int a, b=10, c = 5;
int x, y, z;
x = 10;
MODULE 1
9 CSC3C03- PROBLEM SOLVING USING C
y = z = 5;
Here
b = 10
,
c=5
,
x =10
,
y= 5
,
z=5
.
The symbols [ ] { } ^ \ | ~ # are frequently used in C programs, but in the late 1980s, there were
code sets in use (ISO 646 variants, for example, in Scandinavian countries) where the ASCII
character positions for these were used for national language variant characters (e.g. £ for # in
the UK; Æ Å æ å ø Ø for { } { } | \ in Denmark; there was no ~ in EBCDIC). This meant that it
was hard to write C code on machines that used these sets.
To solve this problem, the C standard suggested the use of combinations of three characters to
produce a single character called a trigraph. A trigraph is a sequence of three characters, the first
two of which are question marks.
The following is a simple example that uses trigraph sequences instead of #, { and }:
??=include <stdio.h>
int main()
??<
printf("Hello World!\n");
??>
MODULE 1
10 CSC3C03- PROBLEM SOLVING USING C
This will be changed by the C preprocessor by replacing the trigraphs with their single-character
equivalents as if the code had been written:
#include <stdio.h>
int main()
printf("Hello World!\n");
Trigraph Equivalent
??= #
??/ \
??' ^
??( [
??) ]
??! |
??< {
??> }
??- ~
Note that trigraphs are problematic because, for example, ??/ is a backslash and can affect the
meaning of continuation lines in comments, and have to be recognized inside strings and
character literals (e.g. '??/??/' is a single character, a backslash).
MODULE 1
11 CSC3C03- PROBLEM SOLVING USING C
Constants
Fixed values that do not change throughout program execution are called constants. The
keyword
const
can be used to define a constant as follows.
const datatype name = value;
For example
#define
preprocessor directive. You can learn about the symbolic constants in this tutorial.
C supports the following types of constants.
Integer Constants
A sequence of digits is referred to as an integer constant. Spaces, commas, and non-digit
characters are not permitted between digits. The integer constants are of three types.
MODULE 1
12 CSC3C03- PROBLEM SOLVING USING C
Numbers containing fractional parts are called real constants. Examples of real constants include
452.5
-.74
+321.2
etc.
Single Character Constants
A single character enclosed within a pair of single quote marks is called a single character
constant. Examples of single character constants include
'F'
'c'
'3'
.
String Constants
A sequence of characters enclosed in double quotes is called a string constant. Letters, numerals,
special characters, and blank spaces can all be used as characters. Some examples are
"Hello"
"Good Morning"
"1996"
"what?"
etc.
Backslash Character Constants
MODULE 1
13 CSC3C03- PROBLEM SOLVING USING C
C includes various special backslash character constants that can be used in output functions.
They are known as escape sequences. The following table shows the list of backslash character
constants in C.
Constant Meaning
\a Bell
\b Back space
\f Form feed
\n New line
\r Carriage return
\t Horizontal tab
\v Vertical tab
\’ Single quote
\” Double quote
\? Question mark
\\ Back slash
\0 Null
Data types are used to determine the size and type of data stored in a variable. For example,
int mark;
Here mark is a variable of type int. That is mark can store integer values.
MODULE 1
14 CSC3C03- PROBLEM SOLVING USING C
The following table contains various data types along with their size, range of values and format
specifier.
Integer
Integers are whole numbers having a range of values that are supported by a certain computer. In
C, there are three types of integer storage:
short int
,
int
, and
long int
, which are available in both
signed
and
unsigned
forms. That is integers can store both zero, positive and negative values but no decimal values.
int roll;
signed int x;
MODULE 1
15 CSC3C03- PROBLEM SOLVING USING C
short int
represents relatively small integer values and takes half the storage space of a typical int
number.
unsigned int
employ all of the bits for the magnitude of the number and are always positive. Because the
default declaration implies a signed number, the use of the qualifier
signed
on integers is optional.
Floating point
Floating-point variables are used to store real numbers with 6 digits of precision. In C, floating-
point numbers are defined by the keyword
float
. To define a number with 14 numbers of precision, the type
double
can be used. These are referred to as double-precision numbers.
long double
can be used to increase precision even further.
float rate;
double price;
Character
The
char
data type can be used to define a single character.
The
void
MODULE 1
16 CSC3C03- PROBLEM SOLVING USING C
type has no values. This is typically used to specify the type of function that returns no value to
the caller function.
Derived Data Types and User-Defined Data Types
Derived types are data types that are derived from fundamental data types. Arrays, pointers,
function types, structures, and so on are examples.
int roll;
int roll, mark;
short int id;
signed int x;
short int represents relatively small integer values and takes half the storage space of a typical int
number. unsigned int employ all of the bits for the magnitude of the number and are always
positive. Because the default declaration implies a signed number, the use of the qualifier signed
on integers is optional.
Floating point
Floating-point variables are used to store real numbers with 6 digits of precision. In C, floating-
point numbers are defined by the keyword float. To define a number with 14 numbers of
precision, the type double can be used. These are referred to as double-precision numbers. long
double can be used to increase precision even further.
float rate;
double price;
Character
The char data type can be used to define a single character.
MODULE 1
17 CSC3C03- PROBLEM SOLVING USING C
Derived types are data types that are derived from fundamental data types. Arrays, pointers,
function types, structures, and so on are examples.
The typedef is a keyword that is used to provide existing data types with a new name. The C
typedef keyword is used to redefine the name of already existing data types.
When names of datatypes become difficult to use in programs, typedef is used with user-
defined datatypes, which behave similarly to defining an alias for commands.
C typedef Syntax
typedef existing_name alias_name;
After this declaration, we can use the alias_name as if it were the real existing_name in out C
program.
Example of typedef in C
typedef long long ll;
// C program to implement typedef
#include <stdio.h>
// defining an alias using typedef
typedef long long ll;
// Driver code
int main()
{
// using typedef name to declare variable
ll var = 20;
printf("%ld", var);
return 0;
}
Enum
MODULE 1
18 CSC3C03- PROBLEM SOLVING USING C
// Or
MODULE 1
19 CSC3C03- PROBLEM SOLVING USING C
int main()
{
enum week day;
day = Wed;
printf("%d",day);
return 0;
}
Output:
2
A symbolic constant is a name given to any constant. In C, the preprocessor directive
#define
is used for defining symbolic constants.
#define
instructions are usually placed at the beginning of the program. By convention, the names of
symbolic constants are written in uppercase, but this is not compulsory. The syntax for creating a
symbolic constant is as follows:
#define constant_name value
For example:
#define PI 3.14
It will define a symbolic constant
PI
having value
3.14
. When we use
MODULE 1
20 CSC3C03- PROBLEM SOLVING USING C
PI
in our program, it will be replaced with 3.14 by the compiler automatically.
The rules below apply to a
#define
statement that defines a symbolic constant.
No blank space is allowed between the
#
symbol and the word
define
.
The character in the line should be
#
.
A blank space is required between the constant name and #define and between the
constant name and the value.
A semicolon must not be used at the end of a
#define
statement.
Within the program, the symbolic constant should not be assigned any other value.
Example
#include <stdio.h>
#define PI 3.1415
int main()
{
float radius=10, area;
area = PI*radius*radius;
printf("Area=%.2f",area);
return 0;
}
Operators in C
n this tutorial, you will learn about different operators in C programming.
An operator is a symbol that instructs a computer to perform certain operations. Operators are
typically used as part of mathematical or logical expressions. C supports a rich set of operators to
perform various operations.
MODULE 1
21 CSC3C03- PROBLEM SOLVING USING C
C Arithmetic Operators
An arithmetic operator performs mathematical operators such as addition, subtraction etc. C
supports all basic arithmetic operators. The list of all arithmetic operators in C is listed in the
following table.
The variables in which the operation is performed is called operand. That is, in a + b, a and b are
operands and + is the operator.
When the operands in a single arithmetic expression are both integers, then the operation is
known as integer arithmetic. Integer arithmetic always produces an integer value as output. All
the examples in the above table are integer arithmetic. For example: 12 / 10 = 1
Real arithmetic refers to arithmetic operations that will use only real operands. The operator %
cannot be used with real operands. For example: 3.0 / 2.0 = 1.5
Mixed-mode arithmetic expressions are those in which one of the operands is real and the other
is an integer. Since one of the operands is of real type, then the result is always a real number.
For example: 12 / 10.0 = 1.2
MODULE 1
22 CSC3C03- PROBLEM SOLVING USING C
c = a+b;
printf("Sum = %d \n",c);
c = a-b;
printf("Difference = %d \n",c);
c = a*b;
printf("Product = %d \n",c);
c = a/b;
printf("Quotient = %d \n",c);
c = a%b;
printf("Remainder after division = %d \n",c);
return 0;
}
Output
Sum = 10
Difference = 6
Product = 16
Quotient = 4
Remainder after division = 0
C Relational Operators
MODULE 1
23 CSC3C03- PROBLEM SOLVING USING C
The relationship operators are used to check the relationship between two operands. The value of
a relational operator is either 1 (true) or 0 (false). The list of relational operators supported in C is
given in the table. Suppose a = 6 and b = 2.
MODULE 1
24 CSC3C03- PROBLEM SOLVING USING C
Output
5 == 4 is 0
5 > 4 is 1
5 < 4 is 0
5 != 4 is 1
5 >= 4 is 1
5 <= 4 is 0
C Logical Operators
The logical operators are used to make a decision by testing one or more conditions. The three
logical operators supported in C are:
&& – logical AND – True only if all operands are true.
|| – logical OR – True only if either one operand is true.
! – logical NOT – True only if the operand is 0
The value of a logical operator is also one or zero according to the truth table given below:
A B A && B A || B !A
0 0 0 0 1
0 1 0 1 1
1 0 0 1 0
1 1 1 1 0
C Assignment Operator
Assignment operators are used to assigning values to a variable. The assignment operator in c is
=. C also has a set of shorthand assignment operators as shown in the table:
MODULE 1
25 CSC3C03- PROBLEM SOLVING USING C
/= a /= b a = a / b
%= a %= b a = a % b
C Increment and Decrement Operator
In C, the operators ++ and -- are called the increment and decrement operators and are used to
change the value of an operand by 1.
The increment operator ++ increases the value of an operand by 1 and the decrement operator --
decreases the value of an operand by 1. They both are unary operators.
These operators can be used as prefixes like ++a and can be used as postfixes like a++. You can
learn the difference in increment and decrement operators when used as prefix and postfix here.
Example
#include <stdio.h>
int main() {
// Write C code here
printf("Postfix Operators");
int a,b;
a=4;
b=a++ + a++;
printf("%d",b);
printf("\nPrefix Operators");
a=4;
b=++a + ++a;
printf("%d",b);
return 0;
Output
Postfix Operators9
Prefix Operators12
MODULE 1
26 CSC3C03- PROBLEM SOLVING USING C
C Bitwise Operator
For manipulation of data at bit level, C supports special operators known as bitwise operators.
Bit wise operators and their meaning is given in the following table:
Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
` Bitwise complement
<< Shift left
>> Shift right
C Conditional Operator
C has a special ternary operator ?: called conditional operator. The conditional operator behaves
similarly to the ‘if-else’ statement. The syntax of a conditional operator is as follows:
max = (a > b) ? a : b ;
First, the expression a > b is evaluated. If it is true, the statement will be equivalent to
max = a;
. If
a>b
is false, then the statement will be equivalent to
max = b
.
MODULE 1
27 CSC3C03- PROBLEM SOLVING USING C
Special Operators
C also support some special operators such as comma operator, sizeof operator, pointer
operators, etc.
The comma operator is used to link the related expression together. For example:
float a, b, c;
The sizeof Operator
The sizeof operator return the number of bytes a operand occupies. It can be used to know the
size of variables, constants, arrays, structures etc. For example:
x = sizeof(mark);
Other operators
&
and deference operator
*
is used in pointer operations. The member selection operator
.
and
->
are used to select members of a structure.
MODULE 1
28 CSC3C03- PROBLEM SOLVING USING C
(a + b) * (a-b)
\[\frac{ab}{c}\]
(a * b) / c
\[2x^2+3x\]
2*x*x+3*x
Arithmetic expressions are evaluated using an assignment statement of the form variable =
expression. The expression is evaluated first and the value is assigned to the variable. An
example of an evaluation statement is, c = a - b / d + e
Precedence of Arithmetic Operators in C
To determine the meaning and value of an expression in an unambiguous manner, we apply the
operator precedence and associativity rules. Arithmetic expressions without parentheses are
evaluated from left to right using the rules of operator precedence. In C, arithmetic operators
have two different priority levels.
Hight priority * / %]
Low priority + -
The basic procedure for evaluating an expression includes two passes from left to right. The high
priority operators are applied during the first pass and the low priority operators are applied in
the second pass.
C language has standard libraries that allow input and output in a program. The stdio.h or
standard input output library in C that has methods for input and output.
scanf()
The scanf() method, in C, reads the value from the console as per the type specified. Syntax:
MODULE 1
29 CSC3C03- PROBLEM SOLVING USING C
scanf(“%X”, &variableOfXType);
where %X is the format specifier in C. It is a way to tell the compiler what type of data is in a
variable and & is the address operator in C, which tells the compiler to change the real value of
this variable, stored at this address in the memory.
printf()
The printf() method, in C, prints the value passed as the parameter to it, on the console screen.
Syntax:
printf(“%X”, variableOfXType);
where %X is the format specifier in C . It is a way to tell the compiler what type of data is in a
variable and & is the address operator in C, which tells the compiler to change the real value
of this variable, stored at this address in the memory.
The basic type in C includes types like int, float, char, etc. Inorder to input or output the
specific type, the X in the above syntax is changed with the specific format specifier of that
type. The Syntax for input and output for these are:
Integer:
Input: scanf("%d", &intVariable);
Output: printf("%d", intVariable);
Float:
Input: scanf("%f", &floatVariable);
Output: printf("%f", floatVariable);
Character:
Input: scanf("%c", &charVariable);
Output: printf("%c", charVariable);
Syntax:
int getchar(void);
Example:
MODULE 1
30 CSC3C03- PROBLEM SOLVING USING C
int getch();
Example:
MODULE 1
31 CSC3C03- PROBLEM SOLVING USING C
return 0;
}
Input: g (Without enter key)
Output: Program terminates immediately.
But when you use DOS shell in Turbo C,
it shows a single g, i.e., 'g'
getche()
Like getch(), this is also a non-standard function present in conio.h. It reads a single character
from the keyboard and displays immediately on output screen without waiting for enter key.
Syntax:
int getche(void);
Example:
#include <stdio.h>
#include <conio.h>
// Example for getche() in C
int main()
{
printf("%c", getche());
return 0;
}
putchar() function is a file handling function in C programming language which is used to write a
character on standard output/screen. getchar() function is used to get/read a character from
keyboard input. Please find below the description and syntax for above file handling function.
MODULE 1
32 CSC3C03- PROBLEM SOLVING USING C
putchar(char);
where, char is a character variable/value.
MODULE 1
33 CSC3C03- PROBLEM SOLVING USING C
puts() can be preferred for printing a string because it is generally less expensive
(implementation of puts() is generally simpler than printf()), and if the string has formatting
characters like ‘%s’, then printf() would give unexpected results. Also, if str is a user input string,
then use of printf() might cause security issues (see this for details).
Also note that puts() moves the cursor to next line. If you do not want the cursor to be moved to
next line, then you can use following variation of puts().
MODULE 1