0% found this document useful (0 votes)
77 views27 pages

ICP Module 1 PDF

The document outlines the syllabus for the 'Introduction to C Programming' course at RajaRajeswari College of Engineering, detailing its structure, content, and evaluation methods. It covers fundamental concepts of computing, computer systems, programming languages, and the C language's history and features. The course aims to equip students with essential programming skills and knowledge applicable across various branches of engineering.

Uploaded by

hema
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)
77 views27 pages

ICP Module 1 PDF

The document outlines the syllabus for the 'Introduction to C Programming' course at RajaRajeswari College of Engineering, detailing its structure, content, and evaluation methods. It covers fundamental concepts of computing, computer systems, programming languages, and the C language's history and features. The course aims to equip students with essential programming skills and knowledge applicable across various branches of engineering.

Uploaded by

hema
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/ 27

Introduction to C programming B24ESCK245

RajaRajeswari College of Engineering

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

Ms. Thilagavalli S, Assistant Professor

Subject Name: “Introduction to C programming”

Subject Code:”B24ESCK245”

“Module-1”

Semester: I

BRANCH: ECE

Semester II
Introduction to C Programming
Category: ESC-II
Common to All Branches except CSE allied branches
(Integrated)
Course Code : B24ESCK245 CIE : 50 Marks
Teaching Hours L : T : P : 2:0:2 SEE : 50 Marks
Total Hours : 50 Total : 100 Marks
Credits 3 SEE Duration : 3 Hrs

Module - 1 No. of
Hrs
Introduction to Computing: Computer Systems-Hardware and Software, Computer Languages,
Algorithm, Flowchart, Representation of Algorithm and Flowchart with examples. Introduction to 08
C–History of C, Features of C, Structure of C Program, Character Set, C Tokens-Keywords,
Identifiers, Constants, Variables, Data types, Input/output statements in C, Types of errors.

1
Introduction to C programming B24ESCK245

1. Introduction to Computing

Computing involves using computer systems to process data, perform calculations, and execute
programs. The essential components of a computer system are:

 Hardware: Physical components of the system.


 Software: Programs or instructions that tell the hardware what to do.

1.1. Computer Systems

A. Hardware

Hardware refers to all the physical components that make up a computer system. Key hardware
components include:

1. Central Processing Unit (CPU):


The CPU is the "brain" of the computer. It performs the main processing tasks such as
arithmetic and logic operations, as well as managing the flow of data within the system.
2. Memory (RAM):
Memory is temporary storage used by the CPU to store data while executing programs. RAM
(Random Access Memory) is fast but volatile, meaning it loses data when the computer is
turned off.
ROM (Read-Only Memory):
ROM is a type of memory that is non-volatile, meaning it retains data even when the computer
is turned off. Unlike RAM, the data stored in ROM cannot be easily modified or written to
under normal operating conditions.
3. Storage Devices:
These devices store data permanently. Examples include:
o Hard Drive (HDD)
o Solid-State Drive (SSD)
4. Input Devices:
Input devices allow users to provide data or commands to the computer. Examples include the
keyboard, mouse, and microphone.
5. Output Devices:
Output devices allow the computer to display or produce results. Examples include monitors,
printers, and speakers.
6. Motherboard:
The motherboard connects all hardware components and allows them to communicate.
7. Power Supply:
Supplies the necessary electrical power for all components.

2
Introduction to C programming B24ESCK245

Diagram: Basic Computer System Architecture

B. Software

Software is a collection of programs and data that instruct the hardware on how to operate and perform
specific tasks. There are two primary types of software:

i. System Software

 Operating System (OS):


The OS manages hardware resources and provides a platform for running application software.
Examples include:
o Windows
o Linux
o macOS
 Utility Software:
These programs help manage, maintain, and protect the computer system. Examples include
antivirus software, disk management tools, and file compression utilities.

ii. Application Software

Application software allows users to perform specific tasks. Examples include:

 Word Processors (e.g., Microsoft Word)


 Spreadsheets (e.g., Microsoft Excel)
 Web Browsers (e.g., Google Chrome)
 Games
 Media Players

C. Interaction Between Hardware and Software

 Device Drivers:
Software programs that allow the operating system to communicate with hardware devices
(e.g., printer drivers, graphics card drivers).
 System Calls:
Mechanisms for programs to interact with the operating system to request services like memory
allocation, file manipulation, or hardware access.

3
Introduction to C programming B24ESCK245

1.2. Computer Languages:

Computer languages are used to write software programs. They can be classified based on their level of
abstraction from machine code.

Low-Level Language:

 Definition: Low-level languages communicate directly with the hardware using machine code,
consisting of binary digits (0 and 1).
 Purpose: Operates, manages, and manipulates hardware and system components.
 Types:
o Machine Language: The first generation language written in binary (0s and 1s). Directly
understood by the computer. No need for a translator or interpreter.
Disadvantages: Hard to remember operation codes, machine-dependent, difficult to
debug.
o Assembly Language: Uses words, names, and symbols instead of binary. Translated into
machine code by an Assembler.
o Disadvantages: Machine-dependent (specific to one CPU type), but faster and more
efficient than higher-level languages.

High-Level Language:

 Definition: High-level languages are closer to human language and are easier for programmers
to write, read, and maintain.
 Purpose: Programs are translated into machine language by compilers or interpreters to run on
computers. Less machine-dependent.
 Types:
o Common examples include C, FORTRAN, Pascal, COBOL, Java, LISP, C++,
BASIC, Prolog, and Ada.
 Advantages: Easier to write and debug. User-friendly, as the language uses English-like words,
symbols, and characters. Programs are portable across different computers.
 Compiler: Converts high-level code to machine code, also checks for errors before execution.

4
Introduction to C programming B24ESCK245
Key Characteristics:

 Closer to natural language.


 Easier to understand and write.
 Requires a compiler or interpreter to translate into machine code.

1.2.1 Types of Computer Languages

 Procedural Languages: Focus on the sequence of instructions for the computer to follow (e.g.,
C, Pascal).
 Object-Oriented Languages: Focus on objects and data encapsulation (e.g., C++, Java).
 Functional Languages: Focus on mathematical functions and immutable data (e.g., Haskell,
Lisp).
 Markup Languages: Used to define the structure and presentation of content (e.g., HTML,
XML).
 Scripting Languages: Used to automate tasks or add functionality to websites or programs (e.g.,
Python, JavaScript).

Aspect Low-Level Languages High-Level Languages


Closer to machine language, specific More abstracted from hardware, user-
Definition
to hardware friendly
Ease of Use Difficult to learn and use for humans Easier to understand and use for humans
Simple and readable syntax similar to
Syntax Complex and machine-specific syntax
natural languages
Machine Language, Assembly
Examples Python, Java, C++, Ruby, JavaScript
Language
Faster execution since it is directly Slower execution due to abstraction and
Speed of Execution
understood by the hardware interpretation
Not portable; machine-dependent Portable across different systems with
Portability
(specific to one architecture) minimal changes
Very low; works directly with
Abstraction Level High; abstracts away hardware details
hardware and memory
Memory Manual memory management; more Automatic memory management (e.g.,
Management control over hardware garbage collection)
More difficult due to close interaction Easier to debug, with higher-level tools and
Debugging
with hardware error messages
Typically compiled or interpreted into
Execution Executed directly by the CPU
machine code before execution
Control Over Gives full control over hardware and Limited control over hardware, focuses
Hardware system resources more on software logic
System-level programming, operating Application software, web development,
Use Case
systems, embedded systems business software

5
Introduction to C programming B24ESCK245
For Reference:

1.2.2. Compilers and Interpreters

 Compiler:
A compiler translates the entire high-level program into machine code before execution.
Examples: C, C++.
 Interpreter:
An interpreter translates and executes the program line by line. Examples: Python, JavaScript.

Interpreter Vs Compiler:

Interpreter Compiler

Scans the entire program and translates it as a whole


Translates program one statement at a time.
into machine code.

Interpreters usually take less amount of time to Compilers usually take a large amount of time to
analyze the source code. However, the overall analyze the source code. However, the overall
execution time is comparatively slower than execution time is comparatively faster than
compilers. interpreters.

No Object Code is generated, hence are memory Generates Object Code which further requires
efficient. linking, hence requires more memory.

Programming languages like JavaScript, Python, Programming languages like C, C++, Java use
Ruby use interpreters. compilers.

Diagram: Compiler vs. Interpreter

6
Introduction to C programming B24ESCK245
1.2.3. Evolution of Computer Languages

 First Generation:
Machine Language (binary code).
 Second Generation:
Assembly Language (mnemonics).
 Third Generation:
High-Level Languages (FORTRAN, C, COBOL).
 Fourth Generation:
High-level languages designed for specific tasks, such as SQL for databases or MATLAB for
mathematical computations.

1.3. PROGRAM DESIGN TOOLS :


It help developers plan, structure, and visualize solutions before writing code.

Example: Consider a flowchart for checking if a number is even or odd.

1.3.1. THE MEANING OF ALGORITHMS

Algorithms are step-by-step procedures designed to solve specific problems and perform
tasks efficiently in the realm of computer science and mathematics. These powerful sets of
instructions form the backbone of modern technology and govern everything from web
searches to artificial intelligence. Here's how algorithms work:
 Input: Algorithms take input data, which can be in various formats, such as numbers, text,
or images.
 Processing: The algorithm processes the input data through a series of logical and
mathematical operations, manipulating and transforming it as needed.

 Output: After the processing is complete, the algorithm produces an output, which could
be a result, a decision, or some other meaningful information.
 Efficiency: A key aspect of algorithms is their efficiency, aiming to accomplish tasks
quickly and with minimal resources.
 Optimization: Algorithm designers constantly seek ways to optimize their
algorithms, making them faster and more reliable.
 Implementation: Algorithms are implemented in various programming languages,
enabling computers to execute them and produce desired outcomes.

7
Introduction to C programming B24ESCK245

Example:

Example: A simple algorithm to calculate the sum of the first 5 natural numbers would look like this:

Steps:
1. Start
2. Initialize sum as 0
3. For each number from 1 to 5:
Add the number to sum.
4. End
(Return sum as the output)

1.3.2. FLOWCHARTS
A flowchart is a pictorial (graphical) representation of an algorithm. A flowchart is drawn
using different kinds of symbols. A symbol is used for a specific purpose. Each symbol has
name.

8
Introduction to C programming B24ESCK245
Flowcharts use different shapes of boxes to denote different type of instructions. ANSI
recommended a number of different rules and guidelines to help standardize the
flowcharting process.
 Algorithms are represented using flowcharts
 Flowchart symbols are standardized by ANSI
 Flowchart helps to divide a large complex problem into small manageable ones
 Generally, algorithm is first represented as a flowchart and then expressed in a
programming language.

 While preparing a flowchart, the sequence, selection and iterative structures may be used
wherever required.

Rules for Drawing a Flowchart


 It should contain only one start and one end symbol
 The relevant symbols must be used while drawing a flowchart
 The direction of arrows should be top to bottom and left to right
 It should be simple and drawn clearly and neatly
 Be consistent in using names, variables in the flow chart
 Use properly labeled connectors to link the portions of the flowchart on different pages
 The branches of decision box must be label

9
Introduction to C programming B24ESCK245

10
Introduction to C programming B24ESCK245

11
Introduction to C programming B24ESCK245
2.1 INTRODUCTION TO C

C is one of the most influential and widely-used programming languages, developed in the early 1970s.
It is a general-purpose, procedural, and powerful language that has formed the foundation for many
modern programming languages, such as C++, C#, and even operating systems like Unix. C has been
praised for its efficiency and flexibility, making it suitable for system programming and application
development.

2.1.1 History of C

1. Origins:
o The C programming language was created by Dennis Ritchie at Bell Labs in the early
1970s.
o It was developed as an enhancement of the B language (which was influenced by BCPL)
and aimed to be more powerful and efficient.
o C was originally designed for system programming—specifically, to write operating
systems (like Unix).
2. Development:
o 1972: C was first used for writing the Unix operating system.
o 1978: The first edition of the "K&R C" (named after Brian Kernighan and Dennis
Ritchie) was published in the book "The C Programming Language". This version of
C became widely used and is considered the foundation for modern C programming.
o 1983: The ANSI C standard (American National Standards Institute) was created to
standardize C across platforms.
o 1989: The ANSI C standard was revised and became the C89 standard.
o 1999: A major update, known as C99, was released, which introduced several new
features (e.g., inline functions, new data types).
o 2011: The C11 standard was introduced, focusing on features like multi-threading and
improved Unicode support.

Fig. 9.1: Taxonomy of C Language

12
Introduction to C programming B24ESCK245
3. C's Influence:
o The C language influenced a wide variety of programming languages and is still relevant
today, forming the basis for many others.
o Modern languages such as C++, C#, Objective-C, Java, and Python owe much of their
structure and syntax to C.

2.1.2. Features of C
C is known for its simplicity and versatility. Some of the most important features of the C programming
language include:

1. Simple and Structured:


o C has a small set of keywords and a clean syntax. This simplicity makes C an ideal
language for beginners to learn programming concepts.
o It is structured in a way that allows programmers to break down complex programs into
smaller, manageable functions.

2. Efficient:
o C allows direct manipulation of hardware and memory, which gives it a high degree of
control over system resources.
o It is considered a highly efficient language because it generates minimal machine code,
making programs faster.
3. Portable:
o C programs can run on different types of systems with minimal modification.
o The ANSI C standard allows C programs to be compiled and executed on virtually any
computer or operating system.
o C is not tied to any particular hardware or operating system. A C program written on one
machine can often be compiled and run on another with little or no modification.
4. Low-Level Access:
o C provides low-level access to memory via pointers, enabling developers to manipulate
memory addresses and directly interact with hardware.
o This low-level feature makes C particularly suitable for system programming (e.g.,
operating systems, drivers).
5. Rich Library Support:
o C comes with a comprehensive set of built-in functions and libraries for performing a
wide variety of operations like mathematical calculations, file handling, memory
management, and more.
6. Memory Management:
o C provides manual memory management using functions like malloc() (for memory
allocation) and free() (for deallocating memory).
o This gives developers complete control over memory usage and optimization but requires
more attention to detail to avoid issues like memory leaks.
7. Modularity:
o C allows programs to be divided into smaller functions (modular programming), making
them easier to develop and maintain.
o Functions in C can be reused in different parts of a program or even in different programs.
8. Support for Pointers:
o Pointers are a powerful feature of C, allowing variables to store memory addresses. This
makes it possible to dynamically allocate memory and directly manipulate data structures.

13
Introduction to C programming B24ESCK245
9. Recursion:
o C supports recursion, allowing a function to call itself. This is useful for solving problems
that can be broken down into smaller, similar problems (like tree traversals, factorial
calculation, etc.).
10. Efficient Performance
o C is fast and efficient because it is a compiled language and gives the programmer
direct control over the hardware. It is one of the best languages for performance-critical
applications like operating systems and game development.
o Unlike interpreted languages, C programs can be compiled into highly optimized
machine code.

2.2 Syntax / Structure of a C program:

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

• There are 6 basic sections responsible for the proper execution of a program. Sections are
mentioned below:
• 1. Documentation
• 2. Link/Preprocessor Section
• 3.Definition Section
14
Introduction to C programming B24ESCK245
• 4.Global Declaration Section
• 5.Main() Function Section
• 6.Sub Programs Section

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. Link/ 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 section:

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 MAX 200;

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

15
Introduction to C programming B24ESCK245

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;

Example: Below C program to find the sum of 2 numbers:

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

}
16
Introduction to C programming B24ESCK245

// Subprogram

int sum(int y)

return y + X;

Output: sum : 75

17
Introduction to C programming B24ESCK245

2.4 WRITING THE FIRST C PROGRAM


To Write a C program, we first need to write the code. For this, open a text editor. If you are
a Windows user you may use C Notepad and if you prefer working on UNIX/Linux you can use
emacs or vi/vim. Once the text editor is opened on your screen, type the following statements:
#include<stdio.h>
int main( )
{

printf(" Welcome to the world of C Program”);


return 0;
}

Output

Welcome to the world of C Program

2.5 CHARACTER SET IN C


Like in natural languages, computer languages also use a character set that defines the
fundamental units used to represent information. In C, a character means any letter from English
alphabet, a digit or a special symbol used to represent information. These characters when combined
together form tokens that act as basic building blocks of a C program. The character set of C can
therefore be given as:
a. English alphabet: Include both lower case (a z) as well as upper case (A Z) letters
b. Digits: Include numerical digits from 0 to 9
c. Special characters: Include symbols such as, % & ) < > * S / ) [ " etc.,
d. White space characters: These characters are used to print a blank space on the screen.
They are shown in Figure 2.7.

Fig. 2.7: White space characters used in C

18
Introduction to C programming B24ESCK245

2.6 C TOKENS

Tokens are the basic building blocks in C language. You may think of a token as the smallest
individual unit in a C program. This means that a program is constructed using a combination of
these tokens. There are six main types of tokens in C. They are shown in Figure 2.6.

Fig. 2.6: Tokens used in C

2.6.1. KEYWORDS
Like every computer language, C has a set of reserved words often known as keywords that cannot
be used as an identifier. All keywords are basically a sequence of characters that have a fixed meaning. By
convention al1 keywords must be written in lowercase (small) letters. Table 2.2 shows the list of keywords
in C.

Table 2.2: Keywords used in C

2.6.2. IDENTIFIERS
Identifiers, as the name suggests, help us to identify data and other objects in the program. Identifiers
are basically the names given to program elements such as variables, arrays, and functions. Identifiers may
consist of sequence of letters, numerals, or underscores.

19
Introduction to C programming B24ESCK245

Rules for Forming identifier Names

Some rules have to be followed while forming identifier names. They are as follows:

i. Identifiers cannot include any special characters or punctuation marks (like #,s, ^, ?, ., etc.)
except the underscore_.
ii. There cannot be two successive underscores.
iii. Keywords cannot be used as identifiers.
iv. The case of alphabetic characters that form the identifier name is significant.For example,
"FIRST' is different from 'first' and 'First'.

Examples of valid identifiers include:

roll_number, marks, name, emp_number, basic_pay, HRA,DA, dept_code,


DeptCode, RollNo, EMP_NO
Examples of invalid identifiers include:

23 student, %marks, @name, #emp_number,basic.pay,


-HRA, (DA), &dept_code, auto

2.6.3. VARIABLES
A variable is defined as a meaningful name given to a data storage location incomputer memory.
When using a variable, we actually refer to address of the memory where the data is stored. C language
supports two basic kinds of variables numeric and character.

i. Declaring variables

Each variable to be used in the program must be declared. To declare a variable, specify the data
type of the variable followed by its name. The data type indicates the kind of values that the variable will
store.

Variable names should always be meaningful and must reflect the purpose of their usage in the
program. The memory location of the variable is of importance to the compiler only and not to the
programmer. Programmers must only be concerned with accessing data through their symbolic names. In
C, variable declaration always ends with a semicolon, for example:

int emp_num;

float salary; char grade;


double balance_amount;

unsigned short int acc_no;

20
Introduction to C programming B24ESCK245

ii. Initializing Variables:

While declaring variables, we can also initialize them with some value. For example:

int emp_num = 7;

float salary = 2156.35;

char grade = ‘A’;

double balance_amount = 100000000;

2.6.4. BASIC DATA TYPES IN C


C language provides very few basic data types. Table 2.3 lists of the basic data types, their size,
range, and usage for a C programmer on a 16-bit computer.

Table 2.3: Basic data types in C

Table 9.4 shows the variants of basic data types. As can be seen from the table, we have unsigned
char and signed char. Do we have negative characters? No, then why do we have such data types? The
answer is that we use signed and unsigned char to ensure portability of programs that store non-character
data as char.

While the smaller data types take less memory, the larger types incur a performance penalty.
Although the data type we use for our variables does not have a big impact on the speed or memory usage
of the application, we should always try to use int unless there is a special need to use any other data type.

21
Introduction to C programming B24ESCK245

22
Introduction to C programming B24ESCK245

2.6.5. CONSTANTS
Constants are identifiers whose values do not change. While values of variables can be changed at
any time, values of constants can never be changed. Constants are used to define fixed values like
mathematical constant pie or the charge on an electron so that their value does not get changed in the
program even by mistake.

A constant is an explicit data value specified by the programmer. The value of the constant is known
to the compiler at the compile time. C allows the programmer to specify constants of integer type, floating
point type, character type, and string type (Figure 2.8).

Fig. 2.8: Constants in C

i. Declaring Constants

To declare a constant, precede the normal variable declaration with const keyword and assign it a
value. For example,

const float pi = 3.14;

The const keyword specifies that the value of pi cannot change. However, another way to designate
a constant is to use the pre-processor command define. Like other pre- processor commands, define is
preceded with a # symbol. Although #define statements can be placed anywhere in a C program, it is always
recommended that these statements be placed at the beginning of the program to make them easy to find
and modify at a later stage. Look at the example given below which defines the value of pi using define.

#define pi 3.14159

#define service_tax 0.12

23
Introduction to C programming B24ESCK245

2.6. INPUT/OUTPUT STATEMENTS IN C

2.6.1. Formatting Input/Output


C language supports two formatting functions printf and scanf. printf is used toconvert data stored
in the program into a text stream for output to the monitor, and scanf is used to convert the text stream
coming from the keyboard to data values and stores them in program variables.

2.6.2. printf()

The printf function (stands for print formatting) is used to display information required by the user and also
prints the values of the variables. For this, the print function takes data values, converts them to a text stream
using formatting specifications in the controlstring and passes the resulting text stream to the standard output.
The control string may contain zero or more conversion specifications, textual data, and control characters to
be displayed.

printf("control string", variable list);

The function accepts two parameters-control string and variable list. The control string may also
contain the text to be printed like instructions to the user, captions, identifiers,or any other text to make the
output readable.

Examples:
printf("\n The number is %6d", 12);

Output: The number is 12

printf("\n The price of this item is %09.2f rupees", 123.456);

Output: The price of this item is000123.45 rupees

printf("\n The number is %06d", 1234);

Output:The number is 001234

2.6.3. scanf():

The scanf() function stands for scan formatting and is used to read formatted data from the
keyboard. The scanf function takes a text stream from the keyboard, extracts and formats data from the
stream according to a format control string and then stores the data in specified program variables. The
syntax of the scanf() function can be given as:

scanf("control string", arg1, arg2, arg3,….argn);

24
Introduction to C programming B24ESCK245

The control string specifies the type and format of the data that has to be obtained from the keyboard
and stored in the memory locations pointed by arguments arg1, arg2,, argn, i.e., the arguments are actually
the variable addresses where each piece of data is to be stored.

Ex: int num;

scanf("%d", &num);

The scanf function reads an integer value (because the type specifier is %d) into the address
or the memory location pointed by num.

float salary;
scanf("%f ", &salary) ;

The scanf function reads a floating point number (because the type specifier is %f) into the address
or the memory location pointed by salary.

char ch;
scanf("%c ", &ch);

The scanf function reads a single character (because the type specifier is %c) into the address or the
memory location pointed by ch.

char str[10];
scanf("%s ", str);

The scanf function reads a string or a sequence of characters (because the type specifier is %s) into
the address or the memory location pointed by str. Note that in case of reading strings, we do not use the &
sign in the scanf() function.

Example program:

Write a program to demonstrate the use of printf and scanf statements to read and print values of
variables of different data types.

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

int num;

float amt;

char code;

25
Introduction to C programming B24ESCK245
double pi;
char msg[10];
printf("\n Enter the value of num ");

scanf("%d", &num)
printf("\n Enter the value of amt: ");
scanf("%f", &amt) ;
printf("\n Enter the value of pi : ");
scanf("%ld", &pi);
printf("\n Enter the value of code: ");

scanf("%c", &code);
printf("\n Enter the message :");

scanf("%s", msg);
printf("\n NUM = %d \n AMT = %f \n PI %e \n POPULATION OF INDIA = %ld \nCODE = %c \n MESSAGE =
%s", num, amt, pi, population_of_india, code, msg);
return 0;
}
OUTPUT:

Enter the value of num 5 Enter the value of amt:


123.45Enter the value of pi: 3.14159
Enter the population of India: 12345Enter the value of
code: c
Enter the message : Hello

NUM = 5
AMT = 123.450000PI = 3.141590e+00
POPULATION OF INDIA = 12345CODE = c
MESSAGE = Hello

26
Introduction to C programming B24ESCK245

2.7. Types of Errors in C


1. Syntax Errors:
o These occur when the program does not follow the correct syntax of the C language (e.g.,
missing semicolons, mismatched parentheses).
o Example: int x = 10 (missing semicolon).
2. Semantic Errors:
o These occur when the program follows the syntax rules but produces incorrect results due to
logical flaws or incorrect use of language features.
o Example: Dividing by zero (x / 0), using uninitialized variables.
3. Runtime Errors:
o These errors occur while the program is running, causing the program to terminate
unexpectedly.
o Example: Trying to access an array element out of bounds (arr[10] when the array size is 5).
4. Linker Errors:
o These errors occur when the program cannot link properly, usually because of undefined or
mismatched references to functions or variables in different files.
o Example: Using a function without declaring it or not including the correct library files.
5. Logical Errors:
o These errors occur when the logic of the program is incorrect, even though the program
compiles and runs.
o Example: Incorrect calculation due to wrong formula.

27

You might also like