Unit-I Introduction To C
Unit-I Introduction To C
Unit-I Introduction To C
Programming languages are often categorized into three levels based on their abstraction from
the machine hardware.
1. Low-Level
2. Middle-Level
3. High-Level Languages.
1) Low-Level Programming Language:
Low-level languages are closer to machine code or hardware. They provide little to no
abstraction and are highly dependent on the machine architecture, making them efficient but
more difficult to write and understand for humans.
Characteristics:
• No or minimal abstraction from hardware.
• Faster execution because they interact directly with the CPU.
• Hard to understand and debug.
• Hardware-specific, meaning they are not portable between different systems.
Example: Machine Code, Assembly Code
2) Middle-Level Programming Language:
Middle-level languages serve as a bridge between low-level and high-level languages. They
combine some level of hardware abstraction with the ability to directly manipulate hardware
resources like memory, which makes them more efficient and flexible.
Characteristics:
• Provides a balance between direct hardware control and ease of programming.
• Faster than high-level languages but slower than low-level languages.
• Often used for system programming (operating systems, compilers).
• More portable than low-level languages but may still be platform-dependent in some cases.
Examples: C, C++
3) High-Level Programming Language:
High-level languages are abstracted further from the hardware. They are designed to be easy
for humans to write, read, and maintain.
Characteristics:
• Strong abstraction from machine details.
• Focused on ease of use, portability, and readability.
• Slower execution compared to low- and middle-level languages because of higher
abstraction.
• Portable across different systems without modification.
Examples: Java, Python, Ruby, Php etc….
Translator:
A translator refers to a type of software that converts code written in one programming language
into another language or into a machine-readable format.
There are different types of translators in programming.
a) Assembler
b) Compiler
c) Interpreter
Compiler: A compiler translates code from a high-level programming language (like C, Java, or
Python) into machine code, which is a low-level language that the computer's hardware can
execute directly. The entire source code is typically translated at once, producing an executable
file.
Problem Solving:
Algorithm:
An algorithm is a step-by-step process, or a set of rules designed to perform a specific task or solve
a particular problem. Algorithms serve as a blueprint for writing code, guiding the program
through a sequence of operations to achieve a desired outcome.
Characteristics of an Algorithm:
Input: The algorithm takes zero or more inputs.
Output: The algorithm produces one or more outputs.
Definiteness: Each step of the algorithm is clear and unambiguous.
Finiteness: The algorithm must terminate after a finite number of steps.
Effectiveness: Each step of the algorithm is basic enough to be performed, ideally by a computer.
Examples:
Algorithm-1: Addition of Two Numbers
1. Start
2. Input: Read two numbers, num1 and num2.
3. Process: Calculate the sum of the two numbers by performing the operation:
sum = num1 + num2
4. Output: Display or return the result, sum.
5. End
2. Bottom-Up Approach
Definition: The bottom-up approach starts by solving the simplest or smallest sub-problems
first, and then building up solutions to more complex sub-problems by combining the solutions of
the simpler ones.
Steps:
1. Identify the base cases or smallest sub-problems.
2. Solve the smallest problems first.
3. Combine the solutions of these smaller problems to build up to the solution of the larger
problem.
4. Repeat until you reach the solution to the original, large problem.
Advantages:
• Avoids redundancy by solving each sub-problem once (more efficient).
• Often leads to more optimized solutions.
• Well-suited for iterative implementations.
Disadvantages:
• Can be harder to conceptualize, especially for large problems.
• May involve more initial work in defining and identifying base cases and how to combine
them.
Examples of Usage
1. Fibonacci Sequence Calculation:
• Top-Down (Recursive with Memoization):
o Break the problem as fib(n) = fib(n-1) + fib(n-2), and recursively calculate fib(n-1)
and fib(n-2), while storing the results to avoid re-computation.
• Bottom-Up (Iterative with Tabulation):
o Start with fib(0) and fib(1) and build up to fib(n) by iteratively solving from the base
cases.
Time and Space Complexity of an algorithm:
Generally, there is always more than one way to solve a problem in computer science with different
algorithms. Therefore, it is highly required to use a method to compare the solutions in order to
judge which one is more optimal.
There are two such methods used, time complexity and space complexity
Time Complexity: The time required by the algorithm to solve given problem is called time
complexity of the algorithm. The time complexity of an algorithm quantifies the amount of time
taken by an algorithm to run as a function of the length of the input.
Ex-2: Given an array of n numbers, find if a specific number exists in the array.
Time Complexity Analysis:
Algorithm:
Step 1: Start
Step2: Initialize the loop: i = 0.
Step 2: for i=0 to n n-1:
Compare each element: arr[i] = target.
Continue until the element is found or until all elements have been checked.
Step3: if target found print ‘YES’
Otherwise print ‘NO’
Step 4: Stop
Time Complexity:
• Best Case: O(1) (if the target is at the beginning).
• Worst Case: O(n) (if the target is at the end or not present).
• Explanation: In the worst case, the algorithm iterates through every element of the array,
so the time complexity is O(n).
Space Complexity:
The amount of memory required by the algorithm to solve given problem is called space
complexity of the algorithm.
Ex: Find the Space Complexity of an algorithm to find the element through linear search.
Space Complexity Analysis:
• The algorithm uses a few fixed variables:
o arr[] (the input array) is given as input and does not affect the space complexity.
o target (the element being searched for) is also given.
o A counter variable i is used to traverse the array.
Since no additional memory is used other than these fixed variables, the space complexity remains
constant, regardless of the array's size.
Space Complexity:
• O(1) (constant space).
C Programming:
C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories
in 1972. It is a very popular language, despite being old. The main reason for its popularity is
because it is a fundamental language in the field of computer science.
C is strongly associated with UNIX, as it was developed to write the UNIX operating system.
Features of C Programming:
1) Simple: C is a simple language in the sense that it provides a structured approach (to break the
problem into parts), a rich set of library functions, data types, etc.
2) System Programming Language: C language is a system programming language because it
can be used to do low-level programming (for example driver and kernel).
3) Structured programming language: C is a structured programming language in the sense that
we can break the program into parts using functions. So, it is easy to understand and modify.
Functions also provide code reusability.
4) Mid-level programming language: Although, C is intended to do low-level programming. It is
used to develop system applications such as kernel, driver, etc. It also supports the features of a
high-level language. That is why it is known as a mid-level language.
5) Rich Library: C provides a lot of inbuilt functions that make the development fast.
6) Memory Management: It supports the feature of dynamic memory allocation. In C language,
we can free the allocated memory at any time by calling the free() function.
7) Pointer: C provides the feature of pointers. We can directly interact with the memory by using
the pointers. We can use pointers for memory, structures, functions, array, etc.
8) Extensible: C language is extensible because it can easily adopt new features.
9) Recursion: In C, we can call the function within the function. It provides code reusability for
every function. Recursion enables us to use the approach of backtracking.
Structure of C Program:
A The structure of a C program consists of several sections that follow a standard organization.
While some parts are optional depending on the complexity of the program, every C program
generally adheres to a similar format.
1) Documentation Section
This section consists of comment lines which include the name of the program, the name of the
programmer, the author and other details like time and date of writing the program.
Documentation section helps anyone to get an overview of the program.
/*Documentation Section:
Program Name: Program to find the area of circle
Author: M.Srinu
Date : 12/09/2024
Time : 10 AM
*/
2) Link Section
The link section consists of the header files of the functions that are used in the program. It
provides instructions to the compiler to link functions from the system library such as using the
#include directive.
Example:
#include<stdio.h> //link section
#include<conio.h> //link section
3) Definition Section
All the symbolic constants are written in the definition section. Macros are known as symbolic
constants.
#define PI 3.14 //definition section
6) Subprogram Section
The subprogram section contains all the user defined functions that are used to perform a specific
task. These user defined functions are called in the main() function.
If the program is a multifunction program, then the sub program section contains all the user-
defined functions that are called in the main () function. User-defined functions are generally
placed immediately after the main () function, although they may appear in any order.
void message()
{
printf("This Sub Function \n");
printf("we can take more Sub Function \n");
}
Program-001:
/*Documentation Section:
Program Name: Program to find the area of circle
Author: M.Srinu
Date : 12/09/2024
Time : 11 AM
*/
#include<stdio.h> //link section
#include<conio.h> //link section
#define PI 3.14 //definition section
float area; //global declaration section
void message();
int main()
{
float r; //declaration part
printf("Enter the radius of the circle\n"); //executable part
scanf("%f",&r);
area=PI*r*r;
printf("Area of the circle=%f \n",area);
message();
}
void message()
{
printf("This Sub Function \n");
printf("we can take more Sub Functions \n");
}
Program-002:
#include /* Link section */
int total=0 ; /* Global declaration, definition section */
int sum(int,int); /* Function declaration section */
int main() /* Main function */
{
printf("C programming basics & structure of C programs \n");
total=sum(6,6);
printf("sum=%d\n",total);
}
Token:
A token in C can be defined as the smallest individual element of the C programming language that
is meaningful to the compiler. It is the basic component of a C program.
Types of Tokens in C
The tokens of C language can be classified into six types based on the functions they are used to
perform. The types of C tokens are as follows:
Keywords:
• The keywords are pre-defined or reserved words in a programming language. Each
keyword is meant to perform a specific function in a program.
• Keywords are the words whose meaning has already been explained to the C compiler and
their meanings cannot be changed.
• Keywords can be used only for their intended purpose.
• Keywords cannot be used as user-defined variables.
• All keywords must be written in lowercase.
Identifiers:
Identifiers are user-defined names consisting of an arbitrarily long sequence of letters and digits
with either a letter or the underscore(_) as a first character.
Certain rules should be followed while naming c identifiers which are as follows:
• They must begin with a letter or underscore(_).
• They must consist of only letters, digits, or underscore. No other special character is
allowed.
• It should not be a keyword.
• It must not contain white space.
• It should be up to 31 characters long as only the first 31 characters are significant.
Ex: int a,b,c; //where a,b and c are identifiers and int a keyword.
Constants:
The constants refer to the variables with fixed values. They are like normal variables but with the
difference that their values cannot be modified in the program once they are defined. Constants
may belong to any of the data types.
Ex: const int x=10;
const float pi=3.142f;
Strings:
Strings are nothing but an array of characters ended with a null character (‘\0’). This null
character indicates the end of the string. Strings are always enclosed in double quotes. Whereas, a
character is enclosed in single quotes in C.
Ex: char branch[20]={‘C’,’S’,’E’};
char name[]=”Rajesh”;
Special Symbols:
The following special symbols are used in C having some special meaning and thus, cannot be used
for some other purpose. Some of these are listed below:
• Brackets[]: Opening and closing brackets are used as array element references. These
indicate single and multidimensional subscripts.
• Parentheses(): These special symbols are used to indicate function calls and function
parameters.
• Braces{}: These opening and ending curly braces mark the start and end of a block of code
containing more than one executable statement.
• Comma (, ): It is used to separate more than one statement like for separating parameters
in function calls.
• Colon(:): It is an operator that essentially invokes something called an initialization list.
• Semicolon(;): It is known as a statement terminator. It indicates the end of one logical
entity. That’s why each individual statement must be ended with a semicolon.
• Asterisk (*): It is used to create a pointer variable and for the multiplication of variables.
• Assignment operator(=): It is used to assign values and for logical operation validation.
• Pre-processor (#): The preprocessor is a macro processor that is used automatically by
the compiler to transform your program before actual compilation.
• Period (.): Used to access members of a structure or union.
• Tilde(~): Bitwise One’s Complement Operator.
Operators:
Operators are symbols that trigger an action when applied to C variables The data items on
which operators act are called operands.
Depending on the number of operands that an operator can act upon, operators can be classified
as follows:
Unary Operators: Those operators that require only a single operand to act upon are known as
unary operators. For example, increment and decrement operators
Binary Operators: Those operators that require two operands to act upon are called binary
operators. Binary operators can further be classified into:
1. Arithmetic operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Bitwise Operator
Ternary Operator: The operator that requires three operands to act upon is called the ternary
operator. Conditional Operator(?) is also called the ternary operator.
Variable:
Variable is a name of the memory location where the actual value is to be stored. A variable in C
is a memory location with some name that helps store some form of data and retrieves it when
required.
Syntax:
datatype variable_name; //Variable declaration
datatype variable_name=value; //Variable initialization
Ex: int number=123,sum=-456;
double pi=3.1416,average=-55.66;
2) Global Variables:
A Global variable in C is a variable that is declared outside the function or a block of code. Its
scope is the whole program i.e. we can access the global variable anywhere in the C program
after it is declared.
Program-004:
// C program to demonstrate use of global variable
#include <stdio.h>
void function1();
void function2();
int x = 20; // global variable
int main()
{
function1();
function2();
return 0;
}
void function1()
{
printf("Function 1: %d\n", x);
}
void function2()
{
printf("Function 2: %d\n", x);
}
3) Static Variables:
A static variable in C is a variable that is defined using the static keyword. It can be defined
only once in a C program and its scope depends upon the region where it is declared (can be
global or local).
The default value of static variables is zero.
Syntax:
static data_type variable_name = initial_value;
As its lifetime is till the end of the program, it can retain its value for multiple function calls as
shown in the example.
Program-005:
// C program to demonstrate use of static variable
#include <stdio.h>
void function()
{
int x = 20; // local variable
static int y = 30; // static variable
x = x + 10;
y = y + 10;
printf("\tLocal Variable X: %d\n\tStatic Variable Y: %d\n", x, y);
}
int main()
{
printf("First Call\n");
function();
printf("Second Call\n");
function();
printf("Third Call\n");
function();
return 0;
}
Output:
First Call
Local: 30
Static: 40
Second Call
Local: 30
Static: 50
Third Call
Local: 30
Static: 60
4) Automatic Variable:
All the local variables are automatic variables by default. They are also known as auto
variables. Their scope is local, and their lifetime is till the end of the block. If we need, we can
use the auto keyword to define the auto variables.
The default value of the auto variables is a garbage value.
Syntax: auto data_type variable_name;
or
data_type variable_name; //(in local scope)
Program-006:
// C program to demonstrate use of automatic variable
#include <stdio.h>
void function()
{
int x = 10; // local variable (also automatic)
auto int y = 20; // automatic variable
printf("Auto Variable: %d", y);
}
int main()
{
function();
return 0;
}
Output:
Auto Variable: 20
Note: In the above example, both x and y are automatic variables. The only difference is that
variable y is explicitly declared with the auto keyword.
5) External Variables:
External variables in C can be shared between multiple C files. We can declare an external
variable using the extern keyword. Their scope is global and they exist between multiple C
files.
Data types:
Each variable in C has an associated data type. It specifies the type of data that the variable can
store like integer, character, floating, double, etc. Each data type requires different amounts of
memory and has some specific operations which can be performed over it.
Different data types also have different ranges up to which they can store numbers. These ranges
may vary from compiler to compiler. Below is a list of ranges along with the memory requirement
and format specifiers.
Size Format
Data Type Range
(bytes) Specifier
Datatype Modifiers:
Modifiers are keywords in C which changes the meaning of basic data type in C. It specifies the
amount of memory space to be allocated for a variable. Modifiers are prefixed with basic data
types to modify the memory allocated for a variable.
Need of Datatype Modifiers:
We use int to store the Salary of the employee as we are assuming that the salary will be in whole
numbers. An integer data type takes 4 bytes of memory, and we are aware that the Salary of any
of the employee cannot be “Negative”.
We are using “4 Bytes” to store the salary of an employee and we can easily save 2 Bytes over there
by removing the “Signed Part” in the integer. This leads us to the use of Data Type Modifiers.
Types of Datatype Modifiers:
• Signed
• Size
• Const
Signed modifier:
All data types are “signed” by default. Signed modifier implies that the data type variable can store
positive values as well as negative values. For example, if we need to declare a variable to store
temperature, it can be negative as well as positive.
signed int temperature; Or int temperature;
If we need to declare a variable to store the salary of an employee, we will use “Unsigned” Data
modifier.
unsigned int salary;
Size Modifier:
Sometimes we need to increase the Storage Capacity of a variable so that it can store values higher
than its maximum limit which is there as default.
We need to make use of the “long” data type qualifier. “long” type modifier doubles the “length”
of the data type when used along with it.
For example, if we need to store the “annual turnover” of a company in a variable, we will make us
of this type qualifier.
long int turnover;
A “short” type modifier does just the opposite of “long” with 2 bytes in memory. If one is not
expecting to see high range values in a program and the values are both positive & negative.
For example, if we need to store the “age” of a student in a variable, we will make use of this type
qualifier as we are aware that this value is not going to be very high.
short int age;
Const modifier:
In C all variables are by default not constant. Hence, you can modify the value of variable by
program. You can convert any variable as a constant variable by using modifier const which is
keyword of C language.
Properties of constant variable:
You can assign the value to the constant variables only at the time of declaration.
For example:
const int i=10; float const f=0.0f; unsigned const long double ld=3.14L;
Uninitialized constant variable is not cause of any compilation error. But you cannot assign any
value after the declaration.
Example: const int i;
Note: The long, short, signed and unsigned are datatype modifiers that can be used with some
primitive data types to change the size or length of the datatype.
Literal:
In C, Literals are the constant values that are assigned to the variables. Literals represent fixed
values that cannot be modified.
There are 4 types of literals in C:
• Integer Literal
• Float Literal
• Character Literal
• String Literal
Integer literals are used to represent and store the integer values only. Integer literals are
expressed in two types i.e,
A) Prefixes: The Prefix of the integer literal indicates the base in which it is to be read.
a. Decimal-literal(base 10): A non-zero decimal digit followed by zero or more
decimal digits(0, 1, 2, 3, 4, 5, 6, 7, 8, 9). Ex: 15, 29 etc…
b. Octal-literal(base 8): a 0 followed by zero or more octal digits(0, 1, 2, 3, 4, 5, 6, 7).
Ex: 056, 0123 etc..
c. Hex-literal(base 16): 0x or 0X followed by one or more hexadecimal digits(0, 1,
2, 3, 4, 5, 6, 7, 8, 9, a, A, b, B, c, C, d, D, e, E, f, F).
Ex: 0x5A, 0XAABB etc….
d. Binary-literal(base 2): 0b or 0B followed by one or more binary digits(0, 1).
Ex: 0b101, 0B11011 etc…
B) Suffixes: The Suffixes of the integer literal indicates the type in which it is to be read.
These are represented in many ways according to their data types.
int: No suffix is required because integer constant is by default assigned as an int data
type.
unsigned int: character u or U at the end of an integer constant.
long int: character l or L at the end of an integer constant.
unsigned long int: character ul or UL at the end of an integer constant.
long long int: character ll or LL at the end of an integer constant.
unsigned long long int: character ull or ULL at the end of an integer constant.
Examples on printf():
printf(“Welcome to C Programming\n”); //Output: Welcome to C Programming
int a=10, b=20; printf(“%d %d\n”,a,b); //Output: 10 20
int a=10,b=20,c=a+b; printf(“sum of %d and %d is: %d\n”,a,b,c);//Output:sum of 10 and 20 is: 30
Examples on Scanf():
int n; scanf(“%d”,&n); //Read an integer value
int a,b,c; scanf(“%d %d %d”,&a,&b,&c); //Read there integer values
float p,q; scanf(“%f %f”,&p,&q); //Read two float values.
Char ch; scanf(“%c”,&ch); //Read a Character
Operators:
In C language, operators are symbols that represent operations to be performed on one or more
operands. C has a wide range of operators to perform various operations.
Types of Operators in C
C language provides a wide range of operators that can be classified into 6 types based on their
functionality:
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Bitwise Operators
5. Assignment Operators
6. Other Operators
1) Arithmetic Operators:
The arithmetic operators are used to perform arithmetic/mathematical operations on operands.
Those are +, -, *, / and %.
// Working of arithmetic operators
#include <stdio.h>
int main()
{
int a = 9,b = 4, c;
c = a+b;
printf("a+b = %d \n",c);
c = a-b;
printf("a-b = %d \n",c);
c = a*b;
printf("a*b = %d \n",c);
c = a/b;
printf("a/b = %d \n",c);
c = a%b;
printf("Remainder when a divided by b = %d \n",c);
return 0;
}
Output:
a+b = 13
a-b = 5
a*b = 36
a/b = 2
Remainder when a divided by b=1
2) Relational Operators:
A relational operator checks the relationship between two operands. If the relation is true, it
returns 1; if the relation is false, it returns value 0.
// Working of relational operators
#include <stdio.h>
int main()
{
int a = 5, b = 5, c = 10;
printf("%d == %d is %d \n", a, b, a == b);
printf("%d == %d is %d \n", a, c, a == c);
printf("%d > %d is %d \n", a, b, a > b);
printf("%d > %d is %d \n", a, c, a > c);
In bitwise shift operations, the digits are moved, or shifted, to the left or right.
6) Other Operators:
a) Conditional Opertor(?:)
The conditional operator is the only ternary operator in C.
Syntax: Expression1 ? Expression2 : Expression3
Output:
Size of int = 4 bytes
Size of float = 4 bytes
Size of double = 8 bytes
Size of char = 1 byte
c) Comma(,), dot(.), addressof(&), dereference(*), arrow(->) etc….
Operator Precedence and Associativity:
Precedence: The precedence of operators determines which operator is executed first if there
is more than one operator in an expression.
For Example:
10+20*30 => 610 [Right]
10+20*30 => 900 [Wrong]
Associativity: It defines the order in which operators of the same precedence are evaluated in an
expression. Associativity can be either from left to right or right to left.
2) Explicit Conversion
This conversion is done by user. This is also known as typecasting. In this one data type is
converted into another data type forcefully by the user. In explicit typecasting, the conversion
involves a larger data type to the smaller data type.
Important Questions:
1. Differentiate Hight Level, Middle Level and Low-Level Programming Languages.
2. Define an algorithm. List the characteristics of an algorithm.
3. List and explain the programming strategies or approaches.
4. What is a Time and Space complexity of an algorithm.
5. Differentiate Compiler, Assembler and interpreter.
6. What is the structure of C program and explain in detail of each section.
7. Describe the following
a) C Character set b) Token c) Identifier d) Variable e) Constant
8. What is data type and explain different data types supported by C.
9. Define an operator. List and describe different types of operators in C programming with an
example program.
10. Explain Operator Precedence and Associativity with an example program.
11. Demonstrate the use of printf() and scanf() with an example programs.
12. What is type casting? Demonstrate with an example program.
Programs to Practice:
1. Program to find the simple interest.
2. Program to find the conversion from Fahrenheit to Celsius.
3. Program to find the distance between two points.
4. Program to find the square root of a given number.
5. Program to find the area of Triangle using Heron’s formula.
6. Program to find the BMI value.
Practice the flow chart design for above programs also using dia tool.