Module1 Part 2 Notes
Module1 Part 2 Notes
Introduction to C
• Most of the modern languages are derived from C including C++, Java, PHP, Javascript,
Python, Perl etc.
History of C
Characteristics of C
• C is a robust language whose rich set of built-in functions and operators can be used to
write complex programs.
• Small size - C has only 32 keywords. This makes it relatively easy to learn as compared
to other languages.
• Structured language as the code can be organized as a collection of one or more
functions.
• Facilitates low level (bitwise) programming.
• Supports pointers to refer computer memory, array, structures, and functions.
VCET,Puttur. Page 1
Principles of Programming using C 22POP13 [Module 1- Part 2]
• C is a core language as many other programming languages (such as C++, Java, or Perl)
are based on C. If one knows C, learning other computer languages becomes much easier.
• It is a quick language. Since C programs make use of operators and data types, they are
fast and efficient.
• C is a portable language, a C program written for one computer can be run on another
computer with little or no modification.
• C is an extensible language as it enables the user to add his/her own functions to the C
library.
Uses of C
• C language is primarily used for system programming. Used for implementing operating
systems and embedded system applications.
• C is used in implementation of compilers and interpreters of other programming
languages.
• C is widely used to implement end-user applications, such as browsers for internet,
development of video games, Graphical User Interface.
Structure of a C Program
Documentation section
Link section
Definition section
Global declaration section
main( ) function section
{
Declaration part
Executable part
}
Subprogram section
Function 1
Function 2
.
. (user-defined functions)
.
.
Function n
Documentation section
The documentation section is the part of the program where the programmer gives the details
associated with the program. He usually gives the name of the program, the details of the author
and other details like the time of coding and description. This is done by using the set of
comment lines.
VCET,Puttur. Page 2
Principles of Programming using C 22POP13 [Module 1- Part 2]
VCET,Puttur. Page 3
Principles of Programming using C 22POP13 [Module 1- Part 2]
Sub-program section
If the program is a multi-function program, then the subprogram section contains all 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.
Example program
//Program to calculate area and circumference of circle
#include <stdio.h>/*link section with preprocessor directive*/
#define PI 3.14 /* definition section */
float area, circumference; /*global declaration section*/
void main()
{
float r; /*local declaration part*/
printf("Enter the radius of the circle\n"); /*executable part starts here*/
scanf("%f",&r);
area=PI*r*r;
circumference=2*PI*r;
printf("Area of the circle is %f\n",area);
printf("Circumference of the circle is %f\n”,circumference);
}
SAMPLE PROGRAMS
1.Write a program to find area of a triangle when all sides are given.
#include <stdio.h>
#include<math.h>
void main()
{
float a,b,c,s,area,perimeter;
printf("Enter values of sides of triangle\n");
scanf("%f%f%f",&a,&b,&c);
VCET,Puttur. Page 4
Principles of Programming using C 22POP13 [Module 1- Part 2]
s = (a + b + c) / 2;
area = sqrt(s * (s - a) * (s - b) * (s - c));
printf("Area is %f\n",area);
printf(“perimeter of triangle is %f\n”,s);
}
2. Write a C Program to find area and perimeter of rectangle
#include <stdio.h>
void main()
{
float l, b, area,perimeter;
printf("Enter length and width of Rectangle\n");
scanf("%f%f", &l, &b);
area = l* b;
perimeter = 2*(l + b);
printf("Area of Rectangle is %f\n",area);
printf(" Perimeter of Rectangle is %f\n", perimeter);
}
Output:
Enter length and width of Rectangle
20 10
Area of Rectangle is 200
Perimeter of Rectangle is 60
3. C program which takes as input p, t, r computes the simple interest and display the
result.
#include<stdio.h>
void main()
{
float p,t,r,si;
printf(“Enter the value of p, t and r\n”);
scanf(“%f %f %f”,&p,&t,&r);
si = p*t*r/100;
printf(“The value of Simple Interest is %f\n”,si);
}
Output:
Enter the value of p,t and r
1000 1 10
The value of Simple Interest is 100.000000
VCET,Puttur. Page 5
Principles of Programming using C 22POP13 [Module 1- Part 2]
VCET,Puttur. Page 6
Principles of Programming using C 22POP13 [Module 1- Part 2]
}
Output:
Enter the temperature in Fahrenheit
50
Tempertaure in celsius is 10.000000
Header Files:
They have an extension '.h'. These files contains declarations and definitions for library functions
(predefined functions / built-in functions) and macro definitions.
• Examples of these standard header files include the following:
Object Files
Object files are generated by the compiler as a result of processing the source code file. They
contain binary code. Object Files have a ‘.o’ or ‘.obj’ extension.
Executable file :
This file is generated by the linker. Various object files are linked by the linker for producing a
binary file which will be executed directly. They have an '.exe' extension.
VCET,Puttur. Page 7
Principles of Programming using C 22POP13 [Module 1- Part 2]
• The programming process starts with creating a source file that consists of the statements
written in C language. This source file can be produced with a text editor such as
Windows notepad.
VCET,Puttur. Page 8
Principles of Programming using C 22POP13 [Module 1- Part 2]
C Tokens
• In a C program the smallest individual units are known as C tokens.
• C has six types of tokens as given below.
• C programs are written using these tokens and the syntax of the language.
• Tokens are classified as:
Keywords
Identifiers
Constant
Operators
Strings
Special Characters
Keywords
VCET,Puttur. Page 9
Principles of Programming using C 22POP13 [Module 1- Part 2]
Identifiers
• Identifiers are basically the names given to program elements such as variables, arrays,
and functions.
• They may consist of an alphabet, digit, or an underscore.
• Example:
age_pers : to store the age of the person
name3 : to store the name of the person
salary : to store the salary of the employee
sum() : to calculate the sum
Rules for Forming ldentifier Names
• It cannot include any special characters or punctuation marks (e.g., #, S, ^, ?, ., etc.)
except the underscore.
• The identifier name must begin with an alphabet or an underscore.
• There cannot be two successive underscores.
• Keywords cannot be used as identifiers.
• They are case sensitive. For example, FIRST is different from 'first' and 'First'.
• It should not contain white space.
• Only 31 characters are significant.
VCET,Puttur. Page 10
Principles of Programming using C 22POP13 [Module 1- Part 2]
Data types
• Definition: It is the type of data value that is stored in particular memory location.
• Data types are used to classify the values as Integer, Real, Character,etc.
Primitive data types:
• Primitive data types are most fundamental data types which cannot be decomposed
further into simpler ones.They are also known as basic or built-in data types.
• C language provides following basic data types(Primitive data types).
• C language supports 4 basic data types:
1)integer data type 2)floating point data type 3)character data type 4)void
VCET,Puttur. Page 11
Principles of Programming using C 22POP13 [Module 1- Part 2]
• Unsigned integers use all the bits for the magnitude of the number and are always
positive.
• We declare long and unsigned integers to increase the range of values.
Table lists the data type, their size, range, and usage for a C programmer on a 16-bit computer.
• This represents the number with fractional part i.e., real numbers such as 1.8, 4.5, 12e-5
and -9.66. It can also be both positive and negative.
• Float is allocated 4 bytes (32 bits) of memory space with 6 digits of precision.
• A double data type number uses 64 bits giving a precision of 16 digits.
• To extend the precision further, We may use long double which uses 80 bits.
VCET,Puttur. Page 12
Principles of Programming using C 22POP13 [Module 1- Part 2]
VCET,Puttur. Page 13
Principles of Programming using C 22POP13 [Module 1- Part 2]
✓ Declaration of variables
Declaration does two things:
• It tells the compiler what the variable name is.
• It specifies what type of data the variable will hold.
The declaration of variables must be done before they are used in the program.
• The syntax for declaring a variable is a s follows:
datatype v1,v2,….vn;
v1, v2,….., vn are the names of variables. Variables are separated by commas. A
declaration statement must end with a semicolon.
Example: int a, avg, sum;
char ch;
✓ Initializing Variables
• While declaring the variables, we can also initialize them with some value. The process
of giving initial values to variables is called initialization.
For example,
int emp_num = 7;
float salary = 5000 ;
char grade = 'A';
• C permits initialization of more than one variable in one statement using multiple
assignment operators.
• E.g.: p = q = s = 0;
• Above statement initializes the variables p, q, and s to zero.
VCET,Puttur. Page 14
Principles of Programming using C 22POP13 [Module 1- Part 2]
• When the variable is declared outside all functions, it is known as a global variable.
Constants
• Constants in C refer to fixed values that do not change during the execution of a program.
1. Integer constants
• Integer constants are the numeric constants without any fractional part or exponential
part. There are three types of integer constants
ii) An octal integer constant consists of any combination of digits from the set 0 through 7, and
begins with digit 0. Examples: 037, 0, 0435, 0551
iii) Hexadecimal integer is a sequence of digits which begins with 0x or 0X. Contains digits
from 0-9 and alphabets A through E. The alphabets A through F represent numbers 10 through
15. Examples: 0X2, 0x9F, 0x67
2. Floating-point constants
• Also called as Real constants.
• A floating point constant consists of an integer part, a decimal point, a fractional part,
and an exponent field containing an e or E (e means exponent) followed by an integer
• For example: -2.0, 0.000234 and -0.22e-5
• It is not necessary that every floating point constant must contain all these parts.
• A floating point constant can be of
VCET,Puttur. Page 15
Principles of Programming using C 22POP13 [Module 1- Part 2]
Double Precision (more than 6 digits after decimal point (16 digits)) Examples
4.12300045 -23.4561230 +3.1415927
For example, the value 215.65 may be written as 2.1565e2 in exponential notation. e2 means
multiply by 102. The general form is: Mantissa e exponent
The mantissa is either a real number expressed in decimal notation or an integer. The exponent
is an integer number with an optional plus or minus sign. The letter e separating the mantissa and
the exponent can be written in either lowercase or uppercase.]
4. String Constants
• A string constant is a sequence or group of characters enclosed in double quotes. The
characters may be letters, numbers, special characters and blank space.
• Examples: "Hello!", "1987”, “WELL DONE", “2+4”
• A character constant (e.g., ‘X’) is not equivalent to the single character string constant
(e.g. “X”).
Declaring constants
• Constants can be identifiers whose value does not change. To declare such a constant,
precede the normal variable declaration with const keyword and assign it a value.
#define PI 3.14
INPUT/OUTPUT STATEMENTS IN C
VCET,Puttur. Page 16
Principles of Programming using C 22POP13 [Module 1- Part 2]
• In a text stream, sequence of characters is divided to into lines with each line being
terminated with a new-line character (\n).
• A binary stream contains data values using their memory representation.
• We can do input/output from the keyboard/monitor or from any file.
• We assume that the source of data is the keyboard and destination of the data is the
monitor as in figure 2.
Formatting Input/Output
• C language supports two formatting functions printf and scanf.
• printf is used to convert 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.
• Similar to printf and scanf, there are different functions in C that can carry out the
input/output operations. These functions are collectively known as standard
Input/Output(I/O) Library. A program that uses standard I/0 functions must contain the
statement
#include <stdio.h>
at the beginning of the program.
printf()
• Used to display information in user required format.
• It provides features that are used control alignment and spacing of output produced by the
program.
• Letter f in printf stands for formatting.
VCET,Puttur. Page 17
Principles of Programming using C 22POP13 [Module 1- Part 2]
• Each format specifiers must begin with a % sign and it follows the following
parameters:
1.Flags specify output justification. It is a optional second character used in control
string. The following are different types of flags:
0 The number is left padded with zeros.
- The output is left justified.
+ This character is used to have sign.
#(with o or x) This character is used to have prefix 0 in octal numbers and to have
prefix 0x in hexadecimal numbers.
2.Width: It specifies the minimum number of positions in the output. If data needs
more space than specified, then printf overrides the width specified by the user.
EXAMPLES
1. If x=4568 for all below printf( )
VCET,Puttur. Page 18
Principles of Programming using C 22POP13 [Module 1- Part 2]
4.
.
5.
VCET,Puttur. Page 19
Principles of Programming using C 22POP13 [Module 1- Part 2]
scanf ()
• The function scanf () stands for scan formatting
• It is used to read formatted data from the keyboard.
• This function takes a text stream from the keyboard and formats data from the stream
according to a format control string and then stores the data in specified program
variables.
Syntax: scanf(“control string”, &var1,&var2….&varn);
• The control string specifies the type and format of the data that has to be obtained from
the keyboard
• &var1, &var2…. refers to address of variables where data is stored.
The following are format specifiers used in control string
[Note: Given below are some of the general points to keep in mind while writing a scant
statement.
• All function arguments, must be pointers to variables.
• Format specifications contained in the control string should match the arguments in
order.
• Input data items must be separated by spaces and must match the in the same order.
• The reading will be terminated, when scanf encounters a 'mismatch' of data.
VCET,Puttur. Page 20
Principles of Programming using C 22POP13 [Module 1- Part 2]
• Any unread data items in a line will be considered as part of the data input line to the
next scanf call.
• When the field width specifier w is used, it should be large enough to contain the
input data size.]
• The design and development of correct, efficient, and maintainable programs depends on
the approach adopted by the programmer to perform various activities that need to be
performed during the development process.
• The entire program or software (collection of programs) development process is divided
into a number of phases where each phase performs a well-defined task.
• The diagram shows the phases in software development life cycle
• Requirements Analysis : In this phase , the user’s expectations are gathered and all the
gathered requirements are analysed.
• The last activity in this phase involves documenting every identified requirement of the
user.
• Design : The requirement documented in the previous phase act as the input to the design
phase. In this phase, a plan of actions is made.
The core structure of the software or program is broken down in to modules. The solution
of the program is then specified for each module in the form of algorithms or flowcharts.
• Implementation : In this phase, the designed algorithms are converted in to program
code using any of the high level languages.
The program codes are tested by the programmer to ensure their correctness.
• Testing: In this phase, all the modules are tested together to ensure that the overall
system works well as a whole product.
In this phase, the software is tested using a large number of varied inputs, also known as
test data, to ensure that the software is working as expected by the user’s requirements.
• Software deployment training and support : In this phase the, software is installed or
deployed into the production environment and then the training is given to the user how
to use the product.
• Maintenance : In this phase, activities that are done to cope with newly discovered
problems or new requirements. Such activities may require for the addition of new code
to fix newly discovered problems.
VCET,Puttur. Page 21
Principles of Programming using C 22POP13 [Module 1- Part 2]
Following are the design tools used to develop the solution for the given problem:
✓ Algorithms
✓ Flow charts
✓ Control Structures used in algorithm
✓ Pseudo codes
1.Algorithm:
• It is step by step procedure to solve given problem.
• They form the foundation of writing a program.
2.Flowcharts:
• A flowchart is pictorial representation of an algorithm that uses boxes of different shapes
to denote the flow of control in the problem execution.
VCET,Puttur. Page 22
Principles of Programming using C 22POP13 [Module 1- Part 2]
Sequence: Sequence means that each step of the algorithm is executed in the specified order. An
algorithm to add two numbers. This algorithm performs the steps in a purely sequential order.
Decision: Decision statements are used when the outcome of the process depends on some
condition.
For example, if x=y, then print “EQUAL”.
Hence, the general form of the if construct can be given as
if condition then process
Repetition : Repetition, which involves executing one or more steps for a number of times, can
be implemented using constructs such as while, do-while, and for loops.
These loops execute one or more steps until some condition is true.
4.Pseudocodes : Pseudocodes are an outline of a program that can be easily converted into
programming statements. They consist of short English phrases that explain specific tasks within
a program’s algorithm. They should not include keywords in any specific computer language.
#include<stdio.h>
#define PI 3.1415927
void main()
{
float peri, r;
printf("Enter value for radius\n");
scanf("%f ",&r);
peri=2*PI*r;
printf(“Perimeter=%f\n",peri);
}
3.Write an algorithm, flowchart and C program to find area and perimeter of a rectangle.
VCET,Puttur. Page 24
Principles of Programming using C 22POP13 [Module 1- Part 2]
printf("Area =%f\n",area);
printf("Perimeter =%f\n", peri);
}
4. Write an algorithm, flowchart and C program to convert given temperature from Fahrenheit to
Celsius.
3. Define Variable? Explain the syntax of variable declaration and initialization with
example?
VCET,Puttur. Page 25
Principles of Programming using C 22POP13 [Module 1- Part 2]
4. Define Data type? Explain primitive data types that are supported by C Language with
examples?
6. Define flowchart? Explain the various symbols used to represent the flowchart?
7. Define Constant? How do you declare the constant and explain various types of constants
supported by C programming language?
8. Define and give example for the following. i. Variable ii. Constant
9. Write short notes on printf function.
10. Write short notes on scanf function.
VCET,Puttur. Page 26