PPS Unit-1 Notes
PPS Unit-1 Notes
Introduction to Programming
1. Introduction to components of a computer system:
Computer is an electronic device which operates under the control of instructions stored
in its own memory. A computer can take data from the user through input devices (Input),
process the user given data (Processing), produces the result to the user through output
devices (Output)and stores data (Information) for future use. Computer can be defined as
follows...
Here the user interacts with the software, and the software makes the computer hardware
parts to work for the user.
Computer Hardware:
All physical components of the computer are called as computer hardware. A user can see,
touch and feel every hardware of the computer. All hardware components perform any task
based on the instructions given by the computer software.
The computer hardware is the physical part of a computer.
The computer hardware components are as follows...
Input Devices - These are the parts through which a user can give the data to the
computer.
Output Devices - These are the physical components of a computer through which the
computer gives the result to the user.
Storage Devices- These are the physical components of a computer in which the data
can be stored.
Devices Drives- Using drives, user can read and write data on to the strorage devices
like CD, floppy, etc.,
Cables- Various cables (Wires) are used to make connections in a computer
Other Devices- Other than the above hardware components, a computer also contains
components like Mother board, CPU (Processor), SMPS, Fans, etc.,
Input Devices
Computer input devices are the physical components of the computer which are used to give
the data given by the user to the computer. Using input devices the user can give the data to
the computer.
Example
Output Devices
Computer output devices are the physical components of the computer which are used to give
the computer result to the User. Using output devices, the user can see the computer
generated result.
Example
Storage Devices
Computer storage devices are the physical components of the computer which are used to
store data internally or externally.
Example
Disk:
Generally, a disk is a a round plate on which data can be encoded. There are two basic types
of disks: magnetic disks and optical disks.
Magnetic Disks
On magnetic disks, data is encoded as microscopic magnetized needles on the disk's surface.
You can record and erase data on a magnetic disk any number of times, just as you can with a
cassette tape. Magnetic disks come in a number of different forms:
Floppy disk
A typical 5¼-inch floppy disk can hold 360K or 1.2MB (megabytes). 3½-inch floppies
normally store720K, 1.2MB or 1.44MB of data. Floppy disks or obsolete today, and are
found on older computer systems.
Hard disk
Hard disks can store anywhere from 20MB to more than 1-TB (terabyte). Hard disks are also
from 10 to 100 times faster than floppy disks.
Optical Disks
Optical disks record data by burning microscopic holes in the surface of the disk with a laser.
To read the disk, another laser beam shines on the disk and detects the holes by changes in
the reflection pattern.
Optical disks come in three basic forms:
CD-ROM
Most optical disks are read-only. When you purchase them, they are already filled with data.
You can read the data from a CD-ROM, but you cannot modify, delete, or write new data.
WORM
Worm stands for write-once, read-many. WORM disks can be written on once and then read
any number of times; however, you need a special WORM disk drive to write data onto a
WORM disk.
Primary memory is where programs and data are kept when the processor is actively using
them. When programs and data become active, they are copied from secondary memory into
main memory where the processor can interact with them. A copy remains in secondary
memory.
Main memory is intimately connected to the processor, so moving instructions and data into
and out of the processor is very fast. Main memory is sometimes called RAM. RAM stands
for Random Access Memory. "Random" means that the memory cells can be accessed in any
order.
When people say that a computer has "512 megabytes of RAM" they are talking about how
big its main memory is. One megabyte of memory is enough to hold approximately one
million (106 ) characters of a word processing document. (There will be more about bytes
and megabytes later on in these notes.)
Nothing permanent is kept in main memory. Sometimes data are placed in main memory for
just a few seconds, only as long as they are needed.
Secondary Memory Secondary memory is where programs and data are kept on a long-term
basis. Common secondary storage devices are the hard disk and optical disks.
The hard disk has enormous storage capacity compared to main memory.
The hard disk is usually contained inside the case of a computer.
The hard disk is used for long-term storage of programs and data.
Data and programs on the hard disk are organized into files.
A file is a section of the disk that has a name.
A hard disk might have a storage capacity of 500 gigabytes (room for about 500 x 109
characters).
Primary memory Secondary memory
Fast Slow
Expensive cheap
Low capacity Large Capacity
Works directly with the processor Not connected directly to the
processor
Processor:
A processor, or "microprocessor," is a small chip that resides in computers and other
electronic devices. Its basic job is to receive input and provide the appropriate output. While
this may seem like a simple task, modern processors can handle trillions of calculations per
second.
Operating System:
An operating system (OS) is the program that, after being initially loaded into the computer
by a boot program, manages all of the other application programs in a computer. The
application programs make use of the operating system by making requests for services
through a defined application program interface (API).
Compiler Interpreter
It usually generates intermediate code in the It doesn't create an intermediate object (.obj)
form of the object file (.obj). code.
Detected errors in the program get displayed Detected errors in the program get displayed
after the entire program is read by compiler. after each instruction read by the interpreter.
Software:
The software is the collection of programs (Instructions) that allow the hardware to do its job.
Computer Software divided into two categories.
1) System Software
2) Application Software
The programs directly related to the computer hardware and perform tasks associated with
controlling and utilizing computer hardware
System software:
The programs directly related to the computer hardware and perform tasks associated with
controlling and utilizing computer hardware
System Software mainly divided into three classes.
1) Operating System : An operating system (OS) is the program that, after being
initially loaded into the computer by a boot program, manages all the other programs
in a computer. The other programs are called applications or application programs.
Ex: Windows versions, Linux versions
2) System support: System support software is software that supports, or facilitates the
smooth and efficient execution of various programs and operations of a computer.
There are four major categories of systems support software: utility programs,
language translators, database management systems, and performance statistics
software.
Application Software:
An application is a job or task a user wants to accomplish through a computer.
Application Software is broken into two classes.
General Purpose Software: General Purpose software is programs that help a user perform
general tasks. Ex: word processing, spreadsheets.
Applications Specific Software: Application Specific software are programs that help a user
perform a specific job. Ex: c, c++, java
2. Creating and Running Programs:
We explain 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 and make improvements
to the code.
The job of the programmer to write and test the program. There are four steps in this process.
1. Writing and Editing Programs
2. Compiling Programs
3. Linking Programs
4. Executing Programs
Important Points
1. C program file (Source file) must save with .c extension.
2. Compiler converts complete program at a time from high level language to low level
language.
3. Input to the compiler is .c file and output from the compiler is .exe file, but it also
generates .obj file in this process.
4. Compiler converts the file only if there are no errors in the source code.
5. CPU places the result in User Screen window.
3. Number Systems:
Divide the Number (Decimal Number) by the base of target base system (in which
you want to convert the number: Binary (2), octal (8) and Hexadecimal (16)).
Write the remainder from step 1 as a Least Signification Bit (LSB) to Step last as a
Most Significant Bit (MSB).
Result
Decimal to Binary Conversion
Decimal Number is : (12345)10
Example 2 Hexadecimal
Decimal Number is : (725)10 Number is
(2D5)16
Convert
10, 11, 12, 13, 14,
15
to its equivalent...
A, B, C, D, E, F
4. Introduction to algorithms:
To write a logical step-by-step method to solve the problem is called algorithm, in other
words, an algorithm is a procedure for solving problems. In order to solve a mathematical or
computer problem, this is the first step of the procedure. An algorithm includes calculations,
reasoning and data processing.
Algorithms can be presented by natural languages, pseudo code and flowcharts, etc.
Pseudo code is an artificial and informal language that helps programmers develops
algorithms. Pseudo code is very similar to everyday English.
Example 1: Write an algorithm to determine a student’s final grade and indicate whether it is
passing or failing. The final grade is calculated as the average of four marks.
Pseudo code:
Input a set of 4 marks
Calculate their average by summing and dividing by 4
if average is below 50
Print “FAIL”
else
Print “PASS”
Detailed Algorithm
Step 1: Read M1,M2,M3,M4
Step 2: GRADE = (M1+M2+M3+M4)/4
Step 3: if (GRADE < 50) then
Print “FAIL”
else
Print “PASS”
end if
Flowchart:
Function definition
Loop or repetition
Connector
Data Base
The graphics above represent different part of a flowchart. The process in a flowchart can be
expressed through boxes and arrows with different sizes and colours. In a flowchart, we can
easily highlight a certain element and the relationships between each part.
Algorithm:
Step 1: Initialize X as 0,
Step 2: Increment X by 1,
Step 3: Print X,
Flowchart:
We’ve now seen the steps that are necessary to build a program. In this section, we discuss
how we go about developing a program. This critical process determines the overall quality
and success of our program. If we carefully design each program using good structured
development techniques, our programs will be efficient, error-free, and easy to maintain.
Popular programming languages like C, C++, Java etc., use compiler to convert high level
language instructions into low level language instructions. Compiler is a program that
converts high level language instructions into low level language instructions. Generally,
compiler performs two things, first it verifies the program errors, if errors are found, it returns
list of errors otherwise it converts the complete code into low level language.
To create and execute C programs in Windows Operating System, we need to install Turbo C
software. We use the following steps to create and execute C programs in Windows OS…
History of C
C is a structured programming language. It is also known as function orientated programming
language. C programming language was developed in the year of 1972 by Dennis Ritchie at
Bell Laboratories in USA (AT & T).
In the year of 1968, research was started by Dennis Ritchie on programming languages like
BCPL, CPL. The main aim of his research was to develop a new language to create an OS
called UNIX. After four years of research, a new programming language was created with
solutions for drawbacks in languages like BCPL & CPL. In the year of 1972, the new
language was introduced with the name “Traditional C”.
The name 'c' was selected from the sequence of previous language ‘B’ (BCPL), because most
of the features of 'c' was derived from BCPL (B language).
The first outcome of the c language was UNIX operating system. The initial UNIX OS was
completely developed using 'c' programming language.
The founder of the ‘C’ language,Dennis Ritchie is known as “Father of C”and also “Father of
UNIX”.
C programming language is a very popular programming language, because it is reliable,
simple and easy to use and it is the base for almost all the other programming languages.
The following are the language before ‘c’ & various versions of ‘c’.
3. B Language
B language is derived from BCPL. It was introduced in the year of 1969 by Ken Thompson
and Dennis Ritchie at Bell Laboratory, USA. The B language is similar to the BCPL.
4. C Language
C language is derived from B language. It was introduced in the year of 1972 by Dennis
Ritchie at Bell Laboratory, USA. The C language was mainly developed to create a operating
system called UNIX. The name C is given based on the previous language B and BCPL.
5. ANSI C (C89)
In the year of 1983, the ANSI (American National Standards Institute) formed a committee to
frame standard specifications for the C language. In the year of 1989, this committee
introduced a standard version of C with the name "ANSI C" with standard library files. The
ANSI C is also called as C89 in short form.
6. C90
In the year of 1990, the ANSI C was got ISO (Intenational Organization for Standardization)
standardization with the inclusion of few new features like new library files, new processor
commands.
7. C99
In the year of 1995, many new features were added to the C90 to create a new version of it.
Basic structure of C programs:
C tokens:
Keywords:
In C programming language, keywords are special words with predefined meaning.
Keywords are also known as reserved words in C programming language.
In C programming language, there are 32 keywords. All the 32 keywords have their own
meaning which is already known to the compiler.
Keywords are the reserved words with predefined meaning which already known to the
compiler
Whenever C compiler comes across a keyword, automatically it understands its meaning.
Properties of Keywords
1.All the keywords in C programming language are defined as lowercase letters so
they must be use only in lowercase letters
2.Every keyword has a specific meaning; users can not change that meaning.
3.Keywords cannot be used as user defined names like variable, functions, arrays,
pointers etc...
4.Every keyword in C programming language represents something or specifies some
kind of action to be performed by the compiler.
The following table specifies all the 32 keywords with their meaning...
Identifiers:
Identifier is a user defined name of an entity to identify it uniquely during the program
execution
Example
int marks;
char studentName[30];
Here, marks and studentName are identifiers.
Integer constants
An integer constant can be a decimal integer or octal integer or hexa decimal integer. A
decimal integer value is specified as direct integer value whereas octal integer value is
prefixed with 'o' and hexa decimal value is prefixed with 'OX'.
An integer constant can also be unsigned type of integer constant or long type of integer
constant. Unsigned integer constant value is suffixed with 'u' and long integer constant value
is suffixed with 'l' whereas unsigned long integer constant value is suffixed with 'ul'.
Examples
125 -----> Decimal Integer Constant
O76 -----> Octal Integer Constant
OX3A -----> Hexa Decimal Integer Constant
50u -----> Unsigned Integer Constant
30l -----> Long Integer Constant
100ul -----> Unsigned Long Integer Constant
Example
The floating point value 3.14 is represented as 3E-14 in exponent form.
Character Constants
A character constant is a symbol enclosed in single quotation. A character constant has a
maximum length of one character.
Example
'A'
'2'
'+'
In C programming language, there are some predefined character constants called escape
sequences. Every escape sequence has its own special functionality and every escape
sequence is prefixed with '\' symbol. These escape sequences are used in output function
called 'printf()'.
Strings:
String Constants
A string constant is a collection of characters, digits, special symbols and escape sequences
that are enclosed in double quotations.
Ex: "This""is""btechsmartclass"
Special Symbols:
The following special symbols are used in C having some special meaning and 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.
Variables :
Variable is a name given to a memory location where we can store defferent values of same
datatype during the program execution.
Every variable in c programming language must be declared in the declaration section before
it is used. Every variable must have a data type that determines the range and type of values
to be stored and size of the memory to be allocated.
A variable name may contain letters, digits and underscore symbol. The following are the
rules to specify a variable name...
1.Variable name should not start with digit.
2.Keywords should not be used as variable names.
3.Variable name should not contain any special symbols except underscore(_).
4.Variable name can be of any length but compiler considers only the first 31
characters of the variable name.
Declaration of Variable
Declaration of a variable tells to the compiler to allocate required amount of memory with
specified variable name and allows only specified datatype values into that memory location.
Declaration Syntax:
datatype variableName;
Data Types:
Data used in c program is classified into different types based on its properties. In c
programming language, data type can be defined as a set of values with similar
characteristics. All the values in a data type have the same properties.
Data types in c programming language are used to specify what kind of value can be stored in
a variable. The memory size and type of value of a variable are determined by varible
datatype. In a c program, each variable or constant or array must have a datatype and this
datatype specifies how much memory is to be allocated and what type of values are to be
stored in that variable or constant or array. The formal definition of datatype is as follows...
Primary Datatypes
The primary datatypes in C programming language are the basic datatypes. All the primary
datatypes are already defined in the system. Primary datatypes are also called as Built-In
datatypes. The following are the primary datatypes in c programming lanuage...
1.Integer Datatype
2.Floating Point Datatype
3.Double Datatype
4.Character Datatype
Integer Datatype
Integer datatype is a set of whole numbers. Every integer value does not have the decimal
value. We use the keyword "int" to represent integer datatype in c. We use the keyword int to
declare the variables and to specify return type of a function. The integer datatype is used
with different type modifiers like short, long, signed and unsigned. The following table
provides complete details about integer datatype.
Floating Point Datatypes
Floating point datatypes are set of numbers with decimal value. Every floating point value
must contain the decimal value. The floating point datatype has two variants...
float
double
We use the keyword "float" to represent floating point datatype and "double" to represent
double datatype in c. Both float and double are similar but they differ in number of decimal
places. The float value contains 6 decimal places whereas double value contains 15 or 19
decimal places. The following table provides complete details about floating point datatypes.
void Datatype
The void datatype means nothing or no value. Generally, void is used to specify a function
which does not return any value. We also use the void datatype to specify empty parameters
of a function.
Enumerated Datatype
An enumerated datatype is a user-defined data type that consists of integer constants and each
integer constant is given a name. The keyword "enum" is used to define enumerated datatype.
Derived Datatypes
Derived datatypes are user-defined data types. The derived datatypes are also called as user
defined datatypes or secondary datatypes. In c programming language, the derived datatypes
are created using the following concepts...
Arrays
Structures
Unions
Enumeration
7. Syntax and Logical Errors in compilation:
Error is an illegal operation performed by the user which results in abnormal working of the
program.
Programming errors often remain undetected until the program is compiled or executed.
Some of the errors inhibit the program from getting compiled or executed. Thus errors should
be removed before compiling and executing.
1. Syntax errors: Errors that occur when you violate the rules of writing C/C++ syntax
are known as syntax errors. This compiler error indicates something that must be
fixed before the code can be compiled. All these errors are detected by compiler and
thus are known as compile-time errors.
Most frequent syntax errors are:
Missing Parenthesis (})
Printing the value of variable without declaring it
Missing semicolon like this:
// C program to illustrate
// syntax error
#include<stdio.h>
void main()
{
int x = 10;
int y = 15;
printf("%d", (x, y)) // semicolon missed
}
Error:
error: expected ';' before '}' token
Syntax of a basic construct is written wrong. For example : while loop
2. Run-time Errors : Errors which occur during program execution(run-time) after
successful compilation are called run-time errors. One of the most common run-time
error is division by zero also known as Division error. These types of error are hard to
find as the compiler doesn’t point to the line at which the error occurs.
For more understanding run the example given below.
// C program to illustrate
// run-time error
#include<stdio.h>
void main()
{
int n = 9, div = 0;
// wrong logic
// number is divided by 0,
// so this program abnormally terminates
div = n/0;
printf("resut = %d", div);
}
Error:
warning: division by zero [-Wdiv-by-zero]
div = n/0;
3. Linker Errors: These error occurs when after compilation we link the different
object files with main’s object using Ctrl+F9 key(RUN). These are errors generated
when the executable of the program cannot be generated. This may be due to wrong
function prototyping, incorrect header files. One of the most common linker error is
writing Main() instead of main().
// C program to illustrate
// linker error
#include<stdio.h>
void Main() // Here Main() should be main()
{
int a = 10;
printf("%d", a);
}
Error:
(.text+0x20): undefined reference to `main'
4. Logical Errors : On compilation and execution of a program, desired output is not
obtained when certain input values are given. These types of errors which provide
incorrect output but appears to be error free are called logical errors. These are one of
the most common errors done by beginners of programming.
These errors solely depend on the logical thinking of the programmer and are easy to
detect if we follow the line of execution and determine why the program takes that
path of execution.
// C program to illustrate
// logical error
int main()
{
int i = 0;
// logical error : a semicolon after loop
for(i = 0; i < 3; i++);
{
printf("loop ");
continue;
}
getchar();
return 0;
}
No output
5. Semantic errors : This error occurs when the statements written in the program are
not meaningful to the compiler.
// C program to illustrate
// semantic error
void main()
{
int a, b, c;
a + b = c; //semantic error
}
Error
error: lvalue required as left operand of assignment
a + b = c; //semantic error
9. Operators:
• An operator is a symbol which helps the user to give instruction to the computer to
do a certain mathematical or logical manipulations.
• Operators are used in C language program to operate on data and variables.
• C has a rich set of operators which can be classified as follows:
1. Arithmetic operators.
2. Relational Operators.
3. Logical Operators.
4. Assignment Operators.
5. Increments and Decrement Operators.
6. Conditional Operators.
7. Bitwise Operators.
8. Special Operators.
1.Arithmetic Operators
All the basic arithmetic operations can be carried out in C.
All the operators have almost the same meaning as in other languages.
Both unary and binary operations are available in C language.
Unary operations operate on a single operand,
Therefore the number 5 when operated by unary – will have the value –5.
Operator Meaning
2.Relational Operators
Often it is required to compare the relationship between operands and bring out a decision
and program accordingly. This is when the relational operator come into picture. C supports
the following relational operators.
Ex: It is required to compare the marks of 2 students, salary of 2 persons, we can compare
them using relational operators.
(6.5 <= 25) , (-65 > 0) , (10 < 7 + 5)
which result in either TRUE OR FALSE
Relational expressions are used in decision making statements of C language such as if, while
and for statements to decide the course of action of a running program
Operato Meaning
r
< is less than
<= is less than or equal to
> is greater than
>= is greater than or equal to
== is equal to
!= is not equal to
3.Logical Operators
C has the following logical operators; they compare or evaluate logical and relational
expressions.
Operato Meaning
r Op1 Op2 Op1 & Op1||
op2 op2
&& Logical AND
Nonzer Nonzer 1 1
o o
|| Logical OR
Nonzer 0 0 1
o
! Logical NOT
0 Nonzer 0 1
o
0 0 0 0
4.Assignment Operators
The Assignment Operator evaluates an expression on the right of the expression and
substitutes it to the value or variable on the left of the expression.
Example: x = a + b
In addition, C has a set of shorthand assignment operators of the form.
var oper = exp;
Example: x + = 1 is same as x = x + 1
The commonly used shorthand assignment operators are as follows
Shorthand assignment operators
a=a+1 a += 1
a=a–1 a -= 1
a = a * (n+1) a *= (n+1)
a = a / (n+1) a /= (n+1)
a=a%b a %= b
1. The increment and decrement operators are one of the unary operators which are very
useful in C language.
2. They are extensively used in for and while loops. The syntax of the operators is given
below
1. ++ variable name 2. variable name++
3. – –variable name 4. variable name– –
The increment operator ++ adds the value 1 to the current value of operand.
The decrement operator – – subtracts the value 1 from the current value of operand.
1. ++variable name and variable name++ mean the same thing when they form
statements independently.
2. They behave differently when they are used in expression on the right hand side of an
assignment statement.
Consider the following
m = 5;
y = ++m; (prefix) In this case the value of y and m would be 6
Suppose if we rewrite the above statement as
m = 5;
y = m++; (post fix) Then the value of y will be 5 and that of m will be 6.
The conditional operator consists of 2 symbols the question mark (?) and the colon (:). The
syntax for a ternary operator is as follows:
exp1 ? exp2 : exp3
The ternary operator works as exp1 is evaluated first. If the expression is true then exp2 is
evaluated & its value becomes the value of the expression. If exp1 is false,exp3 is evaluated
and its value becomes the value of the expression. Note that only one of the expression is
evaluated.
For example:
a = 10; b = 15; x = (a > b) ? a : b
Here x will be assigned to the value of b.
The condition follows that the expression is false therefore b is assigned to x.
Output
Input 2 integers : 45 34
The largest of two numbers is 45
7.Bitwise Operators
The C language is well suited to system programming because it contains operators that
can manipulate data at the bit level.
Those operators are used for testing, complementing or shifting bits to the right on
left.
C has two categories of bitwise operators that operate on data at the bit level:
1. Logical bitwise operators and
2. Shift bitwise operators.
Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise Exclusive OR
<< Shift left
>> Shift right
8.Special Operators
C supports some special operators of interest such as comma operator, size of operator,
pointer operators (& and *) and member selection operators (. and ->). The size of and the
comma operators are discussed here.
Precedence
1. Precedence is used to determine the order in which different operators in a complex
expression are evaluated .
2. C extents the concept to 15 levels.
Ex: 2+3*4=(2+(3*4))=14
-b++=(-(b++))
Associativity
1. Associativity is used to determine the order in which operators with the same
precedence are evaluated in a complex expression.
2. Precedence is applied before associativity to determine the order in which expressions
are evaluated.
3. Associativity can be left-to-right or right-to-left.
All the operators have the same precedence. Their associativity is from left to right. so they
are grouped as follows
Ex: 3* 8 / 4 % 4 * 5
• Scope determines the region of the program in which a defined object is visible.
• Scope pertains to any object that can be declared, such as a variable or a function
declaration.
• An object can have three levels of scope
1. Block scope
2. Function scope
3. File scope
Block Scope
• Variables defined within a block have a local scope. They are visible in that block
only. Outside the block they are not visible. Eg:
• { //outer block starts
{//inner block starts
printf("i=%d\t",i);//Print 2
}//inner block ends
Static (static variable):
• The value of static variables persists until the end of the program.
• It is declared using the keyword static :
static int x;
static float y;
• By default, Static variables are initialized with zero.
• The static specifier has two different usages depending on its scope.
1. static variable with block scope
2. static variable with file scope.
Static variable with block scope
• When a static variable is declared in a block scope, static defines the extent of the
variable
• Static variables with Block Scope are also known as Static Local Variables
Scope: Block
Extent: Static
Linkage: Internal
• Declaration:
static type variable_name
• Initialization:
• A static variable name can be initialized where it is defined, or it can be left
uninitialized. If it is initialized, it is initialized only once. If not initialized, its value
will be initialized to zero
Static variable with file scope
• When the static specifier is used with a variable that has a file scope (global scope)
and its linkage is internal.
Scope: File
Extent: Static
Linkage: Internal
Declaration:
Static type variable name;
#include <stdio.h>
#include<conio.h>
void fun1();//function definition
int main()
{//main block starts
int i=1;
printf("OUTPUT\n");
for(i=1;i<=5;i++)
fun1(); //call fun1() 5 times
return 0;
}//main block ends
//function definition
void fun1()
{//function scope starts
static int x=0;//declaring x as static variable
//int x=0;
printf("%d\n",x++);
}//function scope ends
#include<stdio.h>
#include<conio.h>
int main()
{//main block starts
int i=0;
for(i=1;i<=5;i++)
{
printf("In Main\n");
printf("x=%d",x++);
fun1();
}//for loop ends
printf("x=%d\n",x);
return 0;
}//main block ends
void fun1()
{//function scope ends
printf("In function\n");
printf("x=%d\n",x++);
}//function scope ends
External (extern variable)
Extern is used for global variables that are shared across code in several files.
External variables are used with separate compilations.
Large projects are decomposed in to many source files.
Decomposed source files are compiled separately and linked together to form a unit.
Storage is permanently assigned to Global variables (defined outside functions) and
all functions of the storage class extern.
• Characteristics:
• Scope: file
• Extent: static
• Linkage: external
• Declaration:
extern type variable_name;
#include <stdio.h>
#include<conio.h>
printf("OUTPUT\n");
printf("i=%d\t",i);//Print 10
}//inner-inner block ends
printf("i=%d\t",i);//Print 10
}//inner block ends
printf("i=%d\t",i);//Print 10
return 0;
}//main block ends
Class Scop Extent Linkag Keyword
e e
we have assumed that all of our expressions involved data of the same type. But, what
happens when we write an expression that involves two different data types, such as
multiplying an integer and a floating-point number? To perform these evaluations, one of
the types must be converted.
Type conversion is of two types:
1. Implicit Type Conversion
2. Explicit Type Conversion (Cast)
Implicit Type Conversion
When the types of the two operands in a binary expression are different, C automatically
converts one type to another. This is known as implicit type conversion.
Conversion rank:
1. We assign a rank to the integral and floating point arithmetic types.
2. These ranks are known as conversion ranks.
3. Conversion ranks are shown below
The most important function of C is main() function. It is mostly defined with a return
type of int and without parameters :
int main() { /* ... */ }
We can also give command-line arguments in C and C++. Command-line arguments are
given after the name of the program in command-line shell of Operating Systems.
To pass command line arguments, we typically define main() with two arguments : first
argument is the number of command line arguments and second is list of command-line
arguments.
int main(int argc, char *argv[]) { /* ... */ }
or
int main(int argc, char **argv) { /* ... */ }
argc (ARGument Count) is int and stores number of command-line arguments
passed by the user including the name of the program. So if we pass a value to a
program, value of argc would be 2 (one for argument and one for program name)
The value of argc should be non negative.
argv(ARGument Vector) is array of character pointers listing all the arguments.
If argc is greater than zero,the array elements from argv[0] to argv[argc-1] will
contain pointers to strings.
Argv[0] is the name of the program , After that till argv[argc-1] every element is
command -line arguments.
Properties of Command Line Arguments:
1. They are passed to main() function.
2. They are parameters/arguments supplied to the program when it is invoked.
3. They are used to control program from outside instead of hard coding those values
inside the code.
4. argv[argc] is a NULL pointer.
5. argv[0] holds the name of the program.
6. argv[1] points to the first command line argument and argv[n] points last argument.
if…else statement
The if…else statement is an extension of the simple if statement. It takes the following
general form:
if ( test expression)
{
true-block statement(s)
}
else
{
false-block statement(s)
}
statement-x
If the test expression is true, then the true block statements are executed.
If the test expression is false, then the false block statements are executed.
It never executes both blocks at a time.
In both cases the control is transferred
to the statement-X
1. There is another of putting ifs together when multipath decisions are involved .
2. A multipath decision is a chain of ifs in which the statement associated with each else
is an if.
3. It takes general form, as shown below.
if(condition-1)
statement-1;
else if (condition-2)
statement-2;
else if(condition-3)
statement-3
else if(condition n)
statement-n;
else
default statements;
statement-X
case constant-expression :
statement(s);
break; /* optional */
….....
default : /* Optional */
statement(s);
}
Loops:
There are three loop statements:
1. the while
2. the for and
3. the do…while.
The first two are pretest loops and the third is a post-test loop.
Every loop consists of the following properities.
Loop Initialization
1. Loop initialization must be done before the first execution of the loop body.
2. Initialization may be explicit or implicit.
3. When the initialization is explicit, we include code to set the beginning values of key
loop variables.
4. Implicit initialization provided no direct initialization code; rather, it relies on a
preexisting situation to control the loop
Loop Update
How can the condition that controls the loop be true for a while and then change to false.
The answer is that something must happen inside the body of the loop to change the
condition.
1. The actions that cause these changes are known as loop update.
2. Update is done in each iteration, usually as the last action.
3. If the body of the loop is repeated m times, then updating is also done m times.
The goto
1. C supports the goto statement to branch unconditionally one point to another point in
the program.
2. Use of goto statement is highly discouraged in any programming language because it
makes difficult to trace the control flow of a program, making the program hard to
understand and hard to modify.
3. Any program that uses a goto can be rewritten so that it doesn't need the goto.
Syntax:
The syntax for a goto statement in C is as follows:
goto label;
..
.
Label: statement;
Here label can be any plain text except C keyword and it can be set anywhere in the C
program above or below to goto statement.
scanf() function
The scanf() function is used to read multiple data values of different data types from the
keyboard. The scanf() function is built-in function defined in a header file called "stdio.h".
When we want to use scanf() function in our program, we need to include the respective
header file (stdio.h) using #include statement. The scanf() function has the following syntax...
Syntax:
scanf("format strings",&variableNames);
Example Program
#include <stdio.h>
void main(){
int i;
scanf("%d",&i);
}
Output:
Enter any integer value: 55
You have entered 55 number
In the above example program, we used the scanf() function to read an integer value from the
keyboard and store it into variable 'i'.
The scanf function also used to read multiple data values of different or same data types.
Consider the following example program...
#include <stdio.h>
void main(){
int i;
float x;
printf("\nEnter one integer followed by one float value : ");
scanf("%d%f",&i, &x);
printf("\ninteger = %d, float = %f",i, x);
}
Output:
Enter one integer followed by one float value: 20 30.5
integer = 20, float = 30.5
In the above example program, we used the scanf() function to read one integer value and one
float value from the keyboard. Here 'i' is an integer variable so we have used format string
%d, and 'x' is a float variable so we have used format string %f.
The scanf() function returns an integer value equal to the total number of input values read
using scanf function.
Example Program
#include <stdio.h>
void main(){
int i,a,b;
float x;
}
Output:
Enter two integers and one float : 10 20 55.5
Total inputs read : 3
Formatted output Functions in C:
C programming language provides built-in functions to perform output operation. The output
opearations are used to display data on user screen (output screen) or printer or any file. C
programming language provides the following built-in output functions...
1. printf()
printf() function
The printf() function is used to print string or data values or combination of string and data
values on the output screen (User screen). The printf() function is built-in function defined in
a header file called "stdio.h". When we want to use printf() function in our program we need
to include the respective header file (stdio.h) using #include statement. The printf() function
has the following syntax...
Syntax:
printf("message to be display!!!");
Example Program
#include <stdio.h>
void main(){
printf("Hello! Welcome to btechsmartclass!!!");
}
Output:
Hello! Welcome to btechsmartclass!!!
In the above example program, we used the printf() function to print a string on to the output
screen.
The printf() function is also used to display data values. When we want to display data values
we use format string of the data value to be display.
Syntax:
printf("format string",variableName);
Example Program
#include <stdio.h>
void main(){
int i = 10;
float x = 5.5;
printf("%d %f",i, x);
}
Output:
10 5.5
In the above example program, we used the printf() function to print data values of variables i
and x on to the output screen. Here i is a integer variable so we have used format string %d
and x is a float variable so we have used format string %f.
The printf() function can also used to display string along with data values.
Syntax:
Example Program
#include <stdio.h>
void main(){
int i = 10;
float x = 5.5;
printf("Integer value = %d, float value = %f",i, x);
}
Output:
Integer value = 10, float value = 5.5
In the above program we are displaying string along with data values.
Every function in C programming language must have a return value. The printf() function
also have integer as return value. The printf() function returns an integer value equalent to the
total number of characters it has printed.
Example Program
#include <stdio.h>
void main(){
int i;
i = printf("btechsmartclass");
printf(" is %d number of characters.",i);
}
Output:
btechsmartclass is 15 number of characters.
In the above program, first printf() function printing "btechsmartclass" which is of 15
characters. So it returns integer value 15 to variable "i". The value of "i" is printed in the
second printf() function.
To display the output in different lines or as we wish, we use some special characters
called escape sequences. Escape sequences are special characters with special functionality
used in printf() function to format the output according to the user requirment. In C
programming language, we have the following escape sequences...
Escape sequence Meaning
\n New line
\t Horizontal Tab
\v Vertical Tab
\a Beep sound
\b Backspace
\\ Backward slash
\? Question mark
\' Single quotation mark
\" Double quotation mark
Consider the following example program...
#include <stdio.h>
void main(){
printf("Welcome to\n");
printf("btechsmartclass\n");
printf("the perfect website for learning");
}
Output:
Welcome to
btechsmartclass
the perfect website for learning