0% found this document useful (0 votes)
17 views

c unit I

best notes

Uploaded by

Amogh
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

c unit I

best notes

Uploaded by

Amogh
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 31

C programming

2024

SCHOOL OF APPLIED SCIENCE

Bachelor of Computer Applications (BCA)

COURSE MATERIAL

COURSE NAME: C PROGRAMMING

CODE: 24BCAGL101- SEM: I

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 a widely used professional language for various reasons


 Easy to learn
 Structured language
 It produces efficient programs
 It can be compiled on a variety of computer platforms

‘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:

 Understanding the Program


 Using Design Tools to Create a Model
 Develop Test Data

Techniques of problem solving:

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.

The blueprint of algorithm called flowchart.

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:

1. For any change, Flowchart have to redrawn


2. Showing many looping and branching become complex
3. Modification of flowchart is time consuming

3
C programming
2024

Symbol Used in Flowchart:

Symbol Name Description

Terminal Terminal represent start and


end

Input / Output Used for input (reading) and


output (printing) operation.

Processing Used for data manipulation


and data operations.

Arrow Used to represent flow of


operations.

Connector Used to connect different


flow of lines

Decision Used to make decision

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

1. Input: Specify and require input


2. Output: Solution of any problem
3. Definite: Solution must be clearly defined
4. Effective
5. Finite: Steps must be finite
6. Correct: Correct output must be generated

Advantages of Algorithms:

1. It is the way to sole a problem step-wise so it is easy to understand.


2. It uses definite procedure.
3. It is not dependent with any programming language.
4. Each step has it own meaning so it is easy to debug

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?

A Pseudocode is defined as a step-by-step description of an algorithm. Pseudocode does not use


any programming language in its representation instead it uses the simple English language text
as it is intended for human understanding rather than machine reading.
Pseudocode is the intermediate state between an idea and its implementation (code) in a
high-level language.

What is the need for Pseudocode


Pseudocode is an important part of designing an algorithm, it helps the programmer in planning
the solution to the problem as well as the reader in understanding the approach to the problem.
Pseudocode is an intermediate state between algorithm and program that plays supports the
transition of the algorithm into the program.

How to write Pseudocode?


Before writing the pseudo code of any algorithm the following points must be kept in mind.
 Organize the sequence of tasks and write the pseudo code accordingly.
 At first, establishes the main goal or the aim.

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

Decision tables are very helpful in test design techniques.


1. Helps testers to search effects of combinations: It helps testers to search the effects of
combinations of different inputs and other software states that must correctly implement
business rules.
2. Helps to start complex business rules: It provides a regular way of starting complex
business rules that is helpful for developers as well as for testers.
3. Helps in the development process: It assists in the development process with the
developer to do a better job. Testing with all combinations might be impractical.
4. Used in testing: A decision table is basically an outstanding technique used in both
testing and requirements management.
5. Helps to prepare requirements: It is a structured exercise to prepare requirements
when dealing with complex business rules.
6. Helps to model complicated logic: It is also used to model complicated logic.

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.

Types of Programming Methodologies

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

What is Top-Down Approach?

Top-Down Approach is an approach to design algorithms in which a bigger problem is broken


down into smaller parts. Thus, it uses the decomposition approach. This approach is generally
used by structured programming languages such as C, COBOL, FORTRAN.

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.

The implementation of algorithm using top-down approach depends on the programming


language and platform. Top-down approach is generally used with documentation of module
and debugging code.

What is Bottom-Up 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.

It requires a significant amount of communication among different modules. It is generally used


with object oriented programming paradigm such as C++, Java, and Python. Data encapsulation
and data hiding is also implemented in this approach. The bottom-up approach is generally used in
testing modules.List of Characteristics of Good Programming Language

1. Evolution and Updates

Adaptability to evolving industry trends is key. A good programming language undergoes


regular updates and enhancements to stay relevant, incorporating new features and
improvements.

2. Clarity and Readability

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.

3. Efficiency and Performance

Efficiency is a cornerstone of programming languages. A language should allow developers to


write code that executes quickly and consumes minimal system resources. This ensures optimal
performance of applications developed in that language.

4. Flexibility and Versatility

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

A thriving community is a testament to the language’s popularity and support. A good


programming language should have an active community that contributes to its growth, provides
solutions to issues, and shares knowledge.

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

Comprehensive and user-friendly documentation is indispensable. Good programming languages


provide extensive documentation that guides developers through various aspects, from installation
to advanced features, promoting efficient use.

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

Interoperability with other languages and systems is a valuable characteristic. A good


programming language should allow seamless integration with existing codebases and
technologies, promoting collaboration and reuse of resources.

12. Error Handling

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

Interoperability fosters collaboration between different technologies. A good programming


language should support interoperability, allowing developers to use libraries and components from
other languages seamlessly.

15. Evolution and Updates

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

Structured programming (sometimes known as modular programming) is a programming


paradigm that facilitates the creation of programs with readable code and reusable components.
All modern programming languages support structured programming, but the mechanisms of
support, like the syntax of the programming languages, varies. Structured programming
encourages dividing an application program into a hierarchy of modules or autonomous elements,

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.

Advantages of structured programming


The primary advantages of structured programming are:
1. It encourages top-down implementation, which improves both readability and maintainability
of code.
2. It promotes code reuse, since even internal modules can be extracted and made independent,
residents in libraries, described in directories and referenced by many other applications.
3. It's widely agreed that development time and code quality are improved through structured
programming.
4. It is user friendly and easy to understand.
5. Similar to English vocabulary of words and symbols.
6. It is easier to learn.
7. They require less time to write.
8. They are easier to maintain.
9. These are mainly problem oriented rather than machine based.
10. Program written in a higher level language can be translated into many machine languages
and therefore can run on any computer for which there exists an appropriate translator.
11. It is independent of machine on which it is used i.e. programs developed in high level
languages can be run on any computer.

Disadvantages of structured programming

The following are the disadvantages of structured programming:

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

2. The object code generated by a translator might be inefficient compared to an equivalent


assembly language program.

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

Built in data types Derived data types User defined data


e.g: int, float, char, double e.g: arrays, strings, structures, unions, pointer types
etc e.g: typedef, enum etc.

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;

 double: It is a keyword to indicate double precision floating point numbers. It


is used to declare the variable to hold large real numbers with higher precision.
It occupies 8 bytes of memory.
e.g.: double m;

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

 Implicit type conversion: The type conversion performed automatically by


the complier is called implicit type conversion. This conversion is applied in
arithmetic manipulations when variables of different types are intermixed in
an expression.

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.

 Short: It is nothing but int data type with 2 bytes of memory


 Long: it is used to double the size of an existing data type.
 Unsigned: it is used to store only positive data elements.
 Signed: it is a default data type that includes both +ve and -ve values

The size and ranges of basic data types are as follows:

Data type Size in Bytes Range of values


char 1 -128 to +128
unsigned char 1 0 to 256
int 2 -32768 to +32767
unsigned int 2 0 to 65535
short int 2 -32768 to +32767
long int 4 -21147483648 to +21147483647
float 4 -3.4X10E-48 to +3.4X10E48
double 8 -1.7X10E-308 to +1.7X10E308
unsigned long int 4 0 to 4294967295

C Tokens: Tokens is the most important element used in creating a program in C. A


token is defined as the basic and smallest unit of a c program. There are five tokens in
C.
 Identifier
 Keyword
 Constant
 Strings
 Operator
 Special symbols

1. Identifier: An identifier is a name given to the programming element like variable,


array, sting, function etc.

Rules for Identifiers:


1. First character must be alphabet or an underscore.
2. Keywords should not be used as identifiers.
3. Identifier should not contain blank space.
4. Identifiers consist of letters, digits and underscore (no other special symbol is
used).
5. Only 31 characters are significant

14
C programming
2024
Valid identifiers:X, abc, simple_interest , a123, stud_name

Invalid identifiers: 10abc, my-name, “hello”, simple interest, Dept. of CS,

2. Keywords (reserve words):


Keyword is a word that has one or more fixed meaning. Keyword must be written in
lower case. There are 32 keywords in c language.
auto double int break const continue do for
else long case enum float unsigned if void
register char extern return short signed go to volatile
sizeof default struct static switch typedef union while

These reserved words should not be used as constants or variables or identifiers.

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.

Syntax:data type variable list;


e.g: int x, y;
x and y are the variables of type integer.

3. Constants: A constant is a quantity that does not change during the execution of
the program.
C constants

Non Numeric (Character) constant Numeric constant

Integer Constant Floating point constant Single character constant String

Integer Constant: It is a sequence of digits without a decimal point. It is prefixed with


plus or minus sign.
There are 3 types.

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.

Character constant: Single character constant contains a single character enclosed


within a pair
of single quote marks. e.g: ‘a’, ‘?’, ‘#’ etc.
String constant is a sequence of characters enclosed within a pair of double quotes.
e.g: “hello”, “x+2”, “2000” etc.

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.

 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.

C Programming Basic Concepts:


Character Set: The characters in c grouped into following categories.

a) Letters (Alphabets): Upper case A.....Z, Lower case a z


b) Digits: All decimal digits 0........9
c) Special characters: #, +,&...etc....
d) White space: Blank space, new line (\n), horizontal tab (\t), vertical tab (\v)
etc

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

Creating and Executing a C Program


The linker combines the code from specified header file into an object file and generates
executable file as Sample.exe. With this compilation process completes.
1. Step 1: Creating a Source Code.
2. Step 2: Compile Source Code (Alt + F9) .

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.

Declaration & initialization of variables


Declaration of a variable is a statement used to specify the variable name and its data type.
Declaration tells the compiler about the existence of an entity in the program and its location.
The declaration gives a name and a data type for
the variable.
e.g.:int age;
float weight;
char gender;

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

Syntax: #define PI 3.14;

Eg:Program to find area of circumference

#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

const data_type var_name = value;s

C Operators and expressions


Operator is a symbol or set of symbols that works with one or more operands to
perform a specific operation. Operators are broadly classified into 3 categories.
C operators

Unary operators Binary operators Ternary operator

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

Increment OR Decrement Operator: This operator is used to increment or


decrement the value of variable by 1.The symbol ++ and - - are used respectively for
this purpose. They are placed before or after the integer variable.
++ is the increment operator. -- is the
decrement operator a++ is post increment a

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

1. Write a program to illustrate the increment operator


#include<stdio.h>
main ()
{
int a=5,b=6;
a=5
clrscr();
printf(“a=%d\n”,a++); b=7
printf(“b=%d\n”,++b);
getch();
}

Decrement operator is used to decrement the value of an


integer by

1.Write a program to illustrate the decrement operator

#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.

Program to illustrate the arithmetic operators


#include<studio.h>
main()
{
int a,b;
printf(“enter 2numbers a&b \n”);
scanf(“%d%d”,&a,&b”);
printf(“Sum=%d”, a+b);
printf(“Difference=%d”, a-b);
printf(“Product=%d”, a*b);
printf(“Quotient=%d”, a/b);
printf(“Reminder=%d”, a%b);
getch();
}

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.

3.Relational operators: Relational operators are used to test the relationship


between two operands. The value of a relational expression result is either 1(if

25
C programming
2024
the relation is true) or zero (if the relation is false).There are 6 relational
operators in C.

Operator Meaning Relational Resul


expression t
< Lesser than 6<7 1
> Greater than 6>7 0
<= Less than or equal 6<=7 1
to
>= Greater than equal 6>=7 0
to
== Equal to 6==7 0
!= Not equal to 6!=7 1 Program to
the relational operators
#include <stdio.h>
int main()
{
int a=5, b=3;
clrscr();
printf(" a > b: %d \n", a > b);
printf("a >= b: %d \n", a >= b);
printf("a <= b: %d \n", a <= b);
printf("a < b: %d \n", a < b);
printf("a == b: %d \n", a == b);
printf("a != b: %d \n", a != b);
getch();
}

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

Logical OR operator is used to perform logical addition operation. The result of a


logical OR is false when both the operands are false otherwise the result is true.
X Y X || Y
False False False
False True True
True False True
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

Program to illustrate logical operators


#include<stdio.h>
#include<conio.h>
main()
{
int x=5,y=6,z=7;
clrscr();
printf("(x<y)&&(y<z) =%d\n", (x<y)&&(y<z));
printf("(x<y)&&(y>z) =%d\n", (x<y)&&(y>z));
printf("(x>y)&&(y>z) =%d\n", (x>y)&&(y>z));
printf("(x>y)&&(y<z) =%d\n", (x>y)&&(y<z));
printf("(x<y)||(y<z) =%d\n", (x<y)||(y<z));
printf("(x<y)||(y>z) =%d\n", (x<y)||(y>z));
printf("(x>y)||(y>z) =%d\n", (x>y)||(y>z));
printf("(x>y)||(y<z) =%d\n", (x>y)||(y<z));
printf("!(x>y) =%d\n", !(x>y));
printf("!(x<y)=%d\n",!(x<y));
getch();
}

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

1. Bitwise AND operator (&)


2. Bitwise OR operator (OR)
3. Bitwise NOT operator (~)
4. Bitwise exclusive OR operator (^)
5. Bitwise left shift operator (<<)

27
C programming
2024
6. Bitwise right shift operator (>>)

Note: Bitwise operators work only on unsigned integer

Program to illustrate bitwise operators


#include <stdio.h>
#include<conio.h>
main()
{
int a = 20; // 20 = 010100
int b = 21; //21=010101
printf("AND - Value of c is %d\n", a & b);
printf("OR - Value of c is %d\n", a | b );
printf("Exclusive-OR - Value of c is %d\n", a ^ b);
getch();
}

Ternary operator (Conditional operator):


A ternary operator works on 3 operands. Ternary operator works like if else.
Syntax: (condition)?exp1:exp2;
If condition is true, exp1 is executed & skip exp2. If condition is false, exp2 is executed
& skip exp1.
e.g.:x>y?puts("x is greater"):puts("y is greater");

Program to print the largest of two numbers


#include<stdio.h>
main ()
{
int a, b; clrscr(); enter a and b
printf(“enter a and values 15
b values”); scanf 9
(“%d%d”,&a,&b); a is large
(a>b)? printf(“a is large”):printf(“b is large”);
getch();
}

Program to check whether the student is pass or fail


#include <stdio.h>
void main()
{
int mark; clrscr();
printf("Enter mark: ");
scanf("%d", &mark);
puts(mark>=40?"Pass":"Fail");
getch();
}

28
C programming
2024

Special operators in c: C provides the following special operators. sizeof()


operator, comma operator and arrow operator.

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);

A program to illustrate the sizeof () operator


#include<stdio.h>
#include<conio.h>
main ()
2
{
4
int a; float b;
1
char c;
clrscr();
printf(“%d\n, %d\n, %d\n”, sizeof(a),sizeof(b),sizeof(c));
getch();
}
C Expressions

Arithmetic Expressions

An expression is a combination of variables constants and operators written according to the


syntax of C language. In C every expression evaluates to a value i.e., every expression results in
some value of a certain type that can be assigned to a variable. Some examples of C expressions
are shown in the table given below.

Algebraic Expression C Expression


axb–c a*b–c
(m + n) (x + y) (m + n) * (x + y)
(ab / c) a*b/c
3x2 + 2x + 1 3*x*x+2*x+1
(x / y) + c x/y+c

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.

Example of evaluation statements are


29
C programming
2024
x=a*b–c
y=b/c*a
z = a – b / c + d;

Operator Precedence and Associativity:

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.

Operators Description Precedence Associatively


→ Indirect member operator Subscription 1 Left to Right
[] operator Function call
() Increment operator
++
~ Bit wise Not [1’scomplement] 2 Right to left
! Logical Not
+,- Unary plus, Unary Minus
* Multiplication 3 Left to Right
/ Division
% Reminder operator
+,- Addition and subtraction operators 4 Left to Right
<,<= , > Relational Operators 5 Left to Right
>=, ==, !=
&& Logical AND 6 Left to Right
|| Logical OR 7 Left to Right
?: Conditional Operator 8 Left to Right
= Assignment operator 9 Right to left
, Comma operator 10 Left to Right

*********

30
C programming
2024

31

You might also like