0% found this document useful (0 votes)
29 views30 pages

Csa 1500 - Module - 1

The document provides an introduction to the C programming language, its history, and its significance in computer programming. It covers fundamental concepts such as coding, debugging, and the roles of compilers and interpreters, as well as an overview of computer basics, including hardware and software distinctions. Additionally, it outlines problem-solving techniques and the characteristics of algorithms, emphasizing the structured approach to programming and problem resolution.

Uploaded by

kumari K
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)
29 views30 pages

Csa 1500 - Module - 1

The document provides an introduction to the C programming language, its history, and its significance in computer programming. It covers fundamental concepts such as coding, debugging, and the roles of compilers and interpreters, as well as an overview of computer basics, including hardware and software distinctions. Additionally, it outlines problem-solving techniques and the characteristics of algorithms, emphasizing the structured approach to programming and problem resolution.

Uploaded by

kumari K
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/ 30

CSA 1500 Problem Solving Using C Module 1

Introduction to C
Background:

C was developed by a system programmer Dennis Ritchie in 1970-72, at American


Telegraph & Telecommunication (AT & T) Bell Laboratories in New Jersey USA. It
was written originally for programming under UNIX operating system.

C was developed from BCPL (Basic Combined Programming Language-B) which


was improved and renamed as B. B was developed in 1960’s at Cambridge
University.

Languages prior to C are FORTRAN (Formula Translation), COBOL (Common


Business Oriented Language), BASIC (Beginners All Purpose Symbolic Instruction
Code) and Pascal. Languages after C are C++, Java, C# etc. C permits very close
interaction with the inner working of the computer.

C has now become a widely used professional language for various reasons.

 Easy to learn
 Structured language
 It produces efficient programs.
 It can handle low-level activities.
 It can be compiled on a variety of computers.

Coding:
The process of converting the representation of a solution into set of
instruction in a programming language is known as coding.
Debugging:
The process of correcting error in a program is known as debugging.
Complier:
It is a software, which check the entire program created by the uses for
a certain type of errors called syntax error. If the program is error free the
complete program is translated into its equivalent machine language.
Source program/code:
The program created by the users is known as source program.

1
CSA 1500 Problem Solving Using C Module 1

Object program:
The machine language generated by the compiler is known as object
program.
Syntax:
It refers to set of rules which should be followed while creating every
statement in a program.
Syntax error:
The error which accrues due to the wrong use of syntax is known as syntax
error.
Semantic:
It refers to the logic which is followed for representing a solution.

Semantic Error:
An error which is accursed due to wrong use of logic.
Logical Error:
If the program produces wrong result such error are known as logical
error.
Runtime Error:
Errors which are deleted during run time or execution of a program is
known as run time error.
Testing:
It is the process of checking whether program work correctly according to
the requirement of the user.

2
CSA 1500 Problem Solving Using C Module 1

COMPUTER BASICS
 A Computer is an electronic device that stores, manipulates and retrieves
the data.
 Similarly a computer system can have objects and process.

The following are the objects of computer System

a) User ( A person who uses the computer)


b) Hardware
c) Software

Hardware: Hardware of a computer system can be referred as anything which


we can touch and feel. Example: Keyboard and Mouse.
The hardware of a computer system can be classified as
 Input Devices(I/P)
 Processing Devices (CPU)
 Output Devices(O/P)

 ALU: It performs the Arithmetic and Logical Operations such as


+,-,*,/ (Arithmetic Operators) &&, || ( Logical Operators)
 CU: Every Operation such as storing, computing and retrieving the data
should be governed by the control unit.
 MU: The Memory unit is used for storing the data. The Memory unit is
classified into two types.
They are

1) Primary Memory
2) Secondary Memory

3
CSA 1500 Problem Solving Using C Module 1

Primary memory: The following are the types of memories which are treated
as primary.
ROM: It represents Read Only Memory that stores data and instructions even
when the computer is turned off. The Contents in the ROM can‘t be modified
once if they are written . It is used to store the BIOS information.
RAM: It represents Random Access Memory that stores data and instructions
when the computer is turned on. The contents in the RAM can be modified any
no. of times by instructions. It is used to store the programs under execution.
Cache memory: It is used to store the data and instructions referred by
processor.

Secondary Memory:
The following are the different kinds of memories
-Magnetic Storage: The Magnetic Storage devices store information that can
be read, erased and rewritten any number of times.
Example: Floppy Disks, Hard Disks, Magnetic Tapes

-Optical Storage: The optical storage devices that use laser beams to read and
write stored data. Example: CD(Compact Disk),DVD(Digital Versatile Disk)

COMPUTER SOFTWARE

Software of a computer system can be referred as anything which we can feel and
see. Example: Windows, icons
Computer software is divided in to two broad categories: system software and
application software. System software manages the computer resources .It
provides the interface between the hardware and the users. Application software,
on the other hand is directly responsible for helping users solve their problems.

System Software

System software consists of programs that manage the hardware resources of


a computer and perform required information processing tasks. These programs
are divided into three classes: the operating system, system support, and system
development.

4
CSA 1500 Problem Solving Using C Module 1

The operating system provides services such as a user interface, file and
database access, and interfaces to communication systems such as Internet
protocols. The primary purpose of this software is to keep the system operating
in an efficient manner while allowing the users access to the system.
System support software provides system utilities and other operating
services. Examples of system utilities are sort programs and disk format
programs. Operating services consists of programs that provide performance
statistics for the operational staff and security monitors to protect the system and
data.
The last system software category, system development software, includes
the language translators that convert programs into machine language for
execution, debugging tools to ensure that the programs are error free and
computer –assisted software engineering (CASE) systems.

Application software

Application software is broken in to two classes: general-purpose software and


application – specific software. General purpose software is purchased from a
software developer and can be used for more than one application. Examples of
general purpose software include word processors, database management
systems ,and computer aided design systems. They are labeled general purpose
because they can solve a variety of user computing problems.
Application –specific software can be used only for its intended purpose.
A general ledger system used by accountants and a material requirements
planning system used by a manufacturing organization are examples of
application-specific software. They can be used only for the task for which they
were designed they cannot be used for other generalized tasks.
The relationship between system and application software is shown below. In this
figure, each circle represents an interface point .The inner core is hard ware. The
user is represented by the out layer. To work with the system, the typical user
uses some form of application software. The application software in turn interacts
with the operating system, which is a part of the system software layer. The

5
CSA 1500 Problem Solving Using C Module 1

system software provides the direct interaction with the hard ware. The opening
at the bottom of the figure is the path followed by the user who interacts directly
with the operating system when necessary.

COMPUTER LANGUAGES

To write a program (tells what to do) for a computer, we must use a computer
language. Over the years computer languages have evolved from machine
languages to natural languages. The following is the summary of computer
languages
1940‘s Machine Languages

1950‘s Symbolic Languages

1960‘s High Level Languages

Machine Language:

In the earliest days of computers, the only programming languages available were
machine languages. Each computer has its own machine language which is made
of streams of 0‘s and 1‘s. The instructions in machine language must be in streams
of 0‘s and 1‘s. This is also referred as binary digits. These are so named as the
machine can directly understood the programs.
Advantages:
1) High speed execution
2) The computer can understand instructions immediately
3) No translation is needed.
Disadvantages:

1) Machine dependent
2) Programming is very difficult
3) Difficult to understand
4) Difficult to write bug free programs
5) Difficult to isolate an error.

Example : Addition of two numbers

6
CSA 1500 Problem Solving Using C Module 1

Symbolic Languages (or) Assembly Language

In the early 1950‘s Admiral Grace Hopper, a mathematician and naval officer,
developed the concept of a special computer program that would convert
programs into machine language. These early programming languages simply
mirrored the machine languages using symbols or mnemonics to represent the
various language instructions. These languages were known as symbolic
languages. Because a computer does not understand symbolic language it must
be translated into the machine language. A special program called an Assembler
translates symbolic code into the machine language. Hence, they are called as
Assembly language.
Advantages:
1) Easy to understand and use
2) Easy to modify and isolate error
3) High efficiency
4) More control on hardware
Disadvantages:

1) Machine Dependent Language


2) Requires translator
3) Difficult to learn and write programs
4) Slow development time
5) Less efficient
Example:

High-Level Languages:

The symbolic languages greatly improved programming efficiency they still


required programmers to concentrate on the hardware that they were using
working with symbolic languages was also very tedious because each machine
instruction had to be individually coded. The desire to improve programmer
efficiency and to change the focus from the computer to the problems being solved
led to the development of high-level languages.

7
CSA 1500 Problem Solving Using C Module 1

High-level languages are portable to many different computers allowing the


programmer to concentrate on the application problem at hand rather than the
intricacies of the computer.
C A systems implementation Language
C++ C with object-oriented enhancements
Object oriented language for internet and general applications
JAVA using basic C syntax
object-oriented, high-level programming language with dynamic
Python semantics

Advantages:
1) Easy to write and understand
2) Easy to isolate an error
3) Machine independent language
4) Easy to maintain
5) Better readability
6) Low Development cost
7) Easier to document
8) Portable
Disadvantages:

1) Needs translator
2) Requires high execution time
3) Poor control on hardware
4) Less efficient
Example:C language

Difference between Machine, Assembly, High Level Languages

Feature Machine Assembly High Level


Form 0‘s and 1‘s Mnemonic codes Normal English
Machine Dependent Dependent Independent
Dependent
Translator Not Needed Needed (Assembler) Needed
(Compiler)
Execution Time Less Less High

8
CSA 1500 Problem Solving Using C Module 1

Languages Only one Different Different


Manufacturers Languages
Nature Difficult Difficult Easy
Memory Space Less Less More

Language Translators

These are the programs which are used for converting the programs in one
language into machine language instructions, so that they can be executed by
the computer.

1) Compiler: It is a program which is used to convert the high-level language


programs into machine language
2) Assembler: It is a program which is used to convert the assembly level
language programs into machine language
3) Interpreter: It is a program, it takes one statement of a high-level language
program, translates it into machine language instruction and then immediately
executes the resulting machine language instruction and so on.
Comparison between a Compiler and Interpreter

COMPILER INTERPRETER

A Compiler is used to compile an


An interpreter is used to translate
entire program and an executable
each line of the program code
program is generated through the
immediately as it is entered.
object program.

The executable program is stored in a The executable program is generated in


disk for future use or to run it in anothe RAM and the interpreter is required for
computer each run of the program.

The compiled programs run faster The Interpreted programs run slower
Most of the Languages use compiler A very few languages use interpreters.

CREATING AND RUNNING PROGRAMS:

The procedure for turning a program written in C into machine Language. The
process is presented in a straightforward, linear fashion but you should recognize
that these steps are repeated many times during development to correct errors

9
CSA 1500 Problem Solving Using C Module 1

and make improvements to the code.

The following are the four steps in this process


1) Writing and editing the program
2) Compiling the program
3) Linking the program with the required modules
4) Executing the program

Name of File
Sl. No. Phase Code Tools Extension
C Compilers
1 TextEditor Source Code Edit, .C
Notepad Etc..,
2 Compiler Object Code C Compiler .OBJ

Executable
3 Linker C Compiler .EXE
Code

Executable
4 Runner C Compiler .EXE
Code

Writing and Editing Programs

The software used to write programs is known as a text editor. A text editor helps
us enter, change and store character data. Once we write the program in the text
editor, we save it using a filename stored with an extension of C. This file is
referred as source code file.

Compiling Programs
10
CSA 1500 Problem Solving Using C Module 1

The code in a source file stored on the disk must be translated into machine
language. This is the job of the compiler. The Compiler is a computer program
that translates the source code written in a high-level language into the
corresponding object code of the low-level language. This translation
process is called compilation. The entire high-level program is converted into
the executable machine code file. The Compiler which executes C programs is
called as C Compiler. Example Turbo C, Borland C, GC etc.,

Linking Programs

The Linker assembles all functions, the program ‘s functions and system‘s
functions into one executable program.

Executing Programs

To execute a program, we use an operating system command, such as run, to


load the program into primary memory and execute it. Getting the program into
memory is the function of an operating system program known as the loader.
It locates the executable program and reads it into memory. When everything is
loaded the program takes control and it begin execution.

Problem Solving Techniques:

Sometimes it is not sufficient just to cope with problems. We have to solve those
problems. Most people are involving to solve the problem. These problems are
occurred while performing small task or making small decision.

So, here are some basic steps to solve the problems

Step 1: Identify and Define Problem

Explain you problem clearly as possible as you can.

Step 2: Generate Possible Solutions

 List out all the solution that you find. Don’t focus on the quality of the
solution

 Generate the maximum number of solution as you can without considering


the quality of the solution

11
CSA 1500 Problem Solving Using C Module 1

Step 3: Evaluate Alternatives

After generating the maximum solution, Remove the undesired solutions.

Step 4: Decide a Solution

After filtering all the solution, you have the best solution only. Then choose on of
the best solution and make a decision to make it as a perfect solution.

Step 5: Implement a Solution:

After getting the best solution, Implement that solution to solve a problem.

Step 6: Evaluate the result

After implementing a best solution, Evaluate how much you solution solve the
problem. If your solution will not solve the problem then you can again start
with Step 2.

ALGORITHM

Algorithm is a finite sequence of instructions, each of which has a clear meaning


and can be performed with a finite amount of effort in a finite length of time. No
matter what the input values may be, an algorithm terminates after executing a
finite number of instructions.

We represent an algorithm using a pseudo language that is a combination of the


constructs of a programming language together with informal English statements.
The ordered set of instructions required to solve a problem is known as an
algorithm.
The characteristics of a good algorithm are:
 Precision – the steps are precisely stated (defined).
 Uniqueness – results of each step are uniquely defined and only depend on
the input and the result of the preceding steps.
 Finiteness – the algorithm stops after a finite number of instructions are
executed.
 Input – the algorithm receives input.
 Output – the algorithm produces output.
 Generality – the algorithm applies to a set of inputs.

12
CSA 1500 Problem Solving Using C Module 1

Disadvantage of Algorithms:

5) It is time consuming
6) Difficult to show branching and looping statement
7) Large problems are difficult to implement

Example Q. Write a algorithm to find out number is odd or even?


step 1 : start
step 2 : input number
step 3 : rem=number mod 2 step 4 : if rem=0 then
print "number even" else
print "number odd" endif
step 5 : stop

Flowchart:
Flowcharts use special shapes to represent different types of actions or steps in a
process. Lines and arrows show the sequence of the steps, and the relationships
among them. These are known as flowchart symbols.
Common Flowchart Symbols
Rectangle Shape – Represents a process
Oval or Pill Shape – Represents the start or end
Diamond Shape – Represents a decision
Parallelogram – Represents input/output

13
CSA 1500 Problem Solving Using C Module 1

Advantages of flowchart:

The Flowchart is an excellent way of communicating the logic of a program.


It is easy and efficient to analyse problem using flowchart.
During program development cycle, the flowchart plays the role of a guide
or a blueprint. Which makes program development process easier.
After successful development of a program, it needs continuous timely
maintenance during the course of its operation. The flowchart makes
program or system maintenance easier.
It helps the programmer to write the program code.
It is easy to convert the flowchart into any programming language code as
it does not use any specific programming language concept.

Disadvantage of flowchart

1. The flowchart can be complex when the logic of a program is quite


complicated.
2. Drawing flowchart is a time-consuming task.
3. Difficult to alter the flowchart. Sometimes, the designer needs to redraw the
complete flowchart to change the logic of the flowchart or to alter the flowchart.
4. Since it uses special sets of symbols for every action, it is quite a tedious
task to develop a flowchart as it requires special tools to draw the necessary
symbols.
5. In the case of a complex flowchart, other programmers might have
a difficult time understanding the logic and process of the flowchart.
6. It is just a visualization of a program, it cannot function like an actual
program

Examples of flowcharts in programming

Draw a flowchart to add two numbers entered by user.

14
CSA 1500 Problem Solving Using C Module 1

Draw flowchart to find the largest among three different numbers entered by user.

Coding, Compiling and Execution

15
CSA 1500 Problem Solving Using C Module 1

BASIC STRUCTURE OF C PROGRAMMING

1. Documentation section: The documentation section consists of a set


of comment lines giving the name of the program, the author and other details,
which the programmer would like to use later.
// (Single line comment) and /*…….*/ (Multiline comment) are two
types of comments

2. Link section (Preprocessor directive): The link section provides


instructions to the compiler to link functions from the system library such as using
the #include directive. The stdio.h (standard input output header file) contains
definition &declaration of pre-defined function such as printf( ), scanf( ).
 printf() function used to display
 scanf() function used to read value

3. Definition section: The definition section defines all symbolic constants


such using the #define directive.

4. Global declaration section: There are some variables that are used in
more than one function. Such variables are called global variables and are
declared in the global declaration section that is outside of all the functions. This
section also declares all the user-defined functions.

16
CSA 1500 Problem Solving Using C Module 1

5. main () function section: Every C program must have one main


function section. This section contains two parts; declaration part and executable
part
Declaration part: The declaration part declares all the variables used in
the executable part.
Executable part: There is at least one statement in the executable part.
These two parts must appear between the opening and closing braces. The
program execution begins at the opening brace and ends at the closing
brace. The closing brace of the main function is the logical end of the
program. All statements in the declaration and executable part end with a
semicolon.

6. Subprogram section: If the program is a multi-function program then


the subprogram section contains all the user-defined functions that are called in
the main () function. User-defined functions are generally placed immediately
after the main () function, although they may appear in any order.

Steps for Compiling and executing the Programs

A compiler is a software program that analyzes a program developed in a


particularcomputer language and then translates it into a form that is suitable for
execution on a particular computer system.

Step 1: The program that is to be compiled is first typed into a file on the
computer system. Name should be provided with the last two characters as “.c”
or file with extension .c. So, the file name prog1.c might be a valid filename for
a C program.A text editor is usually used to enter the C program into a file. The
program that is entered into the file is known as the source program.

Step 2: Alt+F9
The compiler examines each program statement contained in the source program
and checks the syntax and semantics of the language. If any mistakes are
discovered, they are reported to the user. The errors have to be corrected in the
source program, and the compilation process must be restarted. Typical errors
reported during this phase of compilation might be due to an expression that has
unbalanced parentheses (syntactic error), or due to the use of a variable that is
not “defined” (semantic error).

Step 3: When all the syntactic and semantic errors have been removed from the
program, the compiler translate/Converts itinto a binary format known as object
code
17
CSA 1500 Problem Solving Using C Module 1

Step 4: After the program has been translated into object code, it is ready to be
linked. This process is once again performed automatically. The purpose of the
linking phase is to get the program into a final form for execution on the computer.

Step 5: To execute the program, the command Ctrl+F9

When the program is executed, each of the statements of the program is


sequentially executed. Results that are displayed by the program, known as
output, appear in a window, sometimes called the console. If the program does
not produce the desired results, it is necessary to go back and reanalyze the
program’s logic. This is known as the debugging phase, during which an attempt
is made to remove all the known problems or bugs from the program.

Tokens
In a paragraph of text document, individual words and punctuation marks are
called tokens. Similarly, the smallest individual unit in a c program which are
meaningful to the compiler is known as a token.
Different tokens in C can be classified as below:
1. Keyword (e.g. int, for, if)
2. Identifier (e.g. main, a, sum)
3. Constant (e.g. 10, 3.14)
4. string-literal (e.g. “hello”, “hello”)
5. operator (e.g. +, /, *)
6. Special symbols (e.g. (), {}, ;)
Keywords
Keywords are pre-defined words in a C compiler.
Each keyword convey special meaning and perform a specific function in
a C program.
Since keywords are referred names for compiler, they can’t be used as
variable name.
The C language have the following keywords:

18
CSA 1500 Problem Solving Using C Module 1

Identifier
General terminology used for the names of variables, functions and arrays.
These are user defined names consisting of arbitrarily long sequence of
letters and digits.
Identifiers may either a letter or the underscore(_) as a first character.
eg. x is a name given to integer variable.
int x=10;

Rules for naming an identifier

The first character must always be an alphabet or an underscore.


It should be formed using only letters, numbers, or underscore.
A keyword cannot be used as an identifier.
It should not contain any whitespace character.
The name must be meaningful.

Constant
Data items that remains same i.e. their value during do not changes
during the program
execution.
Several types of C constants that are allowed in C are; integer constant,
real constant,
character constant, string constant and other.

19
CSA 1500 Problem Solving Using C Module 1

String Literal
Sequence of characters enclosed within double quotes. For example, “hello”
, “abc”.
Every sting constant is automatically terminated with a special character ‘’
called the null character which represents the end of the string.
For example, “hello” will represent “hello” in the memory.
Thus, the size of the string is the total number of characters plus one for
the null character.

Operators
C operators are symbols that trigger an action and perform operation
when applied to C variables and other objects.
The data items on which operators act upon are called operands.
Operators can be classified as follows:
Unary Operators: Those operators that require only single operand to act
upon are known as unary operators.
Binary Operators: Those operators that require two operands to act upon
are called binary operators.
Ternary Operators: These operators require three operands to act upon.

Special Symbols
It has some special meaning
Thus, cannot be used for some other purpose.
[] () {} , ; : * … = #
Braces{}: These opening and ending curly braces marks the start and end
of a block of
code containing more than one executable statement.
Parentheses(): These special symbols are used to indicate function calls
and function
parameters.
Brackets[]: Opening and closing brackets are used as array element
reference. These
indicate single and multidimensional subscripts.

20
CSA 1500 Problem Solving Using C Module 1

VARIABLES

A variable is nothing but a name given to a storage area that our


programs can manipulate. Each variable in C has a specific type, which
determines the size and layout of the variable's memory; the range of
values that can be stored within that memory; and the set of
operations that can be applied to the variable.

The name of a variable can be composed of letters, digits, and the


underscore character. It must begin with either a letter or an
underscore. Upper and lowercase letters are distinct because C is case-
sensitive. Based on the basic types explained in the previous chapter,
there will be the following basic variable types −

Type Description

char Typically a single octet(one byte). This is an integer type.

int The most natural size of integer for the machine.

float A single-precision floating point value.

double A double-precision floating point value.

A variable definition tells the compiler where and how much storage to
create for the variable. A variable definition specifies a data type and
contains a list of one or more variables of that type as follows −

type variable_list;

Here, type must be a valid C data type including char, int, float,
double, bool, or any user-defined object; and variable_list may
consist of one or more identifier names separated by commas. Some
valid declarations are shown here −

21
CSA 1500 Problem Solving Using C Module 1

int i, j, k;
char c, ch;
float f, salary;
double d;

The line int i, j, k; declares and defines the variables i, j, and k;


which instruct the compiler to create variables named i, j and k of
type int.

Variables can be initialized (assigned an initial value) in their


declaration. The initializer consists of an equal sign followed by a
constant expression as follows −

type variable_name = value;

Some examples are −

extern int d = 3, f = 5; // declaration of d and f.


int d = 3, f = 5; // definition and initializing d and f.
byte z = 22; // definition and initializes z.
char x = 'x'; // the variable x has the value 'x'.

For definition without an initializer: variables with static storage


duration are implicitly initialized with NULL (all bytes have the value
0); the initial value of all other variables is undefined.

A variable declaration provides assurance to the compiler that there


exists a variable with the given type and name so that the compiler
can proceed for further compilation without requiring the complete
detail about the variable. A variable definition has its meaning at the
time of compilation only; the compiler needs actual variable definition
at the time of linking the program. A variable declaration is useful when
multiple files are used.

22
CSA 1500 Problem Solving Using C Module 1

Difference between Variable and Constant

Examples:

Input and Output: Standard inpuan t d output, formatted output- printf:

Input means to provide the program with some data to be used in it


and Output means to display data on the screen or write the data to a printer or
a file.

The C programming language provides standard library functions to read any


given input and display output on the console.

While dealing with input-output operations in C, we use the following two streams:

 Standard Input (stdin)

 Standard Output (stdout)

Standard input or stdin is used for taking input and Standard


output or stdout is used for giving output. The functions used for standard input
and output are present in the stdio.h header file. Hence, to use those functions,
we need to include the stdio.h header file in our program, as shown below.

#include <stdio.h>

C language offers us several built-in functions for performing input/output


operations. Following are the functions used for standard input and output:

23
CSA 1500 Problem Solving Using C Module 1

1. printf() function - Show Output


2. scanf() function - Take Input
3. getchar() and putchar() function
4. gets() and puts() function

1. The printf() function

The printf() function is the most used function in the C language. This function is
defined in the stdio.h header file and is used to show output on the console
(standard output).

Following is how the printf() function is defined in the C stdio.h library.

int printf(const char *format, ...);

It writes the C string pointed by the format pointer to the standard output
(stdout). On success, the total number of characters written is returned.

This function is used to print a simple text sentence or value of any


variable which can be of int, char, float, or any other datatype.

printf() Code Examples


#include <stdio.h>
int main()
{
int testInteger = 5;
printf("Number = %d", testInteger);
return 0;
}

24
CSA 1500 Problem Solving Using C Module 1

Scanf Statement:

In C programming, scanf() is one of the commonly used function to take input


from the user. The scanf() function reads formatted input from the standard input
such as keyboards.

Example 1:
#include <stdio.h>
int main()
{
int testInteger;
printf("Enter an integer: ");
scanf("%d", &testInteger);
printf("Number = %d",testInteger);
return 0;
}

Output:

Enter an integer: 4

Number = 4

Example 2:
// C program to Read the two integer values using formatted input
scanf()
#include <stdio.h>

// Driver Code
int main()
{
int a, b, c;
c = scanf("%d %d", &a, &b);
printf("Number of successful "
"inputs read : %d",
c);

return 0;

25
CSA 1500 Problem Solving Using C Module 1

getchar() and putchar() function

This is the input function in c programming. We can read only a single


character using this getchar function from the console. See the following syntax.

Syntax:

char getchar();

From the above syntax, the return type of getchar function is char. That means,
it can read only character value. For example, ch=getchar(); will read a single
character from a console and store that character in the character variable ch.

This is output function in c programming which display a single character to the


console. It has the following syntax.

Syntax:

int putchar(char);

from the above syntax, you can see that return type of putchar function is int.
That means it returns the ASCII value of the variable char that we are displaying
on the console.

For example, suppose, we have a integer variable i and the


statement i=putchar(‘a’); will display the character ‘a’ to the console and the
value of i will be 97. The ASCII value of ‘a’ is 97.

C Program to Read and Write a Single Character

In this program, we are just reading a single character and displaying


the same character on the console.

#include <stdio.h>
#include <stdlib.h>
main( )
{
char ch;
printf("Enter a character: ");
ch=getchar();
26
CSA 1500 Problem Solving Using C Module 1

printf("You have entered a character: ");


putchar(ch);
return 0;
}
Output
Enter a character: C
You have entered a character: C

C gets() and puts() functions

The gets() and puts() are declared in the header file stdio.h. Both the functions
are involved in the input/output operations of the strings.

C gets() function

The gets() function enables the user to enter some characters followed by the
enter key.

Syntax

char[] gets(char[]);

Reading string using gets()

#include<stdio.h>

void main ()

char s[30];

printf("Enter the string? ");

gets(s);

printf("You entered %s",s);

C puts() function

27
CSA 1500 Problem Solving Using C Module 1

The puts() function is very much similar to printf() function. The puts() function
is used to print the string on the console which is previously read by using gets()
or scanf() function.

Syntax

int puts(char[])

Let's see an example to read a string using gets() and print it on the console using
puts().

#include<stdio.h>

#include <string.h>

int main(){

char name[50];

printf("Enter your name: ");

gets(name); //reads string from user

printf("Your name is: ");

puts(name); //displays string

return 0;

Difference between Formatted and Unformatted Functions

SlNo Formatted I/O functions Unformatted I/O functions

Unformatted I/O functions are


Formatted I/O functions allow
the most basic form of input and
supply input or display output
1 output and they do not allow to
user desired format.
supply input or display output in
user desired format.
getch(), getche(), getchar(),
printf() and scanf() are
gets(), puts(), putchar() etc.
examples for formatted input and
2 are examples of unformatted
output functions.
input output functions.

28
CSA 1500 Problem Solving Using C Module 1

Unformatted input and output


Formatted input and output
functions do not contain format
3 functions contain format
specifier in their syntax.
specifier in their syntax.
Formatted I/O functions are Unformatted I/O functions are
used for storing data more user used for storing data more
4
friendly. compactly.

Formatted I/O functions are Unformatted I/O functions are


5 used with all data types. used mainly for character and
string data types.

Formatted I/O Example:

#include<stdio.h>
#include<conio.h>
void main()
{
int a;
clrscr();
printf(“Enter value of a:”);
scanf(“%d”, &a);
printf(“ a = %d”, a);
getch();
}

Output of the above program is:

Enter value of a:5𝖩


a=5

Unformatted I/O Example:

#include<stdio.h>
#include<conio.h>
void main()
{
char ch ;

29
CSA 1500 Problem Solving Using C Module 1

clrscr();
printf(“Press any character:”);
ch = getchar();
printf(“\nYou pressed :”)
putchar(ch);
getch();
}

Output of the above program is:

Press any character: L


You pressed: L

30

You might also like