c unit I
c unit I
2024
COURSE MATERIAL
1
C programming
2024
Unit 1
Fundamentals of Computer, Data Types and Operators
Introduction to C Programming
C is a High Level Language used both as general purpose programming language and
special purpose programming language. It was developed at Bell laboratory (AT and T’s)
in 1972; it is the outcome of the efforts of Dennis Ritchie. C language combines the
features of three earlier programming languages such as ALGOL (Algorithm Oriented
Language), BCPL (Basic combined programming language) and ‘B’ language. C
programming language contains all the features of these languages and many more
additional concepts.
In 1978 Dennis Ritchie and Brain Kernighan together published a detailed description
of C language and renamed as ‘K and R C’. In 1983 ANSI (American National
Standards Institute) published a standard for c language.
‘C’ is strongly associated with the UNIX operating system. Initially ‘C’ programming
was limited to the UNIX operating system. Today ‘C’ runs under a variety of operating
systems and hardware platforms. As it started evolving many different versions of the
language were released.
Problem definition-
In C language, a problem definition refers to a clear statement that describes the objective of a
program or application. It outlines the problem to be solved and the requirements of the solution.
2
C programming
2024
Program design-
Overview
Program design consists of the steps a programmer should do before they start coding the
program in a specific language. These steps when properly documented will make the completed
program easier for other programmers to maintain in the future. There are three broad areas of
activity:
Flowchart-
The solution of any problem in picture form is called flowchart. It is the one of the most important
technique to depict an algorithm.
Advantage of Flowchart:
1. Easier to understand
2. Helps to understand logic of problem
3. Easy to draw flowchart in any software like MS-Word
4. Complex problem can be represent using less symbols
5. It is the way to documenting any problem
6. Helps in debugging process
Disadvantage of Flowchart:
3
C programming
2024
Algorithm:
Algorithm is the set of rules that define how particular problem can be solved in finite number of
steps. Any good algorithm must have following characteristics
Advantages of Algorithms:
Disadvantage of Algorithms:
1. It is time consuming
2. Difficult to show branching and looping statement
3. Large problems are difficult to implement
4
C programming
2024
Pseudo code:-
What Is Pseudo-Code in C?
Example:
This program will print first N numbers of Fibonacci series.
Use standard programming structures such as if-else, for, while, and cases the way we
use them in programming. Indent the statements if-else, for, while loops as they are
indented in a program, it helps to comprehend the decision control and execution
mechanism. It also improves readability to a great extent.
Example:
if “1”
print response
“I AM CASE 1”
if “2”
print response
“I AM CASE 2”
Use appropriate naming conventions. The human tendency follows the approach of
following what we see. If a programmer goes through a pseudo code, his approach will
be the same as per that, so the naming must be simple and distinct.
5
C programming
2024
Reserved commands or keywords must be represented in capital letters.
Example: if you are writing IF…ELSE statements then make sure IF and ELSE be in capital
letters.
Check whether all the sections of a pseudo code are complete, finite, and clear to
understand and comprehend. Also, explain everything that is going to happen in the
actual code.
Don’t write the pseudo code in a programming language. It is necessary that the pseudo
code is simple and easy to understand even for a layman or client, minimizing the use of
technical terms.
What is a Decision Table?
A decision table is a good way to settle different combination inputs with their corresponding
outputs and is also called a cause-effect table.
1. The reason to call the cause-effect table is a related logical diagramming technique
called cause-effect graphing that is used to obtain the decision table.
2. The information represented in decision tables can also be represented as decision trees
or in a programming language using if-then-else and switch-case statements.
Importance of Decision Table
Programming methodology
When programs are developed to solve real-life problems like inventory management, payroll
processing, student admissions, examination result processing, etc. they tend to be huge and
complex. The approach to analyzing such complex problems, planning for software development
and controlling the development process is called programming methodology.
6
C programming
2024
There are many types of programming methodologies prevalent among software developers −
Procedural Programming
Problem is broken down into procedures, or blocks of code that perform one task each. All
procedures taken together form the whole program. It is suitable only for small programs that
have low level of complexity.
Example − For a calculator program that does addition, subtraction, multiplication, division,
square root and comparison, each of these operations can be developed as separate procedures. In
the main program each procedure would be invoked on the basis of user’s choice.
Object-oriented Programming
Here the solution revolves around entities or objects that are part of problem. The solution deals
with how to store data related to the entities, how the entities behave and how they interact with
each other to give a cohesive solution.
Example − If we have to develop a payroll management system, we will have entities like
employees, salary structure, leave rules, etc. around which the solution must be built.
Functional Programming
Here the problem, or the desired solution, is broken down into functional units. Each unit
performs its own task and is self-sufficient. These units are then stitched together to form the
complete solution.
Example − A payroll processing can have functional units like employee data maintenance, basic
salary calculation, gross salary calculation, leave processing, loan repayment processing, etc.
Logical Programming
Here the problem is broken down into logical units rather than functional units.
Example: In a school management system, users have very defined roles like class teacher,
subject teacher, lab assistant, coordinator, academic in-charge, etc. So the software can be divided
into units depending on user roles. Each user can have different interface, permissions,
etc.Software developers may choose one or a combination of more than one of these
methodologies to develop software. Note that in each of the methodologies discussed, problem
has to be broken down into smaller units. To do this, developers use any of the following two
approaches −
Top-down approach
Bottom-up approach
7
C programming
2024
The drawback of using the top-down approach is that it may have redundancy since every part of
the code is developed separately. Also, there is less interaction and communication between the
modules in this approach.
Bottom-Up Approach is one in which the smaller problems are solved, and then these solved
problems are integrated to find the solution to a bigger problem. Therefore, it uses composition
approach.
One of the primary characteristics is the clarity and readability of the language. A good
programming language should have syntax and structure that are easy to understand, reducing the
chances of errors and enhancing collaboration among developers.
Versatility is vital for a programming language to cater to various application domains. A good
language should be flexible enough to adapt to different paradigms, allowing developers to use it
for a wide array of projects.
8
C programming
2024
5. Community Support
6. Security Measures
Security is a paramount concern in the digital age. A good programming language incorporates
built-in security features to help developers create robust and secure applications, protecting user
data and preventing vulnerabilities.
7. Scalability
Scalability is crucial for languages used in large-scale applications. A good programming language
should facilitate the development of scalable solutions, ensuring they can handle increased
workloads without compromising performance.
8. Ease of Learning
Accessibility is key. A good programming language should have a gentle learning curve, allowing
newcomers to grasp the basics quickly. This promotes a wider adoption of the language and
encourages a diverse developer community.
9. Documentation
10. Consistency
Consistency in syntax and behavior across the language is essential. It ensures that developers can
predict how code will behave, fostering a smoother development process and reducing debugging
time.
9
C programming
2024
11. Compatibility
Effective error handling is crucial for identifying and resolving issues in a timely manner. A good
programming language provides robust mechanisms for error detection and graceful recovery.
13. Abstraction
Abstraction simplifies complex concepts, making them more manageable. A good programming
language should offer abstraction mechanisms that enable developers to work at higher levels
without getting bogged down by unnecessary details.
14. Interoperability
Adaptability to evolving industry trends is key. A good programming language undergoes regular
updates and enhancements to stay relevant, incorporating new features and improvements.
Structured Programming
10
C programming
2024
which may, in turn, contain other such elements. Within each element, code may be further
structured using blocks of related logic designed to improve readability and maintainability.
Modular programming, which is today seen as synonymous with structured programming,
emerged a decade later as it became clear that reuse of common code could improve developer
productivity. In modular programming, a program is divided into semi-independent modules, each
of which is called when needed. C is called structured programming language because a program
in c language can be divided into small logical functional modules or structures with the help of
function procedure.
1. A high level language has to be translated into the machine language by translator and thus a
price in computer time is paid.
11
C programming
2024
3. Data types are proceeds in many functions in a structured program. When changes occur in
those data types, the corresponding change must be made to every location that acts on those data
types within the program. This is really a very time consuming task if the program is very large.
4. Let us consider the case of software development in which several programmers work as a team
on an application. In a structured program, each programmer is assigned to build a specific set of
functions and data types. Since different programmers handle separate functions that have
mutually shared data type. Other programmers in the team must reflect the changes in data types
done by the programmer in data type handled. Otherwise, it requires rewriting several functions.
Data types in C:
Data type is an attribute of a variable that indicates the type of data that a variable
can hold. Each variable is declared in the beginning of a program. C support three
classes of data type
Data types
a) Primitive or Fundamental or Basic data types: These are the data type whose
meaning is already defined in the compiler. The C language provides 4 basic data
types namely char, int , float and double.
int data type: An integer data type is a whole number without a decimal
point. int is a keyword used to indicate integer data type. It occupies 2 bytes
of computer memory.
e.g.: int x, y, z;
float data type: The float is the keyword used to indicate the real numbers.
These are the numbers with decimal point. They occupy 4 bytes of computer
memory.
e.g.: float area;
char data type: char is a keyword used to declare character type data.It
12
C programming
2024
occupies 1 byte of memory
e.g: char ch;
b) Derived data types: These are created from basic data types such as int, float,
char, etc.
e.g.: arrays, strings, structures, unions, pointer etc
c) User defined data types: Those data types which are defined by the user
according to the requirement and called user-defined data types.
e.g: structures, unions, typedef, enum etc.
Type conversion: C allows the conversion of one data type to another. The process of
converting one data type into another is called type conversion. There are 2 types
1) Implicit type conversion
2) Explicit type conversion
e.g: i) int x,
float y;
If x+y is performed, int converts to float and returns float.
ii) If two variables are int and long int , int converts into long.
Explicit type conversion (Type casting): The data type conversion performed by
the user is called explicit type conversion or type casting.
Syntax : (data type)
expression; e.g: int
x,y;
float m;
m= (float) x/y; this assignment causes x to be converted to float before division.
13
C programming
2024
Data modifiers: C allows the use of data type modifiers which modify the existing basic
data types according to requirements. There are four modifiers signed, unsigned, long
and short are prefixed and used with integer data types.
14
C programming
2024
Valid identifiers:X, abc, simple_interest , a123, stud_name
3.Variables: The quantity that changes during the execution of the program is called
variable. It is a named location in the memory that is used to hold a value. The rules
for forming variables names are same are same as identifiers.
3. Constants: A constant is a quantity that does not change during the execution of
the program.
C constants
15
C programming
2024
1. Decimal integer constants containing digits from 0 to 9. e.g.: 246, + 25, -30 etc.
2. Octal integer constant containing digit from 0 to 7. e.g: 0673, 057 etc.
3. Hexadecimal integer constants containing digits from 0 to 9, A to F. e.g.:
0x24, 0xaf etc.
Floating constant: Real or floating point number can contain both an integer part and
fractional part in the number. Floating point numbers may be represented in 2 from either
in the fractional form in the exponent form.
A floating point numbers in fractional from consists if signed or unsigned digits
including a decimal point between digits.
e.g: 25.6, 0.568.
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 and C++.
Examples of String
char string[20] = {‘h’,’e’,’l’,’l’,’o’,’w’,’o’,’r’,’l’,’d’ };
char string[20] = “helloworld”;
char string [] = “helloworld”;
Operators
Operators are symbols that trigger an action when applied to C variables and other objects. 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 are classified into:
1. Arithmetic operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Bitwise Operator
16
C programming
2024
Ternary Operator: The operator that requires three operands to act upon is called the
ternary operator. Conditional Operator (?) is also called the ternary operator.
5.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.
Structure of a C Program
A C program is divided into different sections. There are 6 main sections to a basic c
program.
Documentation
Link
17
C programming
2024
Global Declarations
Main functions
Definition and statements
Subprograms
1. Documentation
This section consists of the description of the program, the name of the program, and the
creation date and time of the program. It is specified at the start of the program in the form of
comments. Documentation can be represented as:
// description, name of the program, programmer name, date, time etc.
Or
/*
description, name of the program, programmer name, date, time etc.
*/
Anything written as comments will be treated as documentation of the program and this will not
interfere with the given code. Basically, it gives an overview to the reader of the program.
2. Preprocessor Section
All the header files of the program will be declared in the preprocessor section of the program.
Header files help us to access other’s improved code into our code. A copy of these multiple
files is inserted into our program before the process of compilation.
Example:
#include<stdio.h>
#include<math.h>
3. Definition
Preprocessors are the programs that process our source code before the process of compilation.
There are multiple steps which are involved in the writing and execution of the program.
Preprocessor directives start with the ‘#’ symbol. The #define preprocessor is used to create a
constant throughout the program. Whenever this name is encountered by the compiler, it is
replaced by the actual piece of defined code.
Example:
#define long long ll
4. Global Declaration
The global declaration section contains global variables, function declaration, and static
variables. Variables and functions which are declared in this scope can be used anywhere in the
program.
Example:
18
C programming
2024
int num = 18;
5. Main() Function
Every C program must have a main function. The main() function of the program is written in
this section. Operations like declaration and execution are performed inside the curly braces of
the main program. The return type of the main() function can be int as well as void too. void()
main tells the compiler that the program will not return any value. The int main() tells the
compiler that the program will return an integer value.
Example:
void main()
or
int main()
6. Sub Programs
User-defined functions are called in this section of the program. The control of the program is
shifted to the called function whenever they are called from the main or outside the main()
function. These are specified as per the requirements of the programmer.
Example:
int sum(int x, int y)
{
return x+y;
}
e.g :
e.g.:
#include
<stdio.h> void Output:
2. Write a programmain to
( ) find the area of triangle KARNATAKA
#include<stdio.h > {
void main() printf(“\n
{
float b ,h, a;
b= 2;
h= 10;
a = 0.5*b*h ;
printf("\n\n Area of Triangle is: %f",a); Area of Triangle is:
} 10.000000
19
C programming
2024
3. Step 3: Executing / Running Executable File (Ctrl + F9) .
4. Step 4: Check Result (Alt + F5)
Compilation process in c:
The compilation is a process of converting the source code into object code or
machine code.
The compilation process is divided into 4 steps, i.e.,Pre-processing, Compiling,
Assembling and Linking.
Preprocessor: The source code written in a text editor is given a file name with
extension ".c". This source code is first passed to the preprocessor and then the
preprocessor expands this code. After expanding the code, the expanded code is passed
to the compiler.
Compiler: The code which is expanded by the preprocessor is passed to the compiler.
The compiler converts this code into assembly code.
Assembler: The assembly code is converted into object code by an assembler. The
name of the object file generated by the assembler is same as the source file. The
extension of the object file is '.obj,’. If the name of the source file is 'hello.c', then the
object file name is 'hello.obj'.
Linker: All programs written in C use library functions. These functions are pre-
compiled and the object code of these library files is stored with '.lib' extension. The
working of the linker is to combine the object code of library files with the object code
of our program. The job of the linker is to link the object code of our program with the
object code of the library files & other files. The output of the linker is the executable
file. The name of the executable file is same as the source file but differs only in their
extensions. The extension of the executable file is '.exe', Comment
20
C programming
2024
Statements: Comment lines are written for the easy accessibility for the user. These
comment lines are ignored by compliers. There are two types of comments
1. Single line comment:
The single line comment is //. Everything from the // to the end of the line is a
comment.
2. Multiple comment lines:
This comment starts with a slash asterisk /* and ends with a asterisk slash */.
Note: Comment lines may used anywhere in the program.
Applications of C: C is used to develop the system software as well as application
software.
System s\w:
O/S
Interpreters.
Compilers.
Assemblers.
Editors.
Loaders.
Linkers.
In these examples, age, weight and gender are variables which are declared as
integer data type, floating data type and character data type respectively.
Initialization is a process in which a variable is assigned an initial value before it is
used in the program.
C variables declared can be initialized with the help of assignment operator '='
There are two types of variable Initialization:
Declaring the variable and then
initializing it int a;
a = 5;
Declaring and initializing the variable together:
int a = 5;
Symbolic constants: A symbol can be used as a constant by giving the
symbol a value. The value can then be referred to by the symbol name, instead of
by using the value itself.
21
C programming
2024
A symbolic constant is defined by writing #define and placed at the beginning of the
program.
Symbolic names are written in uppercase letters.
The text part may be a character constant, numeric constant or string constant.
They should not end with semicolon.
They are preprocessor directives (like #include) and not executable C statements
#include<stdio.H>
#define PI 3.14
int main()
{
int r,circum;
printf(enter the value of r);
scanf(“%d”,&r);
circum=2*PI*r;
printf(“circumference of circle is”,circum);
getch();
}
Constants in C
The constants in C are the read-only variables whose values cannot be modified once they are
declared in the C program. The type of constant can be an integer constant, a floating pointer
constant, a string constant, or a character constant. In C language, the const keyword is used to
define the constants.
In this article, we will discuss about the constants in C programming, ways to define constants
in C, types of constants in C, their properties and the difference between literals and constants.
What is a constant in C?
As the name suggests, a constant in C is a variable that cannot be modified once it is declared in
the program. We can not make any change in the value of the constant variables after they are
defined.
22
C programming
2024
How to Define Constant in C?
We define a constant in C language using the const keyword. Also known as a const type
qualifier, the const keyword is placed at the start of the variable declaration to declare that
variable as a constant.
Syntax to Define Constant
Unary operators: An operator that acts on only one operand is called a unary operator.
Unary minus
Logical NOT
Bitwise complementation
Increment
Decrement
sizeof() operator
23
C programming
2024
-- is post decrement
++a is pre increment --a is pre decrement
Increment operator is used to increment the value of an
integer by
#include<stdio.h>
main ()
{
int a=8, b=12; clrscr(); a=8
printf (“a= %d\n”, a--); b=1
printf(“b=%d\n”,--b); 1
getch();
}
#include<stdio.h>
#include<conio.h>
int main()
{ Enter the value of
int x; x: 8 x=8
clrscr(); x=9
printf("Enter the value of x: ");
scanf("%d",&x);
printf (“x= %d\n”, x++);
printf (“x= %d\n”, x);
getch();
}
24
C programming
2024
In pre increment, operand is incremented before execution.
In post increment, operand is incremented after execution.
Binary Operators: These operators not upon two operators C operators have
several binary
operators.
i. Arithmetic operators
ii. Assignment operators
iii. Relational operators
iv. Logical operators
v. Bitwise operators
1. Arithmetic operators: Basic arithmetic operations like addition, subtraction,
multiplication and division are performed using +, - ,* and /. Also modulus operator
(%) is used to get the reminder after integer division.
2.Assignment operators: This operator is used to assign the value from right side
to left side
variable. The operator used is “=”
e.g: a=5; this assigns 5 to variable a.
a=b; this assigns value of b to variable a.
a=(x+y); this assigns the value of expression x+y to variable a.
In assignment expressions the LHS should be a variable while the RHS may be a
constant, a variable or an expression.
The short hand assignment operators like +=,-=,*=,/= and %= are also used.
25
C programming
2024
the relation is true) or zero (if the relation is false).There are 6 relational
operators in C.
4.Logical operators: The symbols used to perform logical operations are &&, || and.
Logical AND operator is used to perform the multiplication. The result of a logical AND
is true when both the operands are true.
X Y X && Y
False False False
False True False
True False False
True True True
26
C programming
2024
The logical NOT is used to get the logical complement of the operand. The result
of a logical NOT is true when the operand is false & vice versa
Operand ! Operand
False True
True false
5.Bitwise operators: In C language, the features of low level language are included
for bit level manipulation, which is done using bitwise operators. The bitwise operators
in c are
27
C programming
2024
6. Bitwise right shift operator (>>)
28
C programming
2024
sizeof () operator: The sizeof ( ) operator returns the size of the operand in bytes. The
sizeof() operator is a key word in c
Syntax:sizeof (operand);
Arithmetic Expressions
Evaluation of Expressions
Expressions are evaluated using an assignment statement of the form
Variable = expression;
Variable is any valid C variable name. When the statement is encountered, the expression is
evaluated
first and then replaces the previous value of the variable on the left hand side. All variables used
in the expression must be assigned values before evaluation is attempted.
The operators used in C-Language are evaluated in a complex C expression by following the order
of Precedence. Higher level precedence operators are evaluated first and then the lower level
precedence operators are evaluated. Associativity specifies the order of operations when operators
have the same priority. Associativity can be either left to right [called left associativity ] or right to
left [called right associativity]. Some of the operator precedence and their associativity is as
shown below.
*********
30
C programming
2024
31