Pop Module1 (New)
Pop Module1 (New)
PRINCIPALS OF PROGRAMMING
(MVJ22POP13)
MODULE - 1
Introduction to C: Introduction to computers, input and output devices, designing efficient programs.
Introduction to C, Structure of C program, Files used in a C program, Compilers, Compiling and executing
C programs, variables, constants, Input/output statements in C
PRINCIPALS OF PROGRAMMING USING C (MVJ22POP13) MODULE – 1
INTRODUCTION TO C
INTRODUCTION TO COMPUTERS
COMPUTER
A computer is an electronic device that performs mathematical and logical operations based on a given set of
instructions.
DATA
Data is a collection of raw facts or figures.
INFORMATION
Information comprises of processed data to provide answers to ‘who’, ‘what’, ‘where’, and ‘when’ type of
questions.
KNOWLEDGE
Knowledge is the application of data and information to answer the ‘how’ part of the question.
INSTRUCTIONS
Instructions are the commands given to the computer which tell it what to do.
PROGRAM
Program is a set of instructions in a language understood by computers.
SOFTWARE
Software is a set of programs.
HARDWARE
Hardware refers to computer and all its physical parts.
CHARACTERISTICS OF COMPUTERS
Speed
Computers can process billions of instructions in a second. The speed of the computers is given in nanoseconds
and picoseconds, where 1 nanosecond = 1 x seconds and 1 picosecond = 1 x seconds.
PRINCIPALS OF PROGRAMMING USING C (MVJ22POP13) MODULE – 1
Accuracy
Computers are very fast, reliable and robust devices. Computers perform calculations with the same accuracy
and only produce incorrect outputs/erroneous if the input is incorrect, also known as Garbage-in, Garbage-out
(GIGO).
Automatic
Computers can carry out their jobs automatically once started, without human intervention.
Diligence
Computers can work continuously for years without getting tired or losing concentration.
Versatile
Computers can perform a variety of tasks, such as word processing, web browsing, gaming, and database
management.
Memory
Computers can store large amounts of data and recall any information when needed.
Computers have primary and secondary memory. Primary memory is very expensive and limited in size.
Secondary memory is cheaper and of bigger capacity.
No IQ
Computers do not have feelings or a sense of joy, love, success, or failure. Nowadays to make computers
intelligent we use artificial intelligence (AI) but they still do not have any decision-making abilities of their own.
Economical
Computers are short-term investments for achieving long-term goals. Using computers reduces manpower
requirements and leads to an economical and efficient way of performing various tasks.
GENERATIONS OF COMPUTERS
Speed – improvement of speed and reliability (in comparison with the first generation computers).
Input/output devices – punched cards and magnetic tape.
Examples – IBM 1401, IBM 7090 and 7094, UNIVAC 1107, etc.
Main electronic component: based on artificial intelligence, uses the Ultra Large-Scale Integration (ULSI)
technology and parallel processing method.
ULSI – millions of transistors on a single microchip
Parallel processing method – use two or more microprocessors to run tasks simultaneously.
Language – understand natural language (human language).
Power – consume less power and generate less heat.
Speed – remarkable improvement of speed, accuracy and reliability (in comparison with the fourth
generation computers).
Size – portable and small in size, and have a huge storage capacity.
Input / output device – keyboard, monitor, mouse, trackpad (or touchpad), touchscreen, pen, speech
input (recognise voice / speech), light scanner, printer, etc.
Example – desktops, laptops, tablets, smartphones, etc.
CLASSIFICATION OF COMPUTERS
Computers can be broadly classified into four categories based on size, cost, and speed into several types.
PRINCIPALS OF PROGRAMMING USING C (MVJ22POP13) MODULE – 1
1. Supercomputers
2. Mainframe computers
3. Minicomputers
4. Microcomputers
Here’s a breakdown:
1. Based on Size
Supercomputers:
Use: High-performance tasks like climate modeling, complex simulations, and scientific research.
Mainframe Computers:
Use: Processing large amounts of data for industries like banking and government.
Minicomputers:
Size: Medium-sized, smaller than mainframes but larger than personal computers.
Use: Used by small to medium-sized businesses for tasks like data processing.
Use: General-purpose tasks like word processing, internet browsing, and gaming.
2. Based on Cost
Supercomputers:
Mainframe Computers:
Minicomputers:
Microcomputers:
Cost: Low to moderate, usually from a few hundred to a few thousand dollars.
3. Based on Speed
Supercomputers:
Speed: Extremely high processing power, capable of performing trillions of calculations per second (FLOPS).
Mainframe Computers:
Speed: High, designed to handle large volumes of transactions and data processing efficiently.
PRINCIPALS OF PROGRAMMING USING C (MVJ22POP13) MODULE – 1
Minicomputers:
Speed: Moderate, suitable for many business applications but not as powerful as mainframes or supercomputers.
Microcomputers:
Speed: Varies widely; modern PCs can be quite fast but generally not as fast as larger systems.
APPLICATIONS OF COMPUTER
• Business
• Industry
• Home
• Education
• Printing & publishing
• Medical Diagnosis
• Railway
• Banking
• Defence setup
• Entertainment etc.
1. Input Unit
2. Output Unit
3. Central Processing Unit (CPU), and
4. Memory Unit.
The I/O unit consists of the input unit and the output unit. CPU performs calculations and processing on the input
data, to generate the output. The memory unit is used to store the data, the instructions and the output
information.
Input Unit:
The user interacts with the computer via the input and output unit.
The Input unit accepts data from the user.
The Input unit converts the data that it accepts from the user, into a form that is understandable by the
computer.
PRINCIPALS OF PROGRAMMING USING C (MVJ22POP13) MODULE – 1
The input is provided to the computer using input devices like keyboard, trackball and mouse.
Output Unit:
The Output unit provides the processed data i.e. the information to the user.
The Output unit provides the output in a form that is understandable by the user.
Some of the commonly used output devices are monitor and printer.
CPU controls, coordinates and supervises the operations of the computer, also known as the brain of the
computer. It is responsible for processing of the input data. CPU consists of:
Performs all the arithmetic and logic operations on the input data.
Arithmetic operations are addition, subtraction, multiplication, division etc. Also, doing some Logical
operations like AND, OR, NOT etc.
Control Unit:
It checks the sequence of execution of instructions, and, controls and coordinates the overall
functioning of the units of computer.
It also responsible for decoding the instruction given by the user.
Register Unit:
CPU also has a set of registers for temporary storage of data, instructions, addresses and
intermediate results of calculation.
This is some time called as chip memory. It consists of several high speed registers.
CPU uses this memory for its work.
Memory Unit:
Generally, during the processing of data Memory unit stores the data, instructions, intermediate results and
output temporarily.
i. Primary memory
ii. Secondary memory
Primary memory:
This memory is also called the main memory or primary memory of the computer.
The input data that is to be processed is brought into the main memory before processing.
The instructions required for processing of data and any intermediate results are also stored in the
main memory.
The output is stored in memory before being transferred to the output device.
CPU can work with the information stored in the main memory.
PRINCIPALS OF PROGRAMMING USING C (MVJ22POP13) MODULE – 1
The capacity of this memory is limited and they are volatile in nature.
ROM and RAM are examples of primary memory.
Secondary Memory:
Another kind of storage unit is also referred to as the secondary memory of the computer.
The data, the programs and the output are stored permanently in the storage unit of the computer.
The capacity of this memory is huge.
Magnetic disks, optical disks and magnetic tapes are examples of secondary memory.
INPUT DEVICES
1. Keyboard
A simple device comprising keys and each key denotes either an alphabet, number or number commands
which can be given to a computer for various actions to be performed
It has a modified version of typewriter keys
The keyboard is an essential input device and computer and laptops both use keyboards to give
commands to the computer
2. Mouse
3. Joy Stick
It is a device which comprises a stick which is attached at an angle to the base so that it can be moved and
controlled
Mostly used to control the movement in video games
Apart from a computer system, a joystick is also used in the cockpit of an aeroplane, wheelchairs, cranes,
trucks, etc. to operate them well
4. Light Pen
It is a wand-like looking device which can directly be moved over the device’s screen
It is light-sensitive
Used in conjunction with computer’s cathode ray tube
5. Microphone
6. Scanner
This device can scan images or text and convert it into a digital signal
When we place any piece of a document on a scanner, it converts it into a digital signal and displays it on
the computer screen
7. Barcode Reader
MICR input device is generally used in banks because of a large number of cheques to be processed every
day.
The bank's code number and cheque number are printed on the cheques with a special type of ink that
contains particles of magnetic material that are machine readable.
This reading process is called Magnetic Ink Character Recognition (MICR).
The main advantages of MICR are that it is fast and less error prone.
OUTPUT DEVICES
1. Monitor
The device which displays all the icons, text, images, etc. over a screen is called the Monitor
When we ask the computer to perform an action, the result of that action is displayed on the monitor
Various types of monitors have also been developed over the years
2. Printer
A device which makes a copy of the pictorial or textual content, usually over a paper is called a printer
For example, an author types the entire book on his/her computer and later gets a print out of it, which is
in the form of paper and is later published
Multiple types of printers are also available in the market, which can serve different purposes
3. Speakers
PRINCIPALS OF PROGRAMMING USING C (MVJ22POP13) MODULE – 1
A device through which we can listen to a sound as an outcome of what we command a computer to do is
called a speaker
Speakers are attached with a computer system and also are a hardware device which can be attached
separately
With the advancement in technology, speakers are now available which are wireless and can be
connected using BlueTooth or other applications
4. Projector
An optical device which presents an image or moving images onto a projection screen is called a projector
Most commonly these projectors are used in auditoriums and movie theatres for the display of the videos
or lighting
If a projector is connected to a computer, then the image/video displayed on the screen is the same as
the one displayed on the computer screen
5. Headphones
They perform the same function as a speaker, the only difference is the frequency of sound
Using speakers, the sound can be heard over a larger area and using headphones, the sound is only
audible to the person using them
Also known as earphones or headset.
PROGRAMMING PARADIGMS
The programming paradigm is a fundamental style of programming that defines how the structure and basic
elements of a computer program will be built.
The Monolithic programming paradigm is the oldest. It has the following characteristics. It is also known
as the imperative programming paradigm.
In this programming paradigm, the whole program is written in a single block.
We use the goto statement to jump from one statement to another statement.
It uses all data as global data which leads to data insecurity.
There are no flow control statements like if, switch, for, and while statements in this paradigm.
There is no concept of data types.
An example of a Monolithic programming paradigm is Assembly language.
The Structure-oriented programming paradigm is the advanced paradigm of the monolithic paradigm.
This paradigm introduces a modular programming concept where a larger program is divided into smaller
modules.
It provides the concept of code reusability.
PRINCIPALS OF PROGRAMMING USING C (MVJ22POP13) MODULE – 1
1. Requirement Analysis
This phase includes tasks like cost-benefit analysis, scheduling, resource estimation, and allocation. The
development team collects requirements from several stakeholders such as customers, internal and external
experts, and managers to create a requirement specification document.
The document sets expectations and defines common goals that aid in project planning. The team estimates
costs, creates a schedule, and has a detailed plan to achieve their goals.
2. Design
In the design phase, software engineers analyze requirements and identify the best solutions to create the
software. For example, they may consider integrating pre-existing modules, make technology choices, and
identify development tools. They will look at how to best integrate the new software into any existing IT
infrastructure the organization may have.
3. Implementation
In the implementation phase, the development team codes the product. They analyze the requirements to
identify smaller coding tasks they can do daily to achieve the final result.
4. Testing
The development team combines automation and manual testing to check the software for bugs. Quality analysis
includes testing the software for errors and checking if it meets customer requirements. Because many teams
immediately test the code they write, the testing phase often runs parallel to the development phase.
When teams develop software, they code and test on a different copy of the software than the one that the users
have access to. The software that customers use is called production, while other copies are said to be in the build
environment, or testing environment.
PRINCIPALS OF PROGRAMMING USING C (MVJ22POP13) MODULE – 1
6. Maintenance
In the maintenance phase, among other tasks, the team fixes bugs, resolves customer issues, and manages
software changes. In addition, the team monitors overall system performance, security, and user experience to
identify new ways to improve the existing software.
ALGORITHM
Algorithm is a step-by-step procedure, which defines a set of instructions to be executed in a certain order to get
the desired output.
Characteristics of Algorithm:
Unambiguous − Algorithm should be clear and unambiguous. Each of its steps (or phases), and their
inputs/outputs should be clear and must lead to only one meaning.
Output − An algorithm should have 1 or more well-defined outputs, and should match the desired output.
Independent − An algorithm should have step-by-step directions, which should be independent of any
programming code.
Example 1 − Write an algorithm to add two numbers and display the result.
Program:
#include<stdio.h>
int main()
{
int a, b, c;
printf(“Enter the value for a: ”);
scanf(“%d”, &a);
printf(“Enter the value for b: “);
scanf(“%d”, &b);
c = a + b;
printf(“Addition of two numbers = %d”, c);
return 0;
}
Algorithm:
Step 1: Start
Step 2: Read the values of a & b
Step 3: Compute c = a + b
Step 4: Display c
Step 5: Stop
Program:
#include<stdio.h>
int main()
{
int x, y;
printf(“Enter the values for x and y”);
scanf(“%d%d”, &x, &y);
if(x<y)
{
printf(“y is greater”);
}
else
{
printf(“x is greater”);
}
return 0;
}
Algorithm:
Step 1: Start
Step 2: Read values of x and y
Step 3: if x<y print “y is greater”, then goto step 5.
Step 4: print “x is greater”, then goto step 5.
Step 5: Stop
FLOWCHART
Flowchart in C is a diagrammatic representation of a sequence of logical steps of a program.
PRINCIPALS OF PROGRAMMING USING C (MVJ22POP13) MODULE – 1
Example 1 – Draw a flowchart to add two numbers and display the result.
PSEUDOCODE
pseudocode is a method of describing the algorithm using a combination of natural language (English like words)
and programming language.
This is essentially an intermediate step towards the development of the actual code.
Although pseudocode is frequently used, there are no set of rules for its exact writing.
Examples:
Problem 1: Write a pseudocode to add two numbers and display result to the user.
1. Read a,b
PRINCIPALS OF PROGRAMMING USING C (MVJ22POP13) MODULE – 1
2. Find c = a + b
3. Display c
Problem 2: Write a pseudocode to take marks as the input and display message passed or failed based on the
marks.
1. Read marks
2. If student’s marks is greater than or equal to 35
print “passed”
else
print “failed”
endif
TYPES OF ERRORS
In any programming language errors are common. Errors can be classified as:
1. Run-time Errors
2. Compile-time Errors
i. Syntax Errors
ii. Semantic Errors
3. Logical Errors
4. Linked Errors
1. Run-time Error
This type of error occurs while the program is running. Because this is not a compilation error, the compilation
will be completed successfully. These errors occur due to
2. Compile-time Error
Compile-time errors occur when a program's code is built but fails to compile due to syntax issues.
i. Syntax Error
These errors have occurred when the rule of C writing techniques or syntaxes has been broken. These types of
errors are typically flagged by the compiler prior to compilation.
Even if the syntax and other factors are correct, we may not get the desired results due to logical issues. These
are referred to as logical errors. We sometimes put a semicolon after a loop, which is syntactically correct but
results in one blank loop. In that case, it will display the desired output.
PRINCIPALS OF PROGRAMMING USING C (MVJ22POP13) MODULE – 1
3. Logical Error
Even if the syntax and other factors are correct, we may not get the desired results due to logical issues. These
are referred to as logical errors. We sometimes put a semicolon after a loop, which is syntactically correct but
results in one blank loop. In that case, it will display the desired output.
4. Linked Error
Even if the syntax and other factors are correct, we may not get the desired results due to logical issues. These
are referred to as logical errors. We sometimes put a semicolon after a loop, which is syntactically correct but
results in one blank loop. In that case, it will display the desired output.
1. Unit Testing - Unit testing is a method of testing software where individual software components are
isolated and tested for correctness.
2. Integration Testing - Integration testing is the process of testing the interface between two software
units or modules. It focuses on determining the correctness of the interface. The purpose of integration
testing is to expose faults in the interaction between integrated units.
3. System Testing - System testing is a type of software testing that evaluates the overall functionality and
performance of a complete and fully integrated software solution. It tests if the system meets the
specified requirements and if it is suitable for delivery to the end-users.
Debugging is the process using which we correct the bugs that we found during the testing process.
1. Brute force method - Brute force debugging is a systematic method for identifying the source of a
problem in a software program by manually searching through the code base line by line.
2. Backtracking - Backtracking is a debugging technique that involves working backward from the point of
an error to identify the exact line of code where it occurred.
3. Cause Elimination - The cause elimination method is a debugging technique that involves creating and
testing hypotheses about the cause of a bug in software.
INTRODUCTION TO C
HISTORY OF C
C programming language was developed in 1972 by Dennis Ritchie at bell laboratories of AT&T (American
Telephone & Telegraph), located in the U.S.A.
C language was developed to be used in UNIX operating system. It inherits many features of previous languages
such as B and BCPL.
C was invented specifically to implement UNIX. C instructions are compiled to assembly code, therefore,
depending on the complexity of the code and on the compiler optimization capabilities, C code may run as fast as
assembly.
Ken Thompson created the B language in 1969 from Martin Richard's BCPL (Basic Combined Programming
Language). He used assembly language and B to produce the initial versions of the UNIX operating system.
BCPL and B were type-less languages in which variables were simply words in memory.
Dennis Ritchie of Bell Laboratories later converted B into C by retaining most of B's syntax in 1972 and wrote the
first compiler. This was implemented on DEC's PDP 11 and it was first used as the system's language for rewriting
the UNIX operating system.
PRINCIPALS OF PROGRAMMING USING C (MVJ22POP13) MODULE – 1
STRUCTURE OF A C PROGRAM
1. Documentation section
2. Linking section
The link section provides instruction to the compiler to link the header files or functions from the system library.
Eg:
#include<stdio.h>
PRINCIPALS OF PROGRAMMING USING C (MVJ22POP13) MODULE – 1
3. Definition section
The definition section defines all symbolic constants such by using the #define directive.
Eg:
#define PI=3.14159
There are some variables that are used in more than one function, such variables are called global variables.
In C there are two types of variable declaration,
Local variable declaration: Variables that are declared inside the main function.
Global variable declaration: Variables that are declared outside the main function.
Eg:
// First Program
int main()
{
int a;
int a = 7;
printf(“%d”, a);
return 0;
}
The output obtained in the C language will be:
redeclaration of ‘a’ with no linkage
// Second Program
int a;
int a = 7;
int main()
{
printf(“%d”, a);
return 0;
}
These files contain function definitions, and the entire program logics, these files are human readable and by
convention their names end with .c
2. Header Files
These files contain function prototypes and various pre-processor statements. They are used to allow source code
files to access externally-defined functions and by convention their names end with .h.
3. Object Files
These files are produced as the output of the compiler. They consist of function definitions in binary form, but
they are not executable by themselves and by convention their names end with .o/.obj
These files are produced as the output of a program called a “linker“. The linker links together a number of object
files to produce a binary file that can be directly executed. It contains symbols that the linker can extract from the
archive and insert into an executable as it is being built. And by convention their names end with .exe in windows.
PRINCIPALS OF PROGRAMMING USING C (MVJ22POP13) MODULE – 1
The compilation process in C is converting an understandable human code into a Machine understandable code
and checking the syntax and semantics of the code to determine any syntax errors or warnings present in our C
program.
Suppose we want to execute our C Program written in an IDE (Integrated Development Environment). In that
case, it has to go through several phases of compilation (translation) to become an executable file that a machine
can understand.
1. Preprocessing
2. Compiling
3. Assembling
4. Linking
1. Pre-Processing
Pre-processing is the first step in the compilation process in C performed using the pre-processor tool (A pre-
written program invoked by the system during the compilation). All the statements starting with the # symbol in a
C program are processed by the pre-processor, and it converts our program file into an intermediate file with no #
statements. Under following pre-processing tasks are performed :
i. Comments Removal
PRINCIPALS OF PROGRAMMING USING C (MVJ22POP13) MODULE – 1
Comments in a C Program are used to give a general idea about a particular statement or part of code actually,
comments are the part of code that is removed during the compilation process by the pre-processor as they are
not of particular use for the machine. The comments in the below program will be removed from the program
when the pre-processing phase completes.
/* This is a
multi-line comment in C */
#include<stdio.h>
int main()
{
// this is a single-line comment in C
return 0;
}
Macros are some constant values or expressions defined using the #define directives in C Language. A macro call
leads to the macro expansion. The pre-processor creates an intermediate file where some pre-written assembly
level instructions replace the defined expressions or constants (basically matching tokens). To differentiate
between the original instructions and the assembly instructions resulting from the macros expansion, a '+' sign is
added to every macros expanded statement.
E.g.:
Defining a value:
#define G 9.8
Defining an expression:
#define SUM(a,b) (a + b)
File inclusion in C language is the addition of another file containing some pre-written code into our C Program
during the pre-processing. It is done using the #include directive. File inclusion during pre-processing causes the
entire content of filename to be added to the source code, replacing the #include<filename> directive, creating a
new intermediate file.
E.g.: If we have to use basic input/output functions like printf() and scanf() in our C program, we have to include a
pre-defined standard input output header file i.e. stdio.h.
#include <stdio.h>
Conditional compilation is running or avoiding a block of code after checking if a macro is defined or not (a
constant value or an expression defined using #define). The preprocessor replaces all the conditional compilation
directives with some pre-defined assembly code and passes a newly expanded file to the compiler. Conditional
compilation can be performed using commands like #ifdef, #endif, #ifndef, #if, #else and #elif in a C Program.
PRINCIPALS OF PROGRAMMING USING C (MVJ22POP13) MODULE – 1
A pre-processor converts our source code file into an intermediate file. Intermediate file has an extension of .i,
and it is the expanded form of our C program containing all the content of header files, macros expansion, and
conditional compilation.
2. Compiling
Compiling phase in C uses an inbuilt compiler software to convert the intermediate (.i) file into an Assembly file
(.s) having assembly level instructions (low-level code). To boost the performance of the program C compiler
translates the intermediate file to make an assembly file.
Assembly code is a simple English-type language used to write low-level instructions (in micro-controller
programs, we use assembly language). The whole program code is parsed (syntax analysis) by the compiler
software in one go, and it tells us about any syntax errors or warnings present in the source code through the
terminal window.
3. Assembling
Assembly level code (.s file) is converted into a machine-understandable code (in binary/hexadecimal form) using
an assembler. Assembler is a pre-written program that translates assembly code into machine code. It takes basic
instructions from an assembly code file and converts them into binary/hexadecimal code specific to the machine
type known as the object code.
The file generated has the same name as the assembly file and is known as an object file with an extension of .obj
in DOS and .o in UNIX OS.
An assembly file area.s is translated to an object file area.o having the same name but a different extension.
PRINCIPALS OF PROGRAMMING USING C (MVJ22POP13) MODULE – 1
4. Linking
Linking is a process of including the library files into our program. Library Files are some predefined files that
contain the definition of the functions in the machine language and these files have an extension of .lib. Some
unknown statements are written in the object (.o/.obj) file that our operating system can't understand. You can
understand this as a book having some words that you don't know, and you will use a dictionary to find the
meaning of those words. Similarly, we use Library Files to give meaning to some unknown statements from our
object file. The linking process generates an executable file with an extension of .exe in DOS and .out in UNIX OS.
Here, we have an object file having machine-level code, it is passed through the linker which links the library files
with the object file to generate an executable file.
VARIABLES
Since variables are a part of identifiers, they follow the same naming conventions. Like identifiers, a valid variable
name can start with an alphabet or an underscore ( _ ) and later have a combination of one or more letters, digits,
and underscores.
Declaration of variables
Syntax:
data_type variable_name;
PRINCIPALS OF PROGRAMMING USING C (MVJ22POP13) MODULE – 1
Example: int a;
int x, y, z;
char flat, ch;
Assigning Values to variables
Syntax:
A local variable is declared inside a function. A local variable is visible only inside their function, only statements
inside a function can access that local variable.
Local variables are declared when the function execution started and local variables get destroyed when the
control exits from the function.
Eg: #include<stdio.h>
int main()
{
int a=10, b=30;
…....
}
Global variables:
Global variables are declared outside of any function. A global variable is visible to every function and can be used
by any piece of code. Unlike local variables, global variables retain their values between function calls and
throughout the program execution.
Eg: #include<stdio.h>
int a=10, b=20;
int main()
{
…….
}
CONSTANT
A constant is basically a named memory location in a program that holds a single value throughout the execution
of that program. It can be of any data type- character, floating-point, string and double, integer, etc. The values
assigned to the variables are known as the literal.
For example,
//Global constant
#include<stdio.h>
const double PI =3.14 ;
int main()
{
double r, area;
printf(“Enter the value for radius”);
scanf(“%lf”, &r);
area = PI*r*r;
printf(“Area of a circle=%lf”,area);
}
Initializing PI value again to 2.9 will raise error, as once constant variable is initialized its value remains the same
throughout the execution of the program.
//Local Constant
#include<stdio.h>
int main()
{
const int A; //const int A=20;
A=20;
A=30;
printf(“A=%d”,A);
}
#include<stdio.h>
#define PI 3.14;
PRINCIPALS OF PROGRAMMING USING C (MVJ22POP13) MODULE – 1
int main()
{
double r, area;
printf(“Enter the value for radius”);
scanf(“%lf”, &r);
area = PI*r*r;
printf(“Area of a circle=%lf”,area);
}
Integer constants
An integer constant can be a decimal integer or octal integer or hexadecimal integer. A decimal integer value is
specified as direct integer value whereas octal integer value is prefixed with 'o' and hexadecimal value is prefixed
with 'OX'.
An integer constant can also be unsigned type of integer constant or long type of integer constant. Unsigned
integer constant value is suffixed with 'u' and long integer constant value is suffixed with 'l' whereas unsigned
long integer constant value is suffixed with 'ul'.
Example
Example
The floating-point value 3.14 is represented as 3E-14 in exponent form.
Character Constants
A character constant is a symbol enclosed in single quotation. A character constant has a maximum length of one
character.
Example
'A'
'2'
'+'
In the C programming language, there are some predefined character constants called escape sequences. Every
escape sequence has its own special functionality and every escape sequence is prefixed with '\' symbol. These
escape sequences are used in output function called 'printf()'.
String Constants
A string constant is a collection of characters, digits, special symbols and escape sequences that are enclosed in
double quotations.
We define string constant in a single line as follows...
"This is my first c programming class."
PRINCIPALS OF PROGRAMMING USING C (MVJ22POP13) MODULE – 1
We can also define string constant by separating it with white space as follows...
"This" "is" "my" “first” “c” “programming” “class.”
INPUT/OUTPUT STATEMENTS IN C
C language has standard libraries that allow input and output in a program.
The stdio.h or standard input output library in C that has methods for input and output.
Input function:
The input functions are used to read the data from the keyboard and store in memory-location.
Eg:
scanf(), getchar(), getch(), getche(), gets()
Output function:
The output functions are used to resolve the data from memory-locations and display on the screen.
Eg:
printf(), putchar(), putch(), puts()
Types of Input/Output
UNFORMATTED INPUT/OUTPUT
getchar is used to read a character from the keyboard and store this character into a memory-location.
Syntax:
char variable_name = getchar();
PRINCIPALS OF PROGRAMMING USING C (MVJ22POP13) MODULE – 1
Eg:
#include <stdio.h>
int main( )
{
int c;
printf("Enter a character");
// Take a character as input and store it in variable c
c = getchar();
//display the character stored in variable c
putchar(c);
}
Eg:
#include <stdio.h>
int main( )
{
int c;
printf("Enter a character");
c = getch();
putch(c); //same as printf(“%c”, c)
}
Output:
m //m is not visible
m
getche()
getche() is used to read a character from the keyboard with typed character visible on the screen. The character
thus entered will be stored in the memory-location.
Eg:
#include <stdio.h>
int main( )
{
int c;
printf("Enter a character");
c = getche();
putch(c); //same as printf(“%c”, c)
}
Output:
m //m is visible
m
PRINCIPALS OF PROGRAMMING USING C (MVJ22POP13) MODULE – 1
Eg:
#include <stdio.h>
int main( )
{
char string[20];
printf("Enter a string");
gets(string);
puts(string); //same as printf(“%s”,string)
}
Output:
Enter a string MVJCE
MVJCE
Disadvantage of unformatted I/O
It is not possible to read/print any other data except characters i.e. it is not possible to read/print integer
numbers, floating point numbers etc.
FORMATTED INPUT/OUTPUT
scanf()
The scanf() reads all types of data values given by the user and these values are assigned to the variables.
It requires the conversion specification (such as %s and %d ) to identify the type of data to be read during the
program execution.
We need to pass the address of the variable to the scanf function along with other arguments so that the read
values can be assigned to the correct destination.
scanf() reads the characters from standard input and interprets them according to the format string specification.
It stops reading when it encounters a space or when some input fails to match with the conversion specification.
C program to take Integer value input.
Example 1:
#include <stdio.h>
int main() {
int a;
printf("Please enter a number: ");
scanf("%d", &a);
printf("You entered: %d", a);
}
Example2:
C program to take float value input.
#include <stdio.h>
int main() {
float user_input;
printf("Please enter a decimal number: ");
scanf("%f", &user_input);
PRINCIPALS OF PROGRAMMING USING C (MVJ22POP13) MODULE – 1
Example 3:
Program to take character input value.
#include <stdio.h>
int main() {
char gender;
printf("Please enter your gender (M, F or O): ");
scanf("%c", &gender);
printf("Your gender: %c", gender);
}
KEY CONCEPTS IN C
Format Specifiers
To print values of different datatypes using the printf() statement, we need to use format specifiers.
When we take input from user using the scanf() function, then also, we have to specify what type of input to
expect from the user using these format specifiers.
Datatypes in C
Character Set
The character set refers to a set of all the valid characters that we can use in the source program for forming
words, expressions, and numbers.
They include digits, alphabets, special symbols, etc. The C language provides support for about 256 characters.
PRINCIPALS OF PROGRAMMING USING C (MVJ22POP13) MODULE – 1
Tokens in C
1. Keywords
2. Identifiers
3. Strings
4. Operators
5. Constant
6. Special Characters
KEYWORDS
Keywords are predefined or reserved words that have special meanings to the compiler. These are part of the
syntax and cannot be used as identifiers in the program.
A list of keywords in C or reserved words in the C programming language are mentioned below:
int main()
int signifies that the function returns an integer to the operating system upon completion. This return value is
often used to indicate whether the program executed successfully or if there was an error. A return value of 0 or
EXIT_SUCCESS typically signifies successful completion, while any non-zero value (often EXIT_FAILURE) indicates
an error.
PRINCIPALS OF PROGRAMMING USING C (MVJ22POP13) MODULE – 1
It returns an integer.
It is standard and portable.
It can be called with any number of arguments.
It can take argc and argv arguments.
void main()
The main function does not return a value.
It is non-standard and risky.
It can take void as an argument.
While some compilers might accept void main for certain types of applications (especially embedded systems
where returning a value to an operating system is not required)
It is not standard in ISO C or C++, and its use is generally discouraged.
int main(void)
int main(void) can only be called without any argument.