0% found this document useful (0 votes)
46 views38 pages

C Programming cs25c01

This document provides an introduction to computer programming in C, covering fundamental concepts such as problem-solving, algorithms, flowcharts, and pseudocode. It explains the characteristics and components of computers, the differences between low-level and high-level programming languages, and the role of Integrated Development Environments (IDEs) in software development. Practical examples and algorithms are included to illustrate the programming concepts discussed.

Uploaded by

yy385416
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
46 views38 pages

C Programming cs25c01

This document provides an introduction to computer programming in C, covering fundamental concepts such as problem-solving, algorithms, flowcharts, and pseudocode. It explains the characteristics and components of computers, the differences between low-level and high-level programming languages, and the role of Integrated Development Environments (IDEs) in software development. Practical examples and algorithms are included to illustrate the programming concepts discussed.

Uploaded by

yy385416
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 38

lOMoARcPSD|48469774

Computer programming -C -notes- Module-1

computer science (Anna University)

Scan to open on Studocu

Studocu is not sponsored or endorsed by any college or university


Downloaded by divya rani ([email protected])
lOMoARcPSD|48469774

CS25C01 Computer Programming: C

MODULE-1
Introduction to C: Problem Solving, Problem Analysis Chart, Developing an Algorithm,
Flowchart and Pseudocode, program structure, Compilation & Execution process, Interactive
and Script mode, Comments, Indentation, Error messages, Primitive data types, Constants,
Variables, Reserved words, Arithmetic, Relational, Logical, Bitwise, Assignment, Conditional
operators, Input/Output Functions, Built-in Functions.
Practical: Create Problem Analysis Charts, Flowcharts and Pseudocode for simple C programs
(Minimum three).

Define Computer:
Computer is a calculating machine, which accepts data through input device, processes it using
processing device and give the result through output device. Computer is an electro-
mechanical machine. It consists of electronic parts (IC‟S) electrical (motors, fan) and
Mechanical parts (Outer cover, keyboard).

Characteristics of Computer:
The following are the characteristics of a computer:
1. Speed: Computer can process the data at an extremely high speed.
2. Accuracy: Computer will produce accurate result.
3. Reliability: It is the measurement of performance of computer.
4. Versatile: Computer can be used for different purpose.
5. Storage capacity: computer can store large amount of data.

Block Diagram of a Computer:

Downloaded by divya rani ([email protected])


lOMoARcPSD|48469774

Computer has five fundamental units:


1. Input unit: Through which data will be fed into the computer

Example: Keyboard, Mouse, Microphone, Joystick, Web camera


Keyboard is the standard input unit.
2. Storage unit: It is used to store the data/ Information.
Two types:
(i) Primary Storage Unit / Primary Memory
Example: Random Access Memory (RAM)
(ii) Secondary Storage Unit/ Secondary Memory
Example: Hard Disk Drive (HDD)/ Solid State Device (SSD)
3. Control Unit: Controls all other units.
4. Arithmetic and Logical Unit: Does the computation.
Note: Control Unit and Arithmetic and Logical unit put together called as
Central Processing Unit or CPU. A single chip CPU is called Microprocessor.
5. Output Unit: Through which result will be displayed to the external world
Example: Monitor, Speaker, Projector, Printer
Monitor is the standard output unit.
Output generated using printer is called Hardcopy output.

Hardware: All the physical parts of the computer is called hardware. You can touch and feel.
Example: Keyboard, Mouse, outer cover, IC‟s
Software:Programs written for the computer is called software. Ex: MS-Word, C program,
Windows 10 OS
Operating System:It is the interface between user of the computer and computer hardware.
Text Editor: It is an application program which allows user to type text and edit it.

Computer Languages:
Machine Level Language (MLL) : Binary language it use 1 and 0. It is the only language
understood by the computer.
Assembly Level Language (ALL) : It uses short notations like add, sub, mul and div etc.
It cannot be understood by the computer. Hence ALL needs to be converted into MLL
Assembler: is the program, which converts ALL to MLL and vice versa.
Example for ALL: ALL 8085, ALL 8086

High Level Language (HLL) : It is English like language. It is easy to understand by the
programmer.
It cannot be understood by the computer.
HLL needs to be converted into MLL.
Compiler or Interpreter will be used to convert HLL to MLL and vice versa.
Compiler: converts HLL to MLL in one step.

Downloaded by divya rani ([email protected])


lOMoARcPSD|48469774

Interpreter: Converts HLL to MLL line by line.


Example: C,C++, Java

1.Problem solving
Problem solving in computer programming is the iterative process of understanding a problem,
devising a detailed step-by-step solution (an algorithm), and translating that solution into a
computer program. Key stages include defining and analyzing the problem to determine inputs
and outputs, developing an algorithm using natural language or flowcharts, coding the
algorithm into a programming language, and testing and debugging the program to ensure it
works correctly. This core skill allows programmers to break down complex issues into
manageable steps for a computer to execute.

Steps in the Problem-Solving Process


1. Understand and Define the Problem:
Clearly understand what needs to be solved by identifying the problem's requirements, inputs,
and expected outputs.
2. Analyze the Problem:
Break down the problem into smaller, more manageable parts to identify its principal
components and core functionalities.
3. Develop a Solution (Algorithm):
Create a step-by-step plan for the computer to follow. This is often done in natural language
(like pseudocode) or through visual aids like flowcharts.
4. Code the Solution:
Translate the algorithm into a specific programming language that the computer can
understand and execute.
5. Test and Debug:
Rigorously test the coded solution with various inputs to find and fix errors (bugs) to ensure
the program functions as intended.
6. Review and Refine:

Downloaded by divya rani ([email protected])


lOMoARcPSD|48469774

Evaluate the overall effectiveness of the solution and refine it for clarity, efficiency, and
completeness.

2.Problem Analysis Charts


A Problem Analysis Chart (PAC) is a structured tool used to break down a problem into key
components. It helps to systematically understand the problem, identify necessary data, and
develop a structured approach to solve it. In the context of algorithms and flowcharts, PACs
serve as the initial step in problem-solving by organising information that will be used to
visualise and implement the solution.
The PAC breaks the problem into smaller parts. It helps us to bring a logical sequence to our
thought process and help us arrive at better solutions.

How PACs, Algorithms, and Flowcharts Interrelate


PACs, algorithms, and flowcharts are interconnected in problem-solving:

 PACs provide a structured approach to analyse the problem by identifying inputs,


outputs, processes, and alternative solutions.
 Flowcharts visually represent the steps and decision points outlined in the PAC,
making it easier to understand and communicate the solution process.
 Algorithms are step-by-step procedures derived from the PAC and visualised through
flowcharts. They provide a logical sequence of operations to solve the problem.

By integrating PACs, algorithms, and flowcharts, we can systematically analyse problems,


visualise the solution process, and implement efficient solutions. This structured approach
enhances our problem-solving skills and ensures that solutions are well-organized, efficient,
and easy to understand. The interactive activity demonstrates how a simple algorithm can be
visualised and implemented, reinforcing the concepts of PACs and flowcharts in a practical
context.

3.Algorithm:It is the step-by-step procedure to solve a given problem. It will accept input,
processes and gives output. It is simple to represent and it is independent of programming
language.
Example:
I. Write an algorithm to exchange the contents of two variable.
1. [Start]

2. [Input two numbers]


Read(x,y)
3. [Process two swap two numbers]
t <- x
x <- y

Downloaded by divya rani ([email protected])


lOMoARcPSD|48469774

y <- t
4. [Output – to print the swapped numbers]
Write (x,y)
5. [Stop]

II. Write an algorithm to find the area of a triangle given base and height.
1. [Start]
2. [Input – Base and height of the triangle]
Read(b,h)
3. [Process – to compute the area of the triangle]
a <- 0.5*b*h
4. [Output the area]
Write (a)
5. [Stop]

III. Write an algorithm to find the area of a triangle given its 3 sides.
1. [Start]
2. [Input – 3 sides of the triangle]
Read(a,b,c)
3. [Process – to compute half perimeter]
s<- (a+b+c)/2.0
4. [Process to compute the area ]
a <- sqrt( s * (s-a) * (s-b) * (s-c) )
5. [Output the area]
Write (a)
6. [Stop]

IV. Write an algorithm to compute the area of a circle


1. [Start]
2. [Input – radius of the circle]
Read(r)
3. [Initialize]
p <- 3.14
4. [Process – to compute the area of the circle]
a <- (p * r *r)
5. [Output the area]
Write (a)
6. [Stop]

Downloaded by divya rani ([email protected])


lOMoARcPSD|48469774

V. Write an algorithm to check whether the given number is odd or even


1. [Start]
2. [Input a number]
Read(n)
3. [Compute the reminder]
r <- n modulo 2
4. [ process to check whether the given number is odd or even using reminder value]
If (r = 0)
Write (“Given number is Even”)
Else
Write (“Given number is Odd”)
5. [Stop]

VI. Write an algorithm to compute the sum of first ‘n’ natural numbers
1. [Start]
2. [Input a number]
Read(n)
3. [Initialize]
sum < - 0
4. [compute the sum of first „n‟ numbers ]
for i <- 1 to n step 1
sum <- sum + i
end for
5. [Display the sum]
Write(sum)
6. [Stop]
VII. Write an algorithm to compute the factorial of the given number

1. [Start]
2. [Input a number]
Read(n)
3. [Initialize]
fact < - 1
4. [compute the factorial of „n‟ ]
for i <- 1 to n step 1
fact <- fact* i
end for
5. [Display the sum]
Write(fact)
Downloaded by divya rani ([email protected])
lOMoARcPSD|48469774

6. [Stop]

4. Flow chart:
It is the pictorial representation of an algorithm. All the steps are drawn in the form of
different shapes. Commonly used symbols for flow chart are :

Write a flowchart to exchange contents of two variables:

Downloaded by divya rani ([email protected])


lOMoARcPSD|48469774

Write a flowchart to compute the area of a triangle

5. Pseudocode
Pseudocode is an informal, high-level description of an algorithm or program logic. It uses a
mix of natural language (like English) and common programming constructs to outline the
steps involved in a process, without adhering to the strict syntax rules of any specific
programming language.

Key characteristics of pseudocode:

 Human-readable:
It is designed for human understanding, not for execution by a computer.
 Language-independent:
It can be understood by programmers regardless of their preferred programming language.
 Focus on logic:
It emphasizes the sequence of operations and decision-making within an algorithm.
 Informal syntax:
While it often uses keywords like IF, ELSE, FOR, WHILE, PRINT, etc., it does not require
precise punctuation or grammar like actual code.

Downloaded by divya rani ([email protected])


lOMoARcPSD|48469774

 Indentation for structure:


Indentation is commonly used to show the hierarchical structure of control flow (e.g., within
loops or conditional statements).
Purpose of pseudocode:

 Algorithm design:
It helps in planning and structuring algorithms before writing actual code.
 Communication:
It facilitates communication and understanding of algorithms among developers, designers,
and project managers.
 Problem-solving:
It allows focusing on the logical steps to solve a problem without getting bogged down by
language-specific syntax.
 Documentation:
It can serve as a form of documentation for algorithms.

Example
START
DECLARE variable 'number'
GET input from user and STORE in 'number'

IF 'number' IS GREATER THAN 0 THEN


PRINT "The number is positive."
ELSE IF 'number' IS LESS THAN 0 THEN
PRINT "The number is negative."
ELSE
PRINT "The number is zero."
END IF
END

Difference between Flowchart and Pseudocode


Flowchart Pseudocode

A Pseudocode is a step-by-step
A Flowchart is pictorial representation of
description of an algorithm in code like
flow of an algorithm.
structure using plain English text.

Downloaded by divya rani ([email protected])


lOMoARcPSD|48469774

Flowchart Pseudocode

A Flowchart uses standard symbols for input,


output decisions and start stop statements. Pseudocode uses reserved keywords like
Only uses different shapes like box, circle if-else, for, while, etc.
and arrow.

This is a way of visually representing data, These are fake codes as the word pseudo
these are nothing but the graphical means fake, using code like structure but
representation of the algorithm for a better plain English text instead of programming
understanding of the code language

Pseudocode is better suited for the


Flowcharts are good for documentation
purpose of understanding

6. Introduction to C
C is a programming language developed at AT & T‟s Bell Laboratories of USA in 1972. It
was designed and written by a man named Dennis Ritchie. In the late seventies C began to
replace the more familiar languages of that time like PL/I, ALGOL, etc.

A computer program is just a collection of the instructions necessary to solve a specific


problem. The basic operations of a computer system form what is known as the computer‟s
instruction set. And the approach or method that is used to solve the problem is known as an
algorithm.

Downloaded by divya rani ([email protected])


lOMoARcPSD|48469774

So for as programming language concern these are of two types.


1) Low level language

2) High level language

Low level language:


Low level languages are machine level and assembly level language. In machine level
language computer only understand digital numbers i.e. in the form of 0 and 1. So, instruction
given to the computer is in the form binary digit, which is difficult to implement instruction in
binary code. This type of program is not portable, difficult to maintain and also error prone.
The assembly language is on other hand modified version of machine level language. Where
instructions are given in English like word as ADD, SUM, MOV etc. It is easy to write and
understand but not understand by the machine. So the translator used here is assembler to
translate into machine level.

High level language:


These languages are machine independent, means it is portable. The language in this
category is Pascal, Cobol, Fortran etc. High level languages are understood by the machine.
So it need to translate by the translator into machine level. A translator is software which is
used to translate high level language as well as low level language in to machine level
language. Three types of translator are there:
 Compiler

 Interpreter

 Assembler
Compiler and interpreter are used to convert the high level language into machine
level language. The program written in high level language is known as source program and
the corresponding machine level language program is called as object program. Both
compiler and interpreter perform the same task but there working is different. Compiler read
the program at-a-time and searches the error and lists them. If the program is error free then
it is converted into object program. When program size is large then compiler is preferred.
Whereas interpreter read only one line of the source code and convert it to object code. If it
check error, statement by statement and hence of take more time.

Integrated Development Environments (IDE)


The process of editing, compiling, running, and debugging programs is often managed by a
single integrated application known as an Integrated Development Environment, or IDE for
short. An IDE is a windows-based program that allows us to easily manage large software
programs, edit files in windows, and compile, link, run, and debug programs.

On Mac OS X, CodeWarrior and Xcode are two IDEs that are used by many programmers.
Under Windows, Microsoft Visual Studio is a good example of a popular IDE. Kylix is a

Downloaded by divya rani ([email protected])


lOMoARcPSD|48469774

popular IDE for developing applications under Linux. Most IDEs also support program
development in several different programming languages in addition to C, such as C# and
C++.

6.1 BASIC STRUCTURE OF A C PROGRAM


The basic structure of a C program is divided into 6 parts which makes it easy to read,
modify, document, and understand in a particular format. C program must follow the below-
mentioned outline in order to successfully compile and execute. Debugging is easier in a
well-structured C program.
Sections of the C Program
There are 6 basic sections responsible for the proper execution of a program. Sections are
mentioned below:
1. Documentation
2. Preprocessor Section
3. Definition
4. Global Declaration
5. Main() Function
6. Sub Programs

Example:

// Documentation
/**
* file: sum.c
* author: you
* description: program to find sum.
*/

// Link
#include <stdio.h>

// Definition
#define X 20

// Global Declaration
int sum(int y);

// Main() Function
int main(void)
{
int y = 55;
printf("Sum: %d", sum(y));
return 0;

Downloaded by divya rani ([email protected])


lOMoARcPSD|48469774

// Subprogram
int sum(int y)
{
return y + X;
}

7.Steps involved in the Compilation and execution of a C program:


 Program Creation
 Compilation of the program
 Execution of the program
 The output of the program

 The compilation is the process of converting the source code of the C language into
machine code. As C is a mid-level language, it needs a compiler to convert it into an
executable code so that the program can be run on our machine.
 The C program goes through the following phases during compilation:

Downloaded by divya rani ([email protected])


lOMoARcPSD|48469774

Working Process

7. Interactive and Script mode

 In the context of C programming, "interactive mode" and "script mode" refer to how
C programs are typically developed and executed, although the terminology is more
commonly associated with interpreted languages like Python.

Interactive Mode (for C):

 While C is a compiled language, elements of "interactive mode" can be experienced


during development through tools like debuggers or integrated development
environments (IDEs) with interactive features.

 In a C debugger, you can set breakpoints, step through code line by line, inspect
variable values, and even modify variables during runtime. This provides immediate
feedback on specific parts of your code.

 Debugging, testing small code snippets, understanding program flow, and exploring
variable states during execution.

Downloaded by divya rani ([email protected])


lOMoARcPSD|48469774

Script Mode (for C):


:
 This is the standard way to develop and run C programs. You write your entire
program in source code files (e.g., .c files).

 The C source code is compiled into an executable binary file using a C compiler (like
GCC). This executable is then run as a complete program.

 Developing full-fledged applications, creating reusable libraries, and deploying


production-ready software.

8. Comments
Comments in C programming are non-executable statements within the source code that are
ignored by the compiler. Their primary purpose is to provide explanations, documentation,
and notes for human readers of the code, improving readability and maintainability.

C supports two types of comments:


 Single-line comments:
o Syntax: // Your comment here
o These comments begin with two forward slashes (//) and extend to the end of the current
line. They are suitable for brief explanations of individual lines or small sections of code.
C
int x = 10; // Initialize variable x with value 10

 Multi-line comments (Block comments):


o Syntax: /* Your multi-line comment here */
o These comments begin with /* and end with */. They can span multiple lines and are
typically used for longer explanations, function descriptions, or for temporarily commenting
out blocks of code during development or debugging.

9. Indentation in C

Indentation in C programming refers to the use of whitespace, typically spaces or tabs, at


the beginning of lines of code to visually indicate the structure and hierarchy of the
program. While C compilers do not strictly enforce indentation for code execution (unlike
languages like Python where it is syntactically mandatory), it is crucial for code readability
and maintainability.

10.Errors Meassages
In C programming, "errors" refer to issues that prevent a program from compiling or
executing correctly. These errors can be categorized into several types:

Downloaded by divya rani ([email protected])


lOMoARcPSD|48469774

 Syntax Errors:
Occur when the code violates the grammatical rules of the C language.
Examples include missing semicolons, unbalanced brackets, or misspelled keywords.
Detected by the compiler during the compilation phase, preventing the creation of an
executable.
 Linker Errors:
Arise during the linking phase, when the linker attempts to combine object files and
libraries to create a final executable.
Occur if the linker cannot find the definitions for functions or variables that have been
declared in the code but not defined (e.g., missing library files).
 Runtime Errors:
Happen while the program is executing.
Often caused by illegal operations, such as division by zero, accessing invalid memory
locations, or attempting to open a non-existent file.
Can lead to program crashes or unexpected behavior.
 Logical Errors:
The program compiles and runs without crashing, but it produces incorrect or
unexpected output.
Result from flaws in the program's algorithm or logic, where the code does not correctly
implement the intended functionality.
 Compiler Warnings:
Not strictly errors, but indications of potential issues in the code that might lead to
problems later.
Examples include uninitialized variables or non-standard coding practices.
While warnings do not prevent compilation, it is best practice to address them to avoid
future errors.
 Preprocessor Errors:
Occur during the preprocessor stage, before compilation.
Can be caused by issues with preprocessor directives, such as incorrect use
of #include or inability to locate a referenced header file.
 Memory Errors:
A specific type of runtime error related to memory management.
Examples include memory leaks (failure to free dynamically allocated memory) or
attempting to access memory that has already been freed.

Downloaded by divya rani ([email protected])


lOMoARcPSD|48469774

11.C Tokens: Character set, Identifiers, Keywords, constants, Data types, type
qualifiers, Declaration and Initialization of variables.

Token: The smallest individual units in a program are called tokens. The „C‟

Tokens are classified as:

1. Character set
2. Keywords
3. Identifiers
4. Constants
5. Operators

Character set:

Character set consists of


i) alphabet from A-Z or a-z
ii) digits from 0-9
iii) Special characters like (,), {,}, [,], <, >, &, $, #, %, ^, !, ?, :, ;, ",', .
iv) White space character: blank space
v) Escape sequences:

\b backspace
\a audible bell
\v vertical tab
\t horizontal tab
\f form feed
\r carriage return
\” double quotes
\‟ single quotes
\\ back slash

\r is a carriage return character; it tells your terminal emulator to move the cursor at the
start of the line.
The cursor is the position where the next characters will be rendered.
So, printing a \r allows overriding the current line of the terminal emulator.

Example Program:

#include<stdio.h> main()
{

printf("Backspace Character\b");
Downloaded by divya rani ([email protected])
lOMoARcPSD|48469774

printf(" Audible Bell\a\n");


printf("Vertical Tab\vDemonstration\n");
printf("Horizental Tab\tDefault 8 spaces\n");
printf("Form feed\fIt is only with Printer\n");
printf("Carriage Return\rmove the cursor at the start of the line\n");
printf("Single Quotes The \"Sun\" rises in the \'east\'\n");
printf("Backslash \\hai\n");
}

Output:

Backspace Characte Audible Bell Vertical Tab


Demonstration Horizental Tab
Default 8 spaces Form feed
It is only with Printer
move the cursor at the start of the line
Double quotes and Single Quotes The "Sun" rises in the 'east' Backslash \hai

12.1 Keywords:

Keywords are reserved words. All keywords have fixed meanings. Keywords serve as
basic building blocks for program statements. In „C‟, there are 32 keywords. All
keywords must be written in lower case.

These 32 keywords are classified into 3 types namely

1. Type related Keywords (16)


2. Storage related Keywords (4)
3. Control flow related Keywords (12)

Type related Keywords:

int short void enum


float long struct const
char signed union volatile
double unsigned typedef sizeof

Storage related keywords:

auto static register extern

Downloaded by divya rani ([email protected])


lOMoARcPSD|48469774

Control flow related keywords:

if default goto for


else case continue while
switch break return do

12.2 Identifiers: Identifier refers to the names of the variables, functions and arrays.

Rules to name a particular identifier:

1. It must start with either alphabet or underscore.


2. Remaining letters may be alphabet, digit, underscore.
3. Identifier would not allow any special symbol except underscore.
4. An identifier can be of any length while most compilers of „C‟ language
recognize only the first 8 characters.
5. Do not use keywords as an identifier.

12.3 Constants:

Constants refer to fixed values that do not change during the execution of a program.

Constants are 2 types.


1. Numerical constants
2. Non-numerical constants

Numerical Constants are 2 types.


i. Integer constants
ii. Real constants

Non- Numerical Constants are 2 types.


i. Character constants
ii. String or multiple character constants

Integer constants:

An integer constant refers to a sequence of digits. There are three types of


integers, namely, decimal, octal and hexadecimal.

 Decimal integers consist of a set of digits, 0 through 9, preceded by an


optional – or + sign.
 Valid examples of decimal integer constants are: 321, -
789, 0, +77
 An octal integer constant consists of any combination of digits from the set

Downloaded by divya rani ([email protected])


lOMoARcPSD|48469774

0 through 7, with leading 0.


 Some examples of octal integers are 047, 0,
0543, 0655

 Hexadecimal integer constant consists of a sequence of digits preceded by


0x or 0X.
 They may also include alphabets A through F or a through f. (0 – 9
and A – F or a – f)
 Examples of hexadecimal integer constants are: 0X49,
0x8D

Real constants:

 Some quantities vary continuously, such as distances, heights, temperatures,


prices and so on.
 These quantities are represented by numbers containing fractional parts.
Such numbers are called real or floating point constants.
 A real constant is a sequence of digits with a decimal point.
 Examples of real constants are: 0.00876,
-0.456, 543.78, +247.0
 A real number may also be expressed in exponential or scientific notation.
 Example is:
The value 289.45 may be written as 2.8945e2 in exponential notation.
General form is:
mantissa e exponent
 The mantissa is either a real number expressed in decimal notation or an
integer.
 The exponent is an integer number with an optional plus or minus sign.
 The letter e is either in lowercase or uppercase.

Single Character constants (Character constant):

 A single character constant contains a single character (alphabet, digit,


special symbol, white space) enclosed within a pair of single quote marks.
 Examples are: '1', 'a', '
','@'

Note: Character constants have integer values known as ASCII values. Since each
character constant represent an integer value, so character arithmetic is possible.

Example Program:

#include<stdio.h> main()
{
char ch='a'; printf("ch=%c\n",ch);

Downloaded by divya rani ([email protected])


lOMoARcPSD|48469774

printf("ASCII value of \'%c\'=%d\n",ch,ch);


}

Output:
ch=a
ASCII value of 'a'=97
//Character Arithmetic
#include<stdio.h> main()
{

char ch='a'; printf("ch=%c\n",ch);


ch=ch+2;
printf("ASCII value of %c=%d\n",ch,ch);
}

Output:
ch=a
ASCII value of c=99

String constants (Multiple characters):

 String is a sequence of characters enclosed in double quotes.


 The characters may be an alphabet, digit, special symbol and white space.
 Each and every string ends with null character '\0'.
 Examples are:
"ab", "ab5", "@an", "6*7"

12.4 variables in C:
In C programming, a variable is a named storage location in memory used to hold
data. Variables are fundamental for storing and manipulating information during
program execution.

Key aspects of variables in C:


Declaration: Before a variable can be used, it must be declared. This involves specifying
its data type and a unique name. The data type determines the kind of data the variable
can store (e.g., int for integers, float for floating-point numbers, char for characters) and
the amount of memory it will occupy.

int age; // Declares an integer variable named 'age'


float price; // Declares a float variable named 'price'
char initial; // Declares a character variable named 'initial'

Downloaded by divya rani ([email protected])


lOMoARcPSD|48469774

Initialization: Variables can be assigned a value at the time of declaration or later in the
program.

int count = 10; // Declares and initializes 'count' to 10


float temperature;
temperature = 25.5; // Assigns a value to 'temperature' later

Naming Rules:
Variable names must follow specific rules:
They can contain letters (A-Z, a-z), digits (0-9), and underscores (\_).
They must begin with a letter or an underscore.
They are case-sensitive (e.g., myVar and myvar are different).
They cannot be C reserved keywords (e.g., int, float, if).
They cannot contain spaces or other special characters.
Scope and Lifetime:
Variables have a defined scope (where they are accessible in the code) and lifetime (how
long they exist in memory). Common types include:
Local variables: Declared inside a function, accessible only within that function,
and exist only while the function is executing.
Global variables: Declared outside any function, accessible throughout the entire
program, and exist for the program's entire execution.
Static variables: Retain their value between function calls.
Usage:
Once declared and potentially initialized, variables can be used in expressions,
assignments, function calls, and input/output operations.
Example:
int num1 = 5;
int num2 = 3;
int sum = num1 + num2; // Using variables in an expression
printf("Sum: %d\n", sum); // Displaying the variable's value
12.5 Data types:

Data type specifies which type of data that we are storing in a variable. There are 3 types
of data types.

1. Primary or primitive or fundamental data types


2. User defined data types
3. Derived data types
4. Empty data set

Downloaded by divya rani ([email protected])


lOMoARcPSD|48469774

Primary data types:

There four fundamental data types.

i. Integer
ii. Floating point
iii. Character
iv. Double precision floating point

Integer:

'C' provides three different classes of integers.


They are
a) int
b) short int
c) long int
The difference between these 3 integers is the number of bytes to occupy the range of
values.

Typ Bytes Bits Range


e
signed short int or 2 16 -32768 to 32767
short int
signed int or int 2/4 16/32 -32768 to 32767 or -2147483648 to
2147483647
signed long int or 4 32 -2147483648 to 2147483647
long int
unsigned short int 2 16 0 to 65535
unsigned int 2/4 16/32 0 to 65535 or 0 to 4294967295
unsigned long int 4 32 0 to 4294967295
Integers are whole numbers with a range of values supported by a particular machine.
Integers occupy one word of storage, and since the word sizes of machines vary
(typically 16 or 32 bits).

The size of an integer that can be stored depends on the computer.

Signed integer uses one bit for sign and 15 bits for the magnitude of the number.

Formula to find number of bits occupied by data type when number of bytes is known:
-2n-1 to 2n-1 - 1

Downloaded by divya rani ([email protected])


lOMoARcPSD|48469774

Floating point types:

Floating point or real numbers are stored in 32 bits (on all 16 bit and 32 bit machines)
with 6 bits precision.
3 classes of floating point types:
i. float
ii. double
iii. long double

Type Bytes Bits Range Precision


float 4 32 3.4E-38 to 3.4E+38 6 bits
double 8 64 1.7E-308 to 1.7E+308 14 bits
long double 12 96 3.4E-4932 to 1.1E+4932 19 bits

Character types:

A single character can be defined as a character type data.

Type Bytes Bits Range


signed char 1 8 -128 to 127
unsigned char 1 8 0 to 255

//Program to find number of bytes occupied by primary data types:

#include<stdio.h> main()
{

printf("signed char size=%d\n",sizeof(char)); printf("signed


short int size=%d\n",sizeof(short int)); printf("signed int
size=%d\n",sizeof(int)); printf("signed long int
size=%d\n",sizeof(long int));
printf("unsigned char size=%d\n",sizeof(unsigned char)); printf("unsigned
int size=%d\n",sizeof(unsigned int));
printf("unsigned short int size=%d\n",sizeof(unsigned short int)); printf("unsigned
long int size=%d\n",sizeof(unsigned long int)); printf("float
size=%d\n",sizeof(float));
printf("double size=%d\n",sizeof(double)); printf("long double
size=%d\n",sizeof(long double));
}
Output:

signed char size=1 signed short


int size=2 signed int size=4
signed long int size=4 unsigned
char size=1 unsigned int size=4
Downloaded by divya rani ([email protected])
lOMoARcPSD|48469774

unsigned short int size=2 unsigned


long int size=4 float size=4
double size=8
long double size=12

User defined data types:

 'C' supports a feature known as “type definition” that allows users to define an
identifier that would represent an existing data type.
 The user defined data type identifier can later be used to declare variables.

General form:

typedef type identifier

where type is any existing data type, identifier is a new name given to the data
type.

Examples: typedef int


units;
typedef float marks; units
u1,u2;
marks m1, m2;
 The main advantage of typedef is that we can create meaningful data type
names for increasing the readability of the program.
 typedef is mainly used in the concepts of structure and union.

Example program:
#include<stdio.h> int main()
{

typedef int units; typedef


float marks; units a,b;
marks x,y;
printf("Enter 2 values\n");
scanf("%d%d",&a,&b); printf("Enter 2
values\n"); scanf("%f%f",&x,&y);
printf("a=%d\tb=%d\n",a,b);
printf("x=%f\ty=%f\n",x,y);
}

Output:
Enter 2 values
5
Downloaded by divya rani ([email protected])
lOMoARcPSD|48469774

6
Enter 2 values
1.9
6.7
a=5 b=6
x=1.900000 y=6.700000

Enumerated data type provided by ANSI standard. It is defined as:

enum identifier {value1,value2,…,valuen};

 Where identifier is a user defined enumerated data type, which can be used to
declare variables which can have one of the values enclosed within the braces
(known as enumeration constants).
 After this definition, we can declare variables to be of this 'new' type.

enum identifier v1,v2,…,vn can only have one of the values value1, value2, …, valuen.
The assignments are:
v1=value3;
v5=value1;

Example:

enum day {Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday};


enum day weekst, weekend;
weekst=Monday; weekend=Thursday;

Example program:
#include<stdio.h> main()
{
enum day {Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday};
enum day weekst,weekend;
weekst=Monday;
weekend=Thursday;
printf("weekst=%d\nweekend=%d\n",weekst,weekend);
}

Output:
weekst=0
weekend=3

 The compiler automatically assigns integer digits from 0 to all enumerated


constants.
0 for value1,

Downloaded by divya rani ([email protected])


lOMoARcPSD|48469774

1 for value2,
2 for value3,
3 for value4,
4 for value5,
5 for value6,
6 for value7

 Automatic assignments can be overridden by using the following:

enum day {Monday, Tuesday=5, Wednesday, Thursday, Friday,


Saturday, Sunday};

Example program:
#include<stdio.h> main()
{

enum day {Monday, Tuesday=5, Wednesday, Thursday, Friday, Saturday,


Sunday};
enum day weekst,weekend;
weekst=Tuesday;
weekend=Thursday;
printf("weekst=%d\nweekend=%d\n",weekst,weekend);
}

Output:
weekst=5
weekend=7

 The definition and declaration can be combined in one statement as follows:

enum day {Monday, Tuesday, Wednesday, Thursday, Friday, Saturday} weekst,


weekend;

#include<stdio.h> main()
{

enum day { Monday, Tuesday=5, Wednesday,Thursday, Friday, Saturday}


weekst,weekend;
weekst=Tuesday; weekend=Thursday;
printf("weekst=%d\nweekend=%d\n",weekst,weekend);
}

Type qualifiers:

We can change the properties of primitive or fundamental data type. There are
two type qualifiers:
Downloaded by divya rani ([email protected])
lOMoARcPSD|48469774

i. const for constant


ii. volatile

const:

const is a new data type qualifier defined by ANSI standard

. Example: const int classsize=60;


This tells the compiler that the value of the int variable classsize must not be modified by
the program.

Example program:

1. #include<stdio.h>
2. main()
3. {
4. const int classsize=60;
5. printf("classsize=%d\n",classsize);
6. classsize=classsize*3;
7. printf("classsize=%d\n",classsize);
8. }
Note: The compiler gives an error at line number 6: assignment of read-onlyvariable 'a'.

volatile:

ANSI standard defines qualifier volatile that could be used tell explicitly the compiler that
a variable‟s value may be changed at any time by some external sources (from outside the
program).
Example:
volatile int a;
Example program:
#include<stdio.h>
main()
{
volatile int a=5;
printf("a=%d\n",a);
a=a*4;
printf("a=%d\n",a);
}
Output: a=5 a=20

13. Operator
Downloaded by divya rani ([email protected])
lOMoARcPSD|48469774

This is a symbol use to perform some operation on variables, operands or with the
constant. Some operator required 2 operand to perform operation or Some required
single operation.

Several operators are there those are, arithmetic operator, assignment, increment ,
decrement, logical, conditional, comma, size of , bitwise and others.

1. Arithmetic Operator

This operator used for numeric calculation. These are of either Unary arithmetic
operator, Binary arithmetic operator. Where Unary arithmetic operator required
only one operand such as +,-, ++, --,!, tiled. And these operators are addition,
subtraction, multiplication, division. Binary arithmetic operator on other hand
required two operand and its operators are +(addition), -(subtraction),
*(multiplication), /(division), %(modulus). But modulus cannot applied with
floating point operand as well as there are no exponent operator in c.
Unary (+) and Unary (-) is different from addition and subtraction.

When both the operand are integer then it is called integer arithmetic and the result is
always integer. When both the operand are floating point then it is called floating
arithmetic and when operand is of integer and floating point then it is called mix type
or mixed mode arithmetic . And the result is in float type.

2.Assignment Operator

A value can be stored in a variable with the use of assignment operator. The
assignment operator(=) is used in assignment statement and assignment expression.
Operand on the left hand side should be variable and the operand on the right hand
side should be variable or constant or any expression. When variable on the left hand
side is occur on the right hand side then we can avoid by writing the compound
statement. For example,
int x= y;

int Sum=x+y+z;

3.Increment and Decrement

The Unary operator ++, --, is used as increment and decrement which acts upon single
operand. Increment operator increases the value of variable by one

Downloaded by divya rani ([email protected])


lOMoARcPSD|48469774

.Similarly decrement operator decrease the value of the variable by one. And these
operator can only used with the variable, but cann't use with expression and constant
as ++6 or ++(x+y+z)
It again categories into prefix post fix . In the prefix the value of the variable is
incremented 1st, then the new value is used, where as in postfix the operator is written
after the operand(such as m++,m--).
EXAMPLE
let y=12; z=

++y; y= y+1;

z= y;

Similarly in the postfix increment and decrement operator is used in the operation . And
then increment and decrement is perform.
EXAMPLE
let x= 5; y=

x++; y=x;

x= x+1;
4.Relational Operator

It is use to compared value of two expressions depending on their relation. Expression


that contain relational operator is called relational expression.

Here the value is assign according to true or false value.


a.(a>=b) || (b>20)

b.(b>a) && (e>b)


c. (b!=7)

5. Conditional Operator

It sometimes called as ternary operator. Since it required three expressions as


operand and it is represented as (? , :).
SYNTAX

exp1 ? exp2 :exp3


Here exp1 is first evaluated. It is true then value return will be exp2 . If false then
exp3.
EXAMPLE

void main()
{
Downloaded by divya rani ([email protected])
lOMoARcPSD|48469774

int a=10, b=2

int s= (a>b) ? a:b; printf(“value

is:%d”);

}
Output:
Value is:10
6. Comma Operator
Comma operator is use to permit different expression to be appear in a situation where
only one expression would be used. All the expression are separator by comma and are
evaluated from left to right.
EXAMPLE

int i, j, k, l;
for(i=1,j=2;i<=5;j<=10;i++;j++)
7. Sizeof Operator
Size of operator is a Unary operator, which gives size of operand in terms of byte
that occupied in the memory. An operand may be variable, constant or data type
qualifier.

Generally it is used make portable program(program that can be run on different


machine) . It determines the length of entities, arrays and structures when their size are
not known to the programmer. It is also use to allocate size of memory dynamically
during execution of the program.
EXAMPLE
main( )
{
int sum; float f;

printf( "%d%d" ,size of(f), size of (sum) );


printf("%d%d", size of(235 L), size of(A));
}
8. Bitwise Operator
Bitwise operator permit programmer to access and manipulate of data at bit level.
Various bitwise operator enlisted are
one's complement (~)
bitwise AND (&)
bitwise OR (|)
bitwise XOR (^)
left shift (<<)
right shift (>>)
Downloaded by divya rani ([email protected])
lOMoARcPSD|48469774

These operator can operate on integer and character value but not on float and double.
In bitwise operator the function showbits( ) function is used to display the binary
representation of any integer or character value.

In one's complement all 0 changes to 1 and all 1 changes to 0. In the bitwise OR its
value would obtaining by 0 to 2 bits.
As the bitwise OR operator is used to set on a particular bit in a number. Bitwise
AND the logical AND.

It operate on 2operands and operands are compared on bit by bit basic. And hence both
the operands are of same type.

Logical or Boolean Operator

Operator used with one or more operand and return either value zero (for false) or one
(for true). The operand may be constant, variables or expressions. And the expression
that combines two r more expressions is termed as logical expression.
C has three logical operators :
Operator Meaning

&& AND
|| OR
! NOT
Where logical NOT is a unary operator and other two are binary operator. Logical
AND gives result true if both the conditions are true, otherwise result is false. And
logial OR gives result false if both the condition false, otherwise result is true.

14. Operator precedence and associativity


Operator precedence and associativity are rules that decide the order in which parts of an
expression are calculated. Precedence tells us which operators should be evaluated first,
while associativity determines the direction (left to right or right to left) in which
operators with the same precedence are evaluated.

Category Operator Associativity

Postfix () [] -> . ++ - - Left to right

Unary + - ! ~ ++ - - (type)* & sizeof Right to left

Multiplicative */% Left to right

Additive +- Left to right

Shift << >> Left to right

Downloaded by divya rani ([email protected])


lOMoARcPSD|48469774

Relational < <= > >= Left to right

Equality == != Left to right

Bitwise AND & Left to right

Bitwise XOR ^ Left to right

Bitwise OR | Left to right

Logical AND && Left to right

Logical OR || Left to right

Conditional ?: Right to left

Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left

Comma , Left to right

Within an expression, higher precedence operators will be evaluated first.

15.Input/Output Functions
C programming relies on a set of standard input/output (I/O) functions, primarily found in
the <stdio.h> header file, to interact with the user and external files. These functions facilitate
receiving data from input devices (like the keyboard) and displaying information to output
devices (like the monitor).

1. Console I/O Functions:


 printf(): This is a formatted output function used to display data on the console. It takes a
format string and a variable number of arguments, allowing for precise control over the
output's appearance using format specifiers (e.g., %d for integers, %f for floats, %s for
strings).

#include <stdio.h>
int main() {
int age = 30;
printf("Your age is: %d\n", age);
return 0;
}
 scanf(): This is a formatted input function used to read data from the console. It also uses a
format string to specify the expected data type and requires the address of the variable where
the input should be stored (using the & operator).

#include <stdio.h>
int main() {
Downloaded by divya rani ([email protected])
lOMoARcPSD|48469774

int num;
printf("Enter a number: ");
scanf("%d", &num);
printf("You entered: %d\n", num);
return 0;
}
 getchar(): Reads a single character from the standard input.
 putchar(): Writes a single character to the standard output.
 gets(): Reads a line of text (including spaces) from the standard input into a character
array. Note: gets() is considered unsafe due to potential buffer overflows and is generally
discouraged in favor of fgets().
 puts(): Writes a string to the standard output, followed by a newline character.

2. File I/O Functions:


These functions are used for reading from and writing to files.
 fopen(): Opens a file and returns a file pointer.
 fclose(): Closes an opened file.
 fprintf(): Writes formatted data to a file.
 fscanf(): Reads formatted data from a file.
 fgets(): Reads a line of text from a file.
 fputs(): Writes a string to a file.
 getc() / fgetc(): Reads a single character from a file.
 putc() / fputc(): Writes a single character to a file.

16. Built in functions in c


In C programming, the term "built-in functions" typically refers to the standard library
functions that are provided as part of the C language standard. These functions are not
inherently part of the core language syntax or keywords, but rather are pre-defined and pre-
compiled functions available for use by including specific header files.
Here is a list of some common Standard Library functions, categorized by their header file.
Input and output functions (<stdio.h>)
This library provides functions for handling input from the user and printing output to the
console.
 printf(): Prints formatted output to the console.
 scanf(): Reads formatted input from the console.

Downloaded by divya rani ([email protected])


lOMoARcPSD|48469774

 getchar(): Reads a single character from the standard input.


 putchar(): Writes a single character to the standard output.
 fgets(): Reads a string from a specified stream, such as a file or the console.
 fopen(): Opens a file.
 fclose(): Closes an open file.
Mathematical functions (<math.h>)
For mathematical operations, you must include the <math.h> header.
 sqrt(): Calculates the square root of a number.
 pow(): Returns the result of a number raised to a power.
 abs(): Returns the absolute value of a number (for integers, <stdlib.h> also has abs()).
 ceil(): Rounds a number up to the nearest integer.
 floor(): Rounds a number down to the nearest integer.
 sin(), cos(), tan(): Trigonometric functions.
 log(): Calculates the natural logarithm of a number.
String manipulation functions (<string.h>)
This header file contains functions for manipulating null-terminated strings.
 strcpy(): Copies one string to another.
 strcat(): Joins two strings together.
 strlen(): Calculates the length of a string.
 strcmp(): Compares two strings.
 strchr(): Finds the first occurrence of a character in a string.
 strstr(): Finds the first occurrence of a substring within another string.
Standard utility functions (<stdlib.h>)
The standard library provides many general-purpose functions in <stdlib.h>.
 malloc(): Dynamically allocates a block of memory.
 free(): Deallocates a block of memory previously allocated by malloc().
 exit(): Terminates the program normally.
 atoi(): Converts a string to an integer.
Character handling functions (<ctype.h>)
This library provides functions for testing and converting individual characters.
 isalpha(): Checks if a character is an alphabet letter.
 isdigit(): Checks if a character is a decimal digit.

Downloaded by divya rani ([email protected])


lOMoARcPSD|48469774

 isupper(): Checks if a character is an uppercase letter.


 islower(): Checks if a character is a lowercase letter.
 toupper(): Converts a character to uppercase.
 tolower(): Converts a character to lowercase.
Time and date functions (<time.h>)
For working with time and dates, include the <time.h> header.
 time(): Gets the current time.
 difftime(): Calculates the difference between two times.
 localtime(): Converts a time value into a structure for local time.

Practical: Create Problem Analysis Charts, Flowcharts and


Pseudocode for simple C programs (Minimum three).
Here are pseudocode examples for three simple C programs:
1. Program to Calculate the Sum of Two Numbers

START
DECLARE integer num1, num2, sum
DISPLAY "Enter first number: "
READ num1
DISPLAY "Enter second number: "
READ num2
CALCULATE sum = num1 + num2
DISPLAY "The sum is: ", sum
END
2. Program to Find the Larger of Two Numbers
START
DECLARE integer num1, num2
DISPLAY "Enter first number: "
READ num1
DISPLAY "Enter second number: "
READ num2
IF num1 > num2 THEN
DISPLAY num1, " is larger."
Downloaded by divya rani ([email protected])
lOMoARcPSD|48469774

ELSE IF num2 > num1 THEN


DISPLAY num2, " is larger."
ELSE
DISPLAY "Both numbers are equal."
END IF
END

3. Program to Check if a Number is Even or Odd


START
DECLARE integer number
DISPLAY "Enter an integer: "
READ number
IF number MOD 2 EQUALS 0 THEN
DISPLAY number, " is an even number."
ELSE
DISPLAY number, " is an odd number."
END IF
END

*************************************************************************

Downloaded by divya rani ([email protected])

You might also like