Download as pdf or txt
Download as pdf or txt
You are on page 1of 27

Course Principles of Programming using C

Title:
Course Code: 22POP13/23
CIE Marks 50
Integrated
SEE Marks 50
Course Type
(Theory/Practical
/Integrated ) Total Marks100

Teaching Hours/Week 2:0:2


Exam Hours 3+2
(L:T:P: S)
40 hours
Total Hours of Pedagogy Credits 03
CourseObjectives:

CLO 1. Elucidate the basic architecture and functionalities of a Computer


CLO 2. Apply programming constructs of C language to solve the real-world
problems
CLO 3.Explore user-defined data structures like arrays, structures and pointers in
implementing solutions to problems
CLO 4. Design and Develop Solutions to problems using structured programming
constructs such as functions and procedures

Teaching-Learning Process(General Instructions)

ThesearesampleStrategies,whichteacherscanusetoacceleratetheattainmentofthevariouscourse
outcomes.
1. Lecturer method (L) need not to be only traditional lecture method, but
alternative effective teaching methods could be adopted to attain the outcomes.
2. Use of Video/Animation to explain functioning of various concepts.
3. Encourage collaborative (Group Learning)Learning in the class.
4. Ask atleast three HOT(Higher order Thinking) questions in the class,which
promotes critical thinking.
5. Adopt Problem Based Learning (PBL),which fosters students’ Analytical skills,
develop design thinking skills such as the ability to design, evaluate, generalize,
and analyze information rather than simply recall it.
6. Introduce Topics in manifold representations.
7. Show the different ways to solve the same problem and encourage the students
to come up with their own creative ways to solve them.
8. Discuss how every concept can be applied to the real world-and when that's
possible, it helps to improve the students' understanding.
9. Use https://pythontutor.com/visualize.html#mode=edit in order to visualize the
operations of C Programs
Module-1 (6 Hours of Pedagogy)

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,

Textbook: Chapter 1.1-1.9, 2.1-2.2, 8.1 - 8.6 ,9.1-9.14


Teaching-Learning Chalk and talk method/Power Point Presentation/ Web Content:
Process https://tinyurl.com/4xmrexre
Module-2 (6 Hours of Pedagogy)

Operators in C, Type conversion and typecasting.


Decision control and Looping statements: Introduction to decision control, Conditional
branching statements, iterative statements, nested loops, break and continue statements,
goto statement.
Textbook: Chapter 9.15-9.16, 10.1-10.6

Teaching-Learning Chalk and talk method/ Power Point Presentation


Process
Module-3 (8 Hours of Pedagogy)
Functions: Introduction using functions, Function definition, function declaration, function call, return
statement, passing parameters to functions, scope of variables, storage classes, recursive functions.
Arrays: Declaration of arrays, accessing the elements of an array, storing values in arrays, Operations on
arrays, Passing arrays to functions, two dimensional arrays, operations on two-dimensional arrays, two-
dimensional arrays to functions, multidimensional arrays, applications of arrays.
Textbook: Chapter 11.1-11.10, 12.1-12.10,12.12
Teaching-Learning Chalk and talk method/ Power Point Presentation
Process
Module-4 (6 Hours of Pedagogy)
Strings and Pointers: Introduction, string taxonomy, operations on strings, Miscellaneous string and
character functions, arrays of strings. Pointers: Introduction to pointers, declaring pointer variables, Types of
pointers, Passing arguments to functions using pointers
Textbook: Chapter 13.1-13.6, 14-14.7
Teaching-Learning Chalk and talk method/Power Point Presentation
Process
Module-5 (6 Hours of Pedagogy)

Structure, Union, and Enumerated Data Type: Introduction, structures and functions, Unions, unions
inside structures, Enumerated data type.
Files: Introduction to files, using files in C, reading and writing data files. , Detecting end of file
Textbook: Chapter 15.1 – 15.10, 16.1-16.5

Teaching-Learning Chalk and talk method/Power Point Presentation


Process
Course Outcomes(Course Skill S et)
At the end of the course the student will be able to:
CO1. Elucidate the basic architecture and functionalities of a computer and also recognize
the hardware parts.
CO 2. Apply programming constructs of C language to solve the real world problem
CO 3.Explore user-defined data structures like arrays in implementing solutions to
problems like searching and sorting
CO 4.Explore user-defined data structures like structures, unions and pointers in
implementing solutions
CO5.Design and Develop Solutions to problems using modular programming constructs
using functions

Programming Assignments

1 Simulation of a Simple Calculator.


2 Compute the roots of a quadratic equation by accepting the coefficients. Print appropriate messages.
3 An electricity board charges the following rates for the use of electricity: for the first 200 units 80 paise per unit:
for the next 100 units 90 paise per unit: beyond 300 units Rs 1 per unit. All users are charged a minimum of Rs.
100 as meter charge. If the total amount is more than Rs 400, then an additional surcharge of 15% of total amount
is charged. Write a program to read the name of the user, number of units consumed and print out the charges.
4. Write a C Program to display the following by reading the number of rows as input,
1
1 2 1
12 3 2 1
12 3 4 3 2 1

nth row
5 Implement Binary Search on Integers.
6 Implement Matrix multiplication and validate the rules of multiplication.
7 Compute sin(x)/cos(x) using Taylor series approximation. Compare your result with the built-in library function.
Print both the results with appropriate inferences.
8 Sort the given set of N numbers using Bubble sort.
9 Write functions to implement string operations such as compare, concatenate, and find string length. Use the
parameter passing techniques.
10 Implement structures to read, write and compute average- marks of the students, list the students scoring above
and below the average marks for a class of N students.
11 Develop a program using pointers to compute the sum, mean and standard deviation of all elements stored in
an array of N real numbers.
12. Write a C program to copy a text file to another, read both the input file name and target file name.
Note:
SEE marks for the practical course is 50 Marks.
SEE shall be conducted jointly by the two examiners of the same institute, examiners are appointed by the
University
All laboratory experiments are to be included for practical examination.
(Rubrics) Breakup of marks and the instructions printed on the cover page of the answer script to be strictly
adhered to by the examiners. OR based on the course requirement evaluation rubrics shall be decided jointly by
examiners.
Students can pick one question (experiment) from the questions lot prepared by the internal /external examiners
jointly.
Evaluation of test write-up/ conduction procedure and result/viva will be conducted jointly by examiners.
General rubrics suggested for SEE are mentioned here, writeup-20%, Conduction procedure and result in -60%,
Viva-voce 20% of maximum marks. SEE for practical shall be evaluated for 100 marks and scored marks shall be
scaled down to 50 marks (however, based on course type, rubrics shall be decided by the examiners)
Students can pick one experiment from the questions lot with equal choice to all the students in a batch. Student
should develop an algorithm, program, execute and demonstrate the results with appropriate output for the given
problem.
Change of experiment is allowed only once and 15% Marks allotted to the procedure part to be made zero.
The duration of SEE is 02 hours
Assessment Details (both CIE and SEE)
The weightage of Continuous Internal Evaluation (CIE) is 50% and for Semester End Exam (SEE) is 50%. The
minimum passing mark for the CIE is 40% of the maximum marks (20 marks out of 50). The minimum passing
mark for the SEE is 35% of the maximum marks (18 marks out of 50). A student shall be deemed to have
satisfied the academic requirements and earned the credits allotted to each subject/ course if the student secures
not less than 35% (18 Marks out of 50) in the semester-end examination(SEE), and a minimum of 40% (40
marks out of 100) in the sum total of the CIE (Continuous Internal Evaluation) and SEE (Semester End
Examination) taken together.
Continuous Internal Evaluation(CIE):
Two Unit Tests each of20 Marks (duration 01 hour)
 First test after the completion of 30-40 % of the syllabus
 Second test after completion of 80-90% of the syllabus
One Improvement test before the closing of the academic term may be conducted if necessary. However best two
tests out of three shall be taken into consideration.
Two assignments each of 10 Marks
The teacher has to plan the assignments and get them completed by the students well before the closing of the
term so that marks entry in the examination portal shall be done in time. Formative (Successive) Assessments
include Assignments/Quizzes/Seminars/ Course projects/Field surveys/ Case studies/ Hands-on practice
(experiments)/Group Discussions/ others. . The Teachers shall choose the types of assignments depending on
the requirement of the course and plan to attain the Cos and POs. (to have a less stressed CIE, the portion of
the syllabus should not be common /repeated for any of the methods of the CIE. Each method of CIE should
have a different syllabus portion of the course). CIE methods /test question paper is designed to attain the
different levels of Bloom’s taxonomy as per the outcome defined for the course.
The sum of two tests, two assignments, will be out of 60 marks and will be scaled down to 30 marks
CIE for the practical component of the Integrated Course
 On completion of every experiment/program in the laboratory, the students shall be evaluated and marks
shall be awarded on the same day. The15 marks are for conducting the experiment and preparation of
the laboratory record, the other 05 marks shall be for the test conducted at the end of the semester.
 The CIE marks awarded in the case of the Practical component shall be based on the continuous
evaluation of the laboratory report. Each experiment report can be evaluated for 10 marks. Marks of all
experiments’ write-ups are added and scaled down to 15 marks. 
 The laboratory test (duration 02/03 hours) at the end of the 14th /15th week of the semester /after
completion of all the experiments (whichever is early) shall be conducted for 50 marks and scaled down
to 05 marks.
Scaled-down marks of write-up evaluations and tests added will be CIE marks for the laboratory component of
IPCC for 20 marks.
Semester End Examination (SEE):
SEE for IC
Theory SEE will be conducted by University as per the scheduled time table, with common question papers
for the course (duration 03 hours)

1. The question paper will have ten questions. Each question is set for 20 marks.
2. There will be 2 questions from each module. Each of the two questions under a module (with a
maximum of 3 sub-questions), should have a mix of topics under that module.
3. The students have to answer 5 full questions, selecting one full question from each module.
The theory portion of the Integrated Course shall be for both CIE and SEE, whereas the practical
portion will have a CIE component only. Questions mentioned in the SEE paper shall include
questions from the practical component).

Passing standard:

 The minimum marks to be secured in CIE to appear for SEE shall be 12 (40% of maximum marks-
30) in the theory component and 08 (40% of maximum marks -20) in the practical component. The
laboratory component of the IPCC shall be for CIE only. However, in SEE, the questions from the
laboratory component shall be included. The maximum of 04/05 questions to be set from the
practical component of IPCC, the total marks of all questions should not be more than 30 marks.
 SEE will be conducted for 100 marks and students shall secure 35% of the maximum marks to
qualify for the SEE. Marks secured will be scaled down to 50.

Suggested Learning Resources:

Textbooks
1. Computer fundamentals and programming in c, “Reema Thareja”, Oxford University, Second edition,
2017.
Reference Books:
1. E. Balaguruswamy, Programming in ANSI C, 7th Edition, Tata McGraw-Hill.
2. Brian W. Kernighan and Dennis M. Ritchie, The ‘C’ Programming Language, Prentice Hall of India.
Web links and Video Lectures (e-Resources):
1. elearning.vtu.ac.in/econtent/courses/video/BS/15PCD23.html
2. https://nptel.ac.in/courses/106/105/106105171/ MOOC courses can be adopted for more clarity in
understanding the topics and verities of problem solving methods.
3. https://tinyurl.com/4xmrexre
Activity Based Learning (Suggested Activities in Class)/ Practical Based learning
 Quizzes
 Assignments
 Seminars
PRINCIPLES OF PROGRAMMING USING C
22POP13/23

MODULE-1
INTRODUCTION TO COMPUTERS
INTRODUCTION TO C LANGUAGE
 ‘C’ is a structured programming language.
 It is considered as high- level language because it allows the programmer to
concentrate on the problem and not worry about the machine that the program
will be using.
 ‘C’ is a machine independent language i.e it can be run on many different
hardware platforms.
 ‘C’ language is developed by Dennis Ritchie in 1972.
 It has inherited many concepts from ALGOL[ Algorithmic Language], BCPL [
Basic Combined Programming Language] and ‘B’.
 Concepts of datatypes were also introduced into ‘C’ language.
 In 1983, the ANSI[ American National Standard Institute] began the definition
of a standard for C.
 In 1990, the ISO[ International Standard Organization] adopted ANSI standard.

Program development is a multistep process which requires steps like understanding the
problem, developing a solution, writing the program and testing it.
There are three tools to develop the solution
 Pseudo code
 Flowchart
 Algorithm
Pseudo code:
 It is an outline of the program that is expressed in a formally styled natural
language. It expresses the design in detail.
 It is a restatement of the problem as a list of steps in English like format,
describing what must be done to solve the problem.
 It is not a programming language but informal way of describing a program and
it does not require strict syntax.
 It consists of statements which are a combination of English and C.
 Using the pseudo code, a programmer then writes the actual program.
 Pseudo code to perform addition of two number
Begin
input a,b
sum=a+b
print sum
End

Algorithm
1. A logical and concise list of steps required to solve a problem is called algorithm.
2. The representation of the various steps involved in solving problem is called
algorithm.
3. Points for developing an algorithm
 Name of the algorithm
 Step number
 Explanatory statement following the step number
 Termination

Example:

Algorithm to perform addition of 2 numbers


Algorithm: To find sum of 2 number
Step 1:Start
Step 2: [input the values of a and b]
Read a,b
Step 3:[ find the sum]
sum<-a+b
Step 4:[output the result]
print sum
Step 5:[finished]
Stop

Flowchart
A flowchart is a pictorial representation of an algorithm.
Benefits of using flowcharts are
 Being a pictorial representation they are easier to understand.
 We can review our logic and debug the program with the help of flowcharts.
 Easy to explain a program or discuss the solution.
 It separates the logic development and program syntax.
Example:
BASIC STRUCTURE OF C PROGRAMS

Structure of C Program:

1. PREPROCESSOR DIRECTIVES
2. GLOBAL DECLARATIONS
3. VOID MAIN()
4. {
5. LOCAL DECLARATIONS
6. STATEMENTS
7. }
8. COMMENTS
a. BLOCK /*--------------------*/
b. LINE //

PREPROCESSOR DIRECTIVES
 Every C program is made of one or more preprocessor commands.
 This command is present in the beginning of the program
 All the preprocessor commands starts with a pound sign[#].
 The preprocessor directives are the special instructions that tells the compiler
about what libraries have to be included in the program.
Ex: #include<stdio.h>
The above command tells the compiler to include the standard
input/output library file to the program.
Where, # is pound sign
include is a keyword used to include library files
stdio is standard input/output library
.h is header file
 Some of the preprocessor directive given below
#include<conio.h> this is to include console input/output library
functions.
#include<math.h> this is to include mathematical library functions.
#include<string.h> this is to include string library functions.

MAIN()
 The executable part of the program begins with the main() function.
 Ex: void main()
void : says that the function doesn’t return any value to the operating
system
main: is the function name.
 Note: there should be no semicolon after the function header.
 All the functions in the program are divided into 2 parts:
1. Declaration section: it describe the data that we are using in the
function. It is also called as local declaration.
2. Statement section: it contains the instruction to perform specific
task such as reading input, printing output etc.
 The function main starts with an open brace ‘{‘ and terminates with a close
brace ‘}’.

GLOBAL DECLARATIONS
 It includes the variables that are used in more than one function.
 The variable declared here are visible to all parts of the program
 The global variables are declared after preprocessor directives and before main.

COMMENTS
 They help the readers to place some program documentations
 The compiler ignores the comments when it translates the program to
executable code.
 There are two different formats of comment
1. Block comment
A block comment is used when the comment has several
lines .
Syntax: /*-----------------*/
Everything between the token is ignored by compiler.
2. Line comments
The line comment is used when the comment has only one
line i.e for short comments.
It uses two slashes(//). This format does not require an end-
of-comment token.
EXAMPLE

WRITE A C PROGRAM TO ADD TWO NUMBER


#include<stdio.h>
void main()
{
int a=5,b=6,sum;
sum=a+b;
printf(“sum=%d\n”,sum);
}
or
#include<stdio.h>
main()
{
int a,b,sum;
scanf(“%d%d”,&a,&b);
sum=a+b;
printf(“sum=%d\n”,sum);
}

EXECUTING A ‘C’ PROGRAM Do from mam notes


C TOKENS
A token refers to the smallest unit of a C program.
The following are the C tokens:
 Keywords
 Identifiers
 Constants
 Operators
 Special symbols

KEYWORDS
Keywords are the tokens which have predefined meaning in C language used to
perform a specific task.
 They are also known as reserved word
 All keywords should be written in lower case. 32 keyword in c
 Ex: if, else, for, while, int, void, char etc..

IDENTIFIERS
Identifiers are the names given to the various program elements such as variable,
constants, function, array names etc…
 The rules for identifiers are as follows:
1 . First character must be alphabets or underscore
Ex: a, name , _a
2 . Identifiers must consists only of alphabets, digits or underscore, where as special
symbols and blank spaces are not allowed.
Ex: a1 , student_name
3 . Cannot duplicate a keyword or reserved word.
Ex: int , void, char etc cannot be used as a identifier.
4 . First 63 characters of an identifier are significant.
Ex: if the identifier is more then 63 characters, then only first 63 characters are used.
5 . Two successive underscores are not allowed.
Ex: student_name : valid
studen_ _name : invalid
6 . C is a case-sensitive language.
Ex : sum , SUM
Both the names are considered as different identifiers in the program.

CONSTANTS

Constants are the data values that cannot be changed during the execution of a
program.
 These are classified into:
 Boolean constants
 A Boolean data type can take only two values: true[1] and
false[0].
 If we want to use Boolean datatype in the program then we must
include the Boolean library stdbool.h
 Character constants
 Character constants are enclosed within single quotes[‘ ’]
 Ex:’a’ , ‘1’ etc
 When a backslash [\] is used before the character then that
backslash is known as the ‘escape character’.
 The escape character says that what follows is not the normal
character but it has some special meaning.
 Even though they look like 2 characters , they represent only one.
 The escape characters are normally used in printf statement to
format the output.
 Ex: ‘n’
 \n-newline
 \t-horizontal tab
 \v-vertical tab
 \b-backspace
 \0-null
 \a-alert
 \f-formfeed
 \r-carriage return
 \”
 \’
 \?
 \\
 String constants
A string constants is a sequence of zero or more characters enclosed in
double quotes[“ “].
Ex: “h”, “hello”, “ “this refers as empty string.
 Integer constant
 An integer is a whole number without any fraction part.
 When we initialize a integer number with the type int, by default
the number is coded as signed integer.
 So we can override this by using symbol after the number
 Unsigned: u or U
 Long: l or L
 Long long: ll or LL
 Real constant
 The default type of real constant is double.
 If we want the resulting data to be float or long double, we can
override this by using desired symbols after the number.
 Float: f or F
 Long double: l or L
 Complex constants
 They are coded as 2 parts: real and imaginary separated by + sign.
 Real part: is coded as a real format rules.
 Imaginary part: is coded as a real number multiplied with
imaginary constant [I].
 To use the imaginary constant, we have to include complex.h
header file
 Both real and imaginary parts should be of same type.

CODING CONSTANTS
There are three ways to code/define constants in program
 Literal constant
 A literal is an unnamed constant used to specify data.
 If there is some data that cannot be changed in the program, then
we can simply code the data value itself in a statement.
Ex: a=b+5;
 Defined constant
 Another way to designate a constant is to use the preprocessor
command “#define”.
 The define commands are usually placed at the beginning of the
program.
Ex: #define Pi 3.14
main()
{
A=b*Pi
}
 In program whenever it finds Pi, it is replaced by value
3.142
 Memory constant
It uses C type qualifier “const” to indicate data cannot be changed.
Syntax: const type identifier=value;
Ex: const float cpi=3.14;
It is same as literals, but we are giving a symbolic name to it.
Usually to represent the constant variable we prefix ‘c’ with the variable
name.

Example program:
#include<stdio.h>
#define PI 3.1416 // define constant
void main()
{
const float cpi=3.1416; //memory constant
printf(“ literal constant:%f\n”,3.1416); //literal constant
printf(“ defined constant:%f\n”,PI);
printf(“memory constant:%f\n”cpi);
}
Output:
literal constant:3.141600
defined constant:3.141600
memory constant:3.141600
VARIABLES
 Variables are named memory locations that have a type such as integer or
character etc
 Variable declaration and defined
o Declaration: used to name an object.
o Definition: used to create an object. It reserves memory for variables.
 Syntax: data_type variable_list;
 Ex: int a,b;
 Variable initialization/assignment
o The process of assigning a value to a variable is called as initialization of a
variable.
o Syntax: variable_name=value;
o Ex: a=10;
 We can initialize a variable at the same time when we declare it by including an
initializer.
o Ex: int a=10;
o Char c=‘a’;

INPUT/ OUTPUT FUNCTIONS


 I/O types
o Formatted I/O
 Input function- scanf()
 Output function- printf()
o Unformatted I/O
 Input functions
 getch()
 getche()
 gets()
 getchar()
 Output functions
 putch()
 putche()
 puts()
 putchar()

OUTPUT FORMATTING: PRINTF()


 The printf function converts data stored in the program into text stream for output to
the monitor.

 Syntax: printf(“format control string”,list of variables);


 the parameter passed to printf function are
o Format control string which includes:
 Textual data to be inserted into the text stream
 Contains zero or more “conversion specifications”
 Contains control characters[escape characters]

Ex:

Conversion specification for printf function

% Flag Minimum precision size code


width
 %: start token
 Code: ex:%d, %c, %s, %f
 Size: h[%hd], l[%ld], ll[%lld], L[%Lf]
 Minimum width: used to specify the minimum number of positions in the output.
 Precision:
It is used for floating point number. It specifies the number of decimal places to
be printed.[.m]
If no precision is specified, then the printf() function prints six decimal positions.
o Ex: printf(“%.2f”,3.1427); //output: 3.14
 printf(“%f”,3.1427); //output: 3.142700
 Flag: there are 3 flags:
o justification
Controls the placement of value when it is shorter than the specified width.
 Right justification: by default, values are right justified if there is no
flag.
 Ex: printf(“%6.2f”,1.2);

 Left justification: we use (-) minus sign to left justify a value.


 Ex: printf(“%-6.2f”,1.2);

o Padding : defines the character that fills the unused space when the value is
smaller than the print width. There are two ways of padding
 Space: by default, if there is no flag, the unused width is filled with
white spaces.
 Zero: if the flag is 0, then the unused width is filled with zeros.
The zero flag is ignored if it is used with left justification because
adding zeros after a number changes its value.
 print(“%-06.3f”,1.2568498);

o Sign flag: defines the use or absence of a sign in a numeric value. there are
three formats:
 Default formatting: inserts a sign only when the value is negative.
Positive values are formatted without a sign.
 Ex: int a=10,b=-5;
 printf(“%d”,a); //10
 printf(%d”,b); //-5
 Print signed values: when the flag is set to plus(+), then signs are
printed for both positive and negative values.
 Ex: int a=10,b=-5;
 printf(“%+d”,a); //+10
 printf(“%+d”,b); //-5
 Prefix positive values with a leading space: if the flag is a space, the
positive numbers printed with a leading space and negative numbers with
a minus sign.
 Ex: int a=10,b=-5;
 printf(“% d”,a); // 10
 printf(“% d”,b); //-5
 Ex: printf(“%-0+6.2Lf”,23.324);
Note:Explain each flag. Output is +23.32

INPUT FORMATTING: SCANF()


 It converts the text stream given from the keyboard into values and stores it in
program variables.

 Syntax: scanf(“format control string”,address list);

 scanf(“ %c”,&ch);
 the scanf function is reverse of printf function
 a format control string describes the data to be extracted from the stream
and reformatted
 rather than data values as in the printf function, scanf requires the
variable addresses where each piece of data are to be stored.
 It uses “&”[ampersand] i.e with reference to the memory location
 With the exception to the character specification, the whitespaces are
discarded.
o Ex: scanf(“%d %d”,&a,&b);
 Any non conversion specification character in the format control string
must be exactly matched by the next characters in the input stream.
 Extra characters in the control string can be of two categories
• Non-whitespace characters:
o the non- whitespace character in the control
string must exactly match characters entered by
the user and are discarded by the scanf after
they are read.
o If they don’t match, then scanf goes into an
error state and program must be manually
terminated.
o Ex: if the users want to enter date with slashes
such as 20/12/22, then the scanf function is
scanf(“%d/%d/%d”,&dd,&mm,&yy);
• White space characters:
o The white space characters in the format
control string are matched by zero or more
whitespace characters in the input stream and
discarded.
o Either of the below format can be used to code
white space character in scanf function “ %c”
or “% c”.
o So we must give spaces while writing scanf
statements
o Ex: scanf(“%c %c %d”,&a,&b,&c);

Conversion specification for scanf function

 There are only three optional modifier between the % and conversion code for input
formatting.
 There is no precision in an input conversion specification. It is an error to include a
precision. If scanf finds precision it stops processing.
 There is only one flag for input formatting
o *: assignment suppression
o The assignment suppression flag tells scanf that the next input field is to be
read but not stored. Sinve it is discared.
o Ex: scanf(“%d%c%*f”);
o In the above example, the scanf statement reads an integer, a character and a
floating-point number from the input stream. The floating-point number is read
and discarded. Whereas the other fields are read, formatted and stored.
 Maximum width:
o it specifies the maximum number of characters that are to be read.
o When width specification is included, scanf reads until the maximum
number of characters has been processed or until scanf finds a
whitespace character.
o If scanf finds a white space character before the maximum width is
reads, it stops.

UNFORMATTED INPUT/OUTPUT

 This function works with character datatype[char]


getchar() and putchar()
 Syntax:
char ch;
ch=getchar(); // reads a single character from the keyboard and store it
into the specified variable.
putchar(ch); //displays the character i.e stored in the specified variable.
 Ex:
#include<stdio.h>
void main()
{
char ch;
ch=getchar();
putchar(ch);
}
gets() and puts()
 Syntax:
char str1[10];
gets(str1); // reads a line of string including spaces until a newline is read
i.e gets stops reading characters from keyboard only when the enter key is pressed.
Puts(str1); // display a string and appends a newline character [\n] to it.

Sample Programs
Write a C Program to add two numbers.
#include<stdio.h>
void main() //program to add two numbers
#include <stdio.h>
{ void main()
int a,b,c; {
printf("\n Enter two numbers"); int a,b,sum;
printf("Enter the two number:");
scanf("%d%d",&a,&b); scanf("%d%d",&a,&b);
c=a+b; sum=a+b;
printf("The Sum=%d",sum);
printf("\n Sum=%d\n",c); return 0;
} }
OUTPUT
Enter the two number:55
8
The Sum=63
OUTPUT
Enter the two number:10
2
The sum =12
Write C Program to demonstrate the use of arithmetic operators The sub=8
The mul=20
#include<stdio.h> The div=5
void main() //program to The mol=0
{ #include <stdio.h>
void main()
int a,b; {
printf("\n Enter two numbers\n"); int a,b;
scanf("%d%d",&a,&b); printf("Enter the two number:");
scanf("%d%d",&a,&b);
printf("\n Sum=%d",(a+b)); printf("The sum =%d\n",a+b);
printf("\n diff=%d",(a-b)); printf("The sub=%d\n",a-b);
printf("\n product=%d",(a*b)); printf("The mul=%d\n",a*b);
printf("The div=%d\n",a/b);
printf("\n quatient=%d",(a/b)); printf("The mol=%d\n",a%b);
printf("\n remainder=%d",(a%b)); return 0;
}
}

Write a C Program to display the ASCII value of given character


#include<stdio.h> Enter the character:A
void main() The ASCII value of A=65
//program to find ASCII value
{ Enter the character:a #include <stdio.h>
The ASCII value of a=97 void main()
char c; {
int a; char ch;
printf("\n Enter a character"); int a;
printf("Enter the character:");
scanf("%c",&c); scanf("%c",&ch);
a=c; a=ch;
printf("The ASCII value of %c=%d",a,ch);
printf("\n ASCII value of %c=%d",a,c); return 0;
} }

Write a C program to swap two numbers.


#include<stdio.h>
void main() Enter the two number5
{ 4
int a,b,temp; The number after swamping
a=4
printf(“enter two number\n”); b=5
scanf(“%d%d”,&a,&b);
printf(“the a =%d\t b=%d before swapping\n”,a,b);
temp=a;
a=b;
b=temp;
printf(“a=%d \t b=%d after swapping\n”,a,b);
}
Write a c program to compute area of circle.
#include<stdio.h>
void main()
{
int area,r;
printf(“enter the radius\n”);
scanf(“%d”,&r);
area=3.14*r*r;
printf(“the area of circle is=%d\n”,area);
}

Write a C program to swap two numbers without using temp variable.


#include<stdio.h> //program to find area of circle and circumference
void main() #include <stdio.h>
{ #define PI 3.142
int main()
int a,b,temp; {
printf(“enter two number\n”); float r,area,circum;
printf("Enter the Radius:");
scanf(“%d%d”,&a,&b); scanf("%f",&r);
a=a+b; area=PI*r*r;
b=a-b; circum=2*PI*r;
printf("\nThe Area =%.3f \nand The
a=a-b; circumferance =%.3f",area,circum);
printf(“a=%d \t b=%d after swapping\n”,a,b); }
Enter the Radius:5
} The Area =78.550
and The circumferance
=31.420
 Write a C program to find the area and circumference of circle
 Write a C program to find the area of equilateral triangle
 Write a C program to print an integer.
 Write a C program to multiply two floating-point number
/* Calculate simple interest */
 Write a c program to find ASCII value of a character. SI = (principle * time * rate) /
 Write a C program compute quotient and remainder 100;
 Write a C program to find the Simple interest
 Write a C program to find the Celsius to Fahrenheit // fahrenheit = ((9/5) * celsius) + 32;
// fahrenheit = ((1.8 * celsius) + 32;
 Write a C program to find the Fahrenheit to Celsius

celsius = (fahrenheit - 32) * 5 / 9;


#include <stdio.h> //celsius = 5 *(fahrenheit - 32) / 9;
int main() { //celsius =(fahrenheit-32) * 0.55556;
//program to mul two floating int dividend, divisor, quotient,
point no.#include <stdio.h> remainder;
int main() { printf("Enter dividend: ");
double a, b, product; scanf("%d", &dividend);
printf("Enter two numbers: "); printf("Enter divisor: ");
scanf("%lf %lf", &a, &b); scanf("%d", &divisor);

// Calculating product // Computes quotient


product = a * b; quotient = dividend / divisor;

// %.2lf displays number up to // Computes remainder


2 decimal point remainder = dividend % divisor;
printf("Product = %.2lf",
product); printf("Quotient = %d\n", quotient);
printf("Remainder = %d", remainder);
return 0; return 0;

You might also like