Programming in C Notes
Programming in C Notes
YEAR / SEM: I / I
UNIT-1 I YEAR/I SEM
UNIT I BASICS OF C PROGRAMMING
Introduction to Problem Solving: Algorithm, Flowchart, Pseudocode. Programming Basics:
Applications of C Language-Structure of C program -Identifiers-Data Types – Variables-
Constants – Keywords – Operators – Input/output statements, Decision making statements -
Looping statements - Expressions-Precedence and Associativity – Expressions- Evaluation-
Type Conversions
1.1 ALGORITHMS:
Definition1:
An algorithm can be defined as “a complete, unambiguous, finite number of logical steps for
solving a specific problem”
Definition2:
An algorithm, is defined as a:“well-ordered collection of unambiguous and effectively
computable operations, that when executed, produces a result and halts in a finite amount of
time.”
Definition3:
An algorithm is defined as a finite sequence of explicit instruction that provides a set of
input values, process an output and then terminates.
Definition4:
An algorithm is a well-defined computational procedure consisting of a set of instructions
that takes some value or set of values, as input, and produces some value or set of values, as
output
algorithm
Input Output
Definition5:
An algorithm consists of a set of explicit and unambiguous finite steps which, when carried out
for a given set of initial conditions, produce the corresponding output and terminate in a finite
time. An algorithm is a step-by-step procedure for solving a problem in a finite number of steps.
Definition6:
An algorithm is a finite number of clearly described, unambiguous “doable” steps that can be
systematically followed to produce a desired result for given input in a finite amount of time.
Step1. Identification of input: For an algorithm, there are quantities to be supplied called input
and these are fed externally. The input is to be identified first for any specified problem.
Step2: Identification of output: From an algorithm, at least one quantity is produced, called
output for any specified problem.
2
UNIT-1 I YEAR/I SEM
Step3 : Identification the processing operations : All the calculations to be performed in order
to lead to output from the input are to be identified in an orderly manner.
Step4 : Processing Definiteness : The instructions composing the algorithm must be clear and
there should not be any ambiguity in them.
Step5 : Processing Finiteness : If we go through the algorithm, then for all cases, the algorithm
should terminate after a finite number of steps.
Step6 : Possessing Effectiveness : The instructions in the algorithm must be sufficiently basic
and in practice they can be carries out easily.
PROPERTIES OF AN ALGORITHM:
3
UNIT-1 I YEAR/I SEM
Bottom-up approach : This technique is just reverse of the top down programming. In this
programming technique, the solutions of the independent sub-problems are designed first. Then
these solutions are combined or composed in a main module in order to design the final solution
of the problem. The following figure shows the bottomup approach:
Bottom up approach
Example Algorithm 1
Step 1: Start.
Step 2: Read two numbers a and b.
Step 3: Add the numbers a and b and store in sum as
sum=a+b Step 4: Display sum
Step 5: Stop
Example Algorithm 2
Step 1: Start.
Step 2: Read the three numbers A,B,C.
Step 3: Compare A and B. If A is greater, store A in MAX, else store B in MAX.
Step 4: Compare MAX and C. If MAX is greater, output “MAX is greater” else output
“C is greater”.
Step 5: Stop.
4
UNIT-1 I YEAR/I SEM
1.2 BUILDING BLOCKS OF ALGORITHMS
The building blocks of algorithm refer to the blocks such as statements, state, control
flow structures, functions, etc that are used to develop algorithms
Statements
State
Control flow
Functions
Statements
A statement is a command given to the computer that instructs the computer to take a
specific action, such as display to the screen, or collect input. A computer program is made up of
a series of statements.
Reserved words - words that have pre-defined meanings in the Java language
Identifiers - words that are created by programmers for names of variables, functions,
classes, etc.
Literals - literal values written in code, like strings or numbers
Operators - special symbols that perform certain actions on their operands
Calls to
functions
State
State is the information that the program manipulates to accomplish some task. It is data
or information that gets changed or manipulated throughout the runtime of a program. The state
of an algorithm is defined as its condition regarding stored data. The stored data in an algorithm
are stored as variables or constants. The state shows its current values or contents. An instruction
is a single operation, that describes a computation. When it executed it convert one state to other.
Example: state refers to the set of variables and the values to which they refer.
Control Flow
Control flow is the order that instructions are executed in a program .A control statement is
a statement that determines the control flow of a set of instructions
There are three fundamental forms of control that programming languages provide-
sequential control, selection control, and iterative control.
Sequential control: It is an implicit form of control in which instructions are executed in the
order that they are written. A program consisting of only sequential control is referred to as a
5
UNIT-1 I YEAR/I SEM
“Straight-line program”. Executes statements one by one in linear order
Pseudocode Flowchart
BEGIN
statement
Statement Action1
END
Action2
6
UNIT-1 I YEAR/I SEM
Conditional Statements:
The following are the conditional statements such as if, if-else,if…elif...else statement
if statement:
The if statement is used to test a condition. If the condition is true, the statements of if block
are executed otherwise the statements following the if block are executed.
Pseudocode:
IF(CONDITION)THE
N STATEMENTS
ENDIF
Example:
7
UNIT-1 I YEAR/I SEM
if else
The if-else statement is used to execute different actions based on the condition. The if-else
statement evaluates the condition and will execute body of if only when test condition is true. If
the condition is false, body of else is executed. It is a two-way branching statement
Pseudocode:
IF condition
THEN statement 1
ELSE
statement 2
END‐IF
Example:
if elif else
The if elif else statement is used to check multiple conditions. When series of actions are to
performed based on one-by-one decisions, then if –else-if else statements are used. It is also
called as multipath decision statement. If the condition for if is false, it checks the condition of
the next elif block. If all the conditions are false, body of else is executed.
8
UNIT-1 I YEAR/I SEM
Example
Looping/Iterative statements:
The following are the looping statements such as while , for
while:
The while loop in Python is used to iterate over a block of code as long as the test expression
(condition) is [Link] while loop, test expression is checked first. The body of the loop is entered
only if the test_expression evaluates to True. After one iteration, the test expression is checked
again. This process continues until the test_expression evaluates to False.
1
0
PANIMALAR INSTITUTE OF TECHNOLOGY UNIT-1 I YEAR/I SEM
Example:
for:
The for loop in Python is used to iterate over a sequence .Iterating over a sequence is called
traversal. Loop continues until we reach the last item in the sequence. The body of for loop is
separated from the rest of the code using indentation.
11
PANIMALAR INSTITUTE OF TECHNOLOGY UNIT-1 I YEAR/I SEM
Example:
The statements used to control or terminate from the loop are known as loop control statements.
The following are the loop control statements: break, continue
break
The break statement terminates the loop containing it. Control of the program flows to the
statement immediately after the body of the loop. If break statement is inside a nested loop (loop
inside another loop), break will terminate the innermost loop. Inside the loop body, you can use
the break statement to exit the loop immediately.
12
I YEAR/I SEM
Pseudocode:
WHILE condition
Sequence of
statements BREAK
Continue
The continue statement is used to skip the rest of the code inside a loop for the current iteration
only. Loop does not terminate but continues on with the next iteration. Continue statement
will be encountered, and the flow of control will leave that loop body–but then the loop will
continue with the next element in the range.
13
I YEAR/I SEM
Pseudocode:
WHILE condition
Sequence of
statements
CONTINUE
Functions
A function is a block of organized, reusable code that is used to perform a single, related
action. Functions provide better modularity for your application and a high degree of code
reusing. Other Terms: methods, sub-routines, procedure.
Example:
Function: piece of prewritten code that performs an operation
print function: displays output on the screen
Argument: data given to a function
Example: data that is printed to screen
Types of functions/categories of
functions:
Pseudocode:
14
I YEAR/I SEM
1.3 NOTATION
(PSEUDOCODE,FLOWCHART,PROGRAMMING
LANGUAGE)
Notation refers to the means of representing the algorithm for solving a task. The following are
the notations for representing the algorithms
Pseudocode
Flowchart
Programming Languages
PSEUDOCODE
Pseudo code derived from „pseudo‟ which means imitation and „code‟ means instruction is a
generic way of describing an algorithm without using any specific programming language
related notations. Pseudocode is an artificial and informal language that helps programmers to
develop algorithms. Pseudocode can be defined as the narrative description of the flow and logic
15
I YEAR/I SEM
of the intended program, written in plain language that expresses each step of the [Link]
pseudocode is also called as Program design language (PDL)
Characteristics/properties of Pseudocode:
Pseudocode Language
Constructs
The Commonly used keywords
If statement:
IF condition THEN
statement 1
ELSE
statement 2
END‐IF
While:
WHILE condition
statements
END‐WHILE
16
I YEAR/I SEM
For: FOR
condition
statements
END‐FOR
for subprogram
BEGIN
SUBPROGRAM,
END SUBPROGRAM,
BEGIN
PROCEDURE,
END PROCEDURE
Indenting is used to show structure in the algorithm.
Advantages of Pseudocode:
Its language independent nature helps the programmer to express the design in
plain natural language.
Based on the logic of a problem it can be designed without concerning the syntax or
any rule
FLOWCHARTS
Characteristics/properties of flowchart:
Flowchart advantages
Flowchart not only serves as a program documentation but also helps as a means
to communicate with several programmers as it is language independent.
It serves as a useful reference or a programing aid due to its simple and efficient
method of representing the program logic of a problem.
Flowchart disadvantages
They are hard to modify and can be time consuming.
They need special software for symbols
Constructing a flowchart is time-consuming
Reasons for using flowchart as a problem-solving tool:
Communication
Effective analysis
Proper documentation
General rules /Guidelines for drawing flowcharts
Only one flow line should enter a decision symbol. However, two or three flow
lines may leave the decision symbol.
18
I YEAR/I SEM
Flowcharts are drawn so that flow generally goes from top to bottom of the page or
from left to right
Within standard symbols, write briefly and precisely.
Intersection of flow lines should be avoided.
It is useful to test the validity of the flowchart with normal/unusual test data.
19
I YEAR/I SEM
20
I YEAR/I SEM
Programming Language:
The programming language is the medium through which the problems to be solved by computer
can be represented in the form of programs or set of instructions. The computer executes the set of
instructions written in a particular language to produce the desired result. A programming language
consists of a set of characters, symbols, and usage rules that allow the user to communicate with
computers. In a simple form it can be defined as - any notation for the description of algorithm and
data structure may be termed as a programming language.
21
I YEAR/I SEM
i) Machine language : The machine language programs were written using the digit 0 and 1.
The instruction in machine language consists of two parts. The first part is an operation which
tells the computer what operation is to be performed. The second part of the instruction is
operand, which tells the computer where to find or store the data after applying the operation
ii)Advantages :
Translation free : Machine language is directly understand by the computer so it does not need
any translation. Otherwise, if a program is developed in high level language then it has to be
translated into the machine language so that the computer can understand the instructions.
High speed : The application developed in the machine language are extremely fast because it
does not require any conversion.
Disadvantages :
Machine dependent : Program developed in one computer system may not run on an another
computer system.
Complex language : This language was very difficult to understand and programming techniques
were tedious.
Error prone : Writing machine language programs, a programmer has to remember all the
opcodes and memory locations, so machine language is bound to be error prone.
iii)Assembly language : Assembly language is not a single language, but a group of language. An
assembly language provides a mnemonic instruction, usually three letters long, corresponding to
each machine instruction. The letters are usually abbreviated indicating what the instruction
does, like ADD for addition, MUL for multiplication etc. The assembly language allows the
programmer to interact directly with the hardware. Each line of assembly language program
consists of four columns called fields.
The general format of an assembly language instruction is :
[Label] <Opcode> <Operands> [; Comment]
Advantages:
Easy to understand and use : Assembly language uses mnemonics instead of using numerical
22
I YEAR/I SEM
opcodes and memory locations used in machine language, so it is easy to understand and use.
Less error prone : Assembly language is less error prone and it provides better facility to locate
errors and correct them.
Faster : It is much faster and use less memory resources than the high level language.
Disadvantage :
• Assembly language programs are machine dependent.
• Assembly language is complex to learn.
• A program written in assembly language is less efficient than machine language because every
assembly instruction has to be converted into machine language.
iv) High level language : COBOL, FORTRAN, PASCAL and C are the examples of high level
languages. High level languages are similar to English language. Programs written using these
languages may be machine independent. A single instruction of a high level language can
substitute many instructions of machine language and assembly language. Using the high level
language complex software can be design.
Advantages :
• Readability : Since high level languages are similar to English language so they are easy to
learn and understand.
• Programs written in high level languages are easy to modify and maintain.
• High level language programs are machine independent.
• Programs written in high level language are easy to error checking.
Disadvantages :
Programs written in high level language has to be compile first for execution of the program.
This step of compilation increases the execution time of an application. Moreover, the programs
occupies more memory space during the execution time.
Another main drawback of HLL programs is - its poor control on the hardwares.
Language Translators
The language translators or also called language processors are the programs which converts the
high level language programs into the machine language programs for execution.
Types of Language Translators:
Compiler
Interpreter
Assembler
Compiler : A compiler is a program that can translates an higher level language program to its
machine form. This language processor translates the complete source program as a whole into
machine code before execution. Here the source program means – the program that is written by
the programmer and the translated program is called a object program or object code. Examples: C
and C++ compilers. If there are errors in the source code, the compiler identifies the errors at the
end of compilation. Such errors must be removed to enable the compiler to compile the source
code successfully.
23
I YEAR/I SEM
Assembler : We have already known that - assembly language is the symbolic representation of a
computer‟s binary encoding – machine language . Assembly language is more readable than
machine language because it uses symbols instead of bits. A program called an assembler that
translates assembly language into binary instructions or machine language. An assembler reads a
single assembly language source file and produces an object file containing machine instructions.
24
I YEAR/I SEM
Problem:
The problem can be defined as the gap between actual and desired conditions.
an algorithm requires
28
I YEAR/I SEM
Simplicity:
- It is very easy to understand.
Portability:
- It is the concept of carrying the instruction from one system to another system
Powerful:
- C is a very powerful programming language, it have a wide verity of data types,
functions, control statements, decision making statements, etc
Structure oriented:
- Structure oriented programming language aimed on clarity of program, reduce the complexity
of code, using this approach code is divided into sub-program/subroutines. These programming
have rich control structure.
Modularity
- In c programming we can break our code in subprogram.
Middle level language:
- C programming language can supports two level programming instructions with the
combination of low level and high level language that's why it is called middle level
programming language
Compiler based:
- C is a compiler based programming language that means without compilation no C program
can be executed
Syntax based language
- C is a strongly tight syntax based programming language.
Efficient use of pointers
- Pointers is a variable which hold the address of another variable, pointer directly direct access
to memory address of any variable due to this performance of application is improve
Uses(Applications) of C language:
To Design Operating system
To Design Language Compiler and Interpreter
To Design Database
Language Interpreters
Utilities
29
I YEAR/I SEM
Network Drivers
Assemblers
UNIX Kernel is completely developed in C Language.
30
I YEAR/I SEM
printf(“good morning\n”);
printf is a build-in functions which is used to display output in the screen.
\n is called escape sequence to go to next line It always begin with \ (back slash).
Semicolon(;)
It is used to terminate the statement.
return(0);
- This statement terminates the main function.
- Returns the value 0 to the operating system indicating Successful completion of
program.
- Any other number indicates that the program is failed.
STRUCTURE OF C PROGRAM:
#include<math.h>
32
I YEAR/I SEM
33
I YEAR/I SEM
C TOKENS:
C tokens are the basic buildings blocks in C language which are constructed together to
write a C program.
IDENTIFIERS:
Identifiers are the name used to identify entities like variable, function, array, structure or any other
user-defined item.
Identifier must be unique.
They are created to give unique name to an entity to identify it during the execution of the program.
Rules for naming an Identifier
Identifier name in C can have letters, digits or underscore(_).
The first character of an identifier name must be a alphabet (a-z, A-Z),underscore( _ ).
The first character of an identifier cannot be a digit.
Keywords are not allowed to be used as Identifiers.
No special character (except underscore) blank space and comma can be used in
Identifier name.
KEYWORDS
Keywords are reserved words that have a particular meaning in C language.
The meaning of key word is predefined. These meaning of the keyword cannot be
changed.
There are total 32 keywords in C language.
VARIABLES:
34
I YEAR/I SEM
L-Value: R-Value
L- Value Is An Object Locator. R-value refers to ‘Read Value’.
L-Value Stands For Left Value
The L-Value Could Legally Stand On The Left Side Of R-value can be anything of following:
An Assignment Operator. [Link]
For Example: Mark=20; // [Link]
The L- Value Should Be A Variable. 3. Constant
Eg,
num=20; //constant R value
35
I YEAR/I SEM
36
I YEAR/I SEM
DATA TYPES :
Data types determines the possible values that an identifier can have and the valid
operations that can be applied on it.
The type of a data determines how much space it occupies in storage.
In C Language, data types are broadly classified as
37
I YEAR/I SEM
38
I YEAR/I SEM
typedef datattype
variable
In the below program, rollno is the variable name (alias)given to the existing datatype int. So, after this
type definition, roll no can be used instead of datatype int.
Example (using typedef): Output:
#include<stdio.h> Roll number1 is 4001
int main() Roll number2 is 4002
{
typedef int rollno;
rollno num1 = 4001,num2 = 4002;
printf("Roll number1 is %d\n",num1);
printf("Roll number2 is %d\n",num2); return(0); }
39
I YEAR/I SEM
printf("%d",m1);} m1=MAY;printf("%d",m1);}
Output: Output:
3 3
Explanation: Explanation:
In this example, we declared Integers are assigned to enum
“m1” as the variable and the constants.
value of “APRIL” is
allocated to
m1, which is 3.
40
I YEAR/I SEM
Output:
16.100000
Explicit Conversion(Type casting):
The type conversion performed by the programmer by specifying the data type in the expression.
Data type should be mentioned before the variable name or value.
Syntax:
(data type)expression
Example1: Example2: :(Explicit typecasting)
#include <stdio.h> #include <stdio.h>
main() main()
{ {
int x=13, y=5 ; int x=13, y=5 ;
float z; float z;
z=x/y; // here, quotient is int datatype and it is z=(float)x/y; // int data type is converted to
stored in float variable float and float value(quotiemt) is stored in
printf("%f",z); float variable
} printf("%f",z);
Output: }
2.000000 Output:
2.600000
STORAGE CLASS:
A storage class defines the scope (visibility) and life-time of variables. Scope
- Where to store a variable (Storage area of variable) Lifetime- How long
the variable can be stored in the memory( alive) The following storage
classes are most often used in C programming.
[Link] [Link]
[Link] [Link]
A variable should be declared in any one of these four storage class.
1. auto storage class:
- auto is the default storage class.
- It is stored in RAM(main memory)
Scope: It can be used only in the block of code where it is declared.(local variable)
Lifetime: It will be alive only inside the block of code where it is declared.
Default value is Garbage Value
Syntax: Example:
auto data_type variablename; (or) auto int a;
41
I YEAR/I SEM
42
I YEAR/I SEM
Syntax: Example:
register data_type variablename; register int a;
Printing the value of the variable using register storage class Output:
#include<stdio.h> int Value of a is 11
main() Value of a is 11
{ Value of a is 11
increment();
increment();
increment();
43
I YEAR/I SEM
}
int increment()
{
register int a=10; a++;
printf("Value of a is: %d\n", a);
}
CONSTANTS (LITERALS):
Constants are the values that cannot be changed during the execution of a program.
Constant is a fixed value which may be an integer, floating point number, character or a string.
Types of constants:
Integer constants:
- Integer constants are integer values like -1, 2, 8 without any decimal point.
- It can be either positive or negative. If no sign proceeds an integer is assumed to be
positive.
There are three types of integer constants in C language:
- Decimal constant (base 10)
- Octal constant (base 8)
44
I YEAR/I SEM
Character constants:
- Character constants can have one character enclosed within single quotes.
- For example: 'a', 'l', 'Y', 'A' etc.
Escape Sequences
- C supports some special character constants that are used in output functions.
- Escape sequence consists of a backward slash (\) followed by a character.
45
I YEAR/I SEM
{ int main()
{
46
I YEAR/I SEM
OPERATORS IN C:
Operands:
An operand specifies an entity on which an operation is to be performed.
An operand can be a variable name, constant, a function call.
Operators:
Operators are special symbol that tells the compiler to perform specific mathematical or logical
operations.
Operator specifies the operation to be applied to its operands.
CLASSIFICATION OF OPERATORS:
The operators in c are classified on the basis of the following criteria:
1. The number of operands on which an operator operates.
2. The role of an operator.
Classification based on Number of Operands
Based upon the number of operands on which an operator operates,operators are classified as,
Unary operator: Binary operator ternary operator
A unary operator operates Binary operator operates Ternary operator operates on three
on only one operand. on two operands. operands. (Conditional operator)
Eg, Eg: Eg,
-3. Here the – is an unary 2-3. Here (-) acts as a ?: is a ternary operator
minus operator. binary operator.
Classification based on role of operator
Based upon their role operators are classified as:
1. Arithmetic operators
2. Assignment operators
3. Relational operators
4. Logical operators
5. Bitwise operators
6. Increment /Decrement operators
7. Conditional operator
8. Special operators
Arithmetic operators
Arithmetic operations like addition, subtraction, multiplication, divisions, etc. The arithmetic operators
available in c are given here.
47
I YEAR/I SEM
48
I YEAR/I SEM
c %= a;
printf("c=%d \n", c); return 0;
}
Relational operators:
- Relational operators are used to check the conditions.
- If the relation is true, it returns 1; if the relation is false, it returns value 0.
- The operand may be variables, constants or expressions.
Operator Description Example program Output
:
== Check if two operand are equal #include<stdio.h> 0
!= Check if two operand are not equal. int main() 0
> Check if operand on the left is { 1
greater than operand on the right int a=5,b=8; 0
< Check operand on the left is smaller printf("%d\n",a==b); 1
than right operand printf("%d\n",a>b); 1
>= check left operand is greater than or printf("%d\n",a<b);
equal to right operand printf("%d\n",a>=b);
<= Check if operand on left is smaller printf("%d\n",a<=b);
than or equal to right operand printf("%d\n",a!=b);
}
Logical operators:
- Logical operators are used to combine the results of two or more conditions. C has the
following logical operators.
Op Description Example a=5, b=2
erator
&& Logial AND. True only if all operands are true ((a == 5) && (b > 5)) equals to 0.
|| Logical OR. True only if either one operand is true ((a == 5) || (b > 5)) equals to 1.
49
I YEAR/I SEM
50
I YEAR/I SEM
Special Operator:
Operator Description Example
Sizeof Returns the size of an variable sizeof(x);
& Returns the address of an variable &x;
* Pointer to a variable *x ;
Example: Output:
#include <stdio.h> Size of integer is 2
int main() Size of Float value is 4
{ Size of character is 1
int a;float b;char c;
printf("Size of integer is %d\n", sizeof(a));
printf("Size of Float value is %d\n", sizeof(b));
printf("Size of character is %d\n", sizeof(c));
}
Conditional operator:
Conditional operator is the ternary operator.
Syntax:
Condition? Expression 1: Expression 2
Condition: condition is checked first. This expression evaluates to 1 if it's true and evaluates to 0 if
it's false.
51
I YEAR/I SEM
Expression1: If the condition is true, this expression is evaluated and return the result of Expression1.
Expression2: If the condition is false, this expression is evaluated.
Advantages of ternary operator:
Using ?: reduce the number of line codes and improve the performance of application.
Example 1: Use of ternary Example 2: Use of ternary operator
operator
#include <stdio.h> #include<stdio.h>
int main() main()
{ {
int a=89,b; int a=10,b=20,small;
b=(a ==100?1:2); printf((a<b ? printf("a is less") : printf("a is greater")));
printf("%d\n",b);return(0); return(0);
} }
Output: Output:
2 a is less
PRECEDENCE OF OPERATORS:(Associativity)
52
I YEAR/I SEM
* Multiplication left-to-right
/ Division Modulus
%
+ Addition left-to-right
- Subtraction
< Relational less than operator left-to-right
<= less than or equal to operator
> Relational greater than greater
>= than or equal to
53
I YEAR/I SEM
EXPRESSIONS:
Expressions:
An expression is a sequence of operands and operators.
The meaningful expression consists of one or more operands or operators that specify the
operations to be performed on operands.
Example: a+b, a-b.
Operands:
An operand specifies an entity on which an operation is to be performed.
Operators:
Operators are special symbol that tells the compiler to perform specific mathematical or logical operations.
Operator specifies the operation to be applied to its operands.
Based on the number of operators present in an expression, expressions are classified as simple
expression and compound expressions.
Simple expressions:
An expression that has only one operator is known as a simple expression
For example: a+2; Compound
Expressions:
An expression that has more than one operator is known as compound expressions.
For example: b= 2+3*5;
INPUT AND OUTPUT STATEMENTS:
In c language two types of input/output statements are available. They are
1. Formatted input/output statements
2. Unformatted input/output statements
54
I YEAR/I SEM
scanf() statement:
55
I YEAR/I SEM
56
I YEAR/I SEM
57
I YEAR/I SEM
58
I YEAR/I SEM
{ The Temperature in
float celsius, fahrenheit; Fahrenheit is:50.000000
printf ("Enter the Temperature in Celsius:"); scanf
("%f", &celsius);
fahrenheit = (1.8 * celsius) + 32;
printf ("The Temperature in Fahrenheit is:%f", fahrenheit); return(0);
}
59
I YEAR/I SEM
input.
Syntax: Syntax:
variable name=getchar(); putchar(variable_name);
Example Example:
char c; char c;
c=getchar(); putchar(c );
Program using getchar and putchar function:
#include<stdio.h>
int main()
{
char a;
printf("enter any key");
a=getchar(); // read input and store it in variable ‘a’
putchar(a); //display the output on screen
}
Output: enter
any key s
s
getch() putch()
- getch() accepts only single character from It displays any alphanumeric characters to the
keyboard. standard output device. It displays only one
- getch() function will just wait for any character at a time.
keyboard input (and press ENTER). It won’t Syntax:
display the given input character in output screen. putch(variable_name)
Syntax: Example:
variable_name=getch(); char a;
Example: putch(a);
char x;
x=getch();
60
I YEAR/I SEM
getche()
Like getch(), getche() also accepts only single character, but getche() displays the entered input
character in the screen.
Syntax:
Variable_name=getche();
Example:
char x; x=getche();
To use getch(), getche() functions, you need to include #include <conio.h> header file
which is a non-standard header file.
gets() puts()
- gets() accepts any line of string including spaces puts displays a single / paragraph of text to the
from the standard Input device (keyboard). standard output device.
-gets() stops reading character from keyboard Syntax: puts(variable_name);
only when the enter key is pressed. Example:
Syntax: gets(variable_name); char name[25];
Example: puts(name);
char name[25];
gets(name);
Program to read and print the string using gets
and puts:
#include<stdio.h> main()
{
char name[20]; printf("enter
the string\n"); gets(name); Output:
puts(name); enter the string
return(0); hello my friend
} hello my friend
61
I YEAR/I SEM
Program to convert character from lower case to uppercase and vice versa:
#include<stdio.h> Output 1:
int main() enter the character
{ g
char a; G
printf("enter the character\n"); Output 2:
a=getchar(); enter the character
if(islower(a)) G
putchar(toupper(a)); g
}
else
{
putchar(tolower(a));
} return(0);
}
Difference Between Formatted And Unformatted Input/Output Functions:
Formatted Unformatted
1. These are standard input output library These are console input output library function.
function.
2. Formatted input and output functions can Unformatted input/output can deal with one
deals with all kind of data types. character at a time and string function for array of
characters (string).
3. Unformatted Input / Output functions Formatted Input / Output functions are several
have fixed format to give the input and standard library functions
obtain the output.
- Decision making and branching statements are used to decide the order of execution of
statements based on certain conditions.
- Decision making and branching statements are used to transfer the program control from
one point to another.
- They are categorized as
Conditional statements
Unconditional statements
Conditional statements:
Conditional statements also known as Selection statements. In this, the program control is transferred
from one point to another based upon the outcome of certain condition. The following conditional
statements are available in C:
1. if statement
2. if-else statement
3. nested if statement
4. else-if ladder
5. switch statements
62
I YEAR/I SEM
1. if statement
If the condition is true, the statements inside if statement will be executed.
If the condition is false, the control will be transferred to the statements outside of if.
2. if...else statement
In this, else statement can be combined with if statement.
If Condition is checked first.
If the condition is true, statements inside the if part is executed
When the condition is false, statements in else part is executed.
63
I YEAR/I SEM
64
I YEAR/I SEM
If 'expression' is false the 'statement-3' will be executed, otherwise it continues to check the condition
for 'expression 1' .
If the 'expression 1' is true the 'statement-1' is executed otherwise 'statement-2' is executed
65
I YEAR/I SEM
4. else-if ladder :
If there are more than three alternatives, we can go for else if ladder.
Once a true condition(if) is satisfied, the other statements in the ladder will be skipped.
When all conditions became false, then the final else part which contains default statement will be
executed.
66
I YEAR/I SEM
67
I YEAR/I SEM
}
else
printf("Root are imaginary\n");
}
Program to find the entered key is an alphabet or numeric Output:
or alphanumeric(using character Build-in functions) Enter any key
#include<stdio.h> 8
int main() Entered key is number
{
char a;
printf("Enter any key\n");
a=getchar();
if(isdigit(a))
printf(" Entered key is number");
else if(isalpha(a))
printf("Entered key is alphabet");
else
printf("Entered key is alphanumeric");
return(0);
}
Program to find the entered key is an alphabet or numeric or Output:
alphanumeric(using print, scanf statements) enter a single character or
#include<stdio.h> value
int main() [
{ Alphanumeric
char ch;
printf("enter a single character or value \n"); scanf("%c",&ch);
if((ch>='a')&&(ch<='z'))
printf("Alphabet\n");
else if((ch>='0')&&(ch<='9'))
printf("Number\n");
else
printf(("Alphanumeric\n")); return(0);
}
Note:
In if statement, a single statement can be written without using curly braces { }
Eg, int x=2;
if(x > 4)
printf("welcome");
In the above case, no curly braces are required, but if we have more than one statement
inside if condition, then we must use curly braces.
Other than 0(zero), all other values are considered as true.
Eg, if(9)
printf("welcome");
In above example, hello will be printed, because the integer 9 is a non zero value.
68
I YEAR/I SEM
Switch statement:
C provides a multi way decision statement called switch statement.
It allows the user to make a decision from number of choices.
The expression(condition) in switch case return an integer value or character constant, which is
compared with the values in different cases.
When the condition matches with the case ,that block of statement is executed.
If there is no match, then default statement is executed.
Note:
It isn't necessary to use break after each block, but if you do not use it, all the consecutive block of codes will
get executed after the matching block.
int i = 1;
switch(i)
{
case 1:
printf("A"); // No break case 2:
printf("B"); //No break case 3:
printf("C");
break;
}
Output : A B C
- The output was supposed to be only A because only the first case matches, but as there is no break
statementaftertheblock,thenextblocksareexecuted,untilthe cursor encounters a break.
Rules for switch Statement:
o Default case is optional andcan be placed anywhere in the switch case. But Usualy we place itattheend.
69
I YEAR/I SEM
70
I YEAR/I SEM
break;
case 4 :
printf("Division is %d : ",a/b); break;
default :
printf(" Enter Your Correct Choice."); break;
}
return(0);
71
I YEAR/I SEM
while Loop:
It is an entry controlled looping statement.
Statements are executed repeatedly until the while condition is true.
It is completed in 3 steps.
Variable initialization. ( e.g int x=0; )
Condition Checking ( e.g while( x<=10) )
Variable increment or decrement ( x++ or x-- or x=x+2)
Description:
Step 1: The while condition is checked first.
Step 2: If the condition is true, the statements inside the loop will be executed, then the variable value is
incremented or decremented at the end of the looping statement.
Step 3: If the condition is false, the loop body will be skipped and the statements after the while loop will
be executed.
72
I YEAR/I SEM
73
I YEAR/I SEM
}
if(rev == n )
printf("It is a palindrome no.\n"); else printf("it is
not a palindrome no.\n"); return(0);
}
To Check Armstrong number or not: Output:
#include <stdio.h> Enter a number
int main() 153
{ Its an Armstrong number
int n, arm = 0, dig, temp;
printf("Enter a number\n");
scanf("%d", &n);
temp=n;
while (temp != 0)
{
dig = temp %10;arm= arm + (dig*dig*dig);
temp = temp/10;
}
if(arm==n)
printf("Its an Armstrong number"); else
printf("Its an not Armstrong number"); return(0);
}
do whileloop:
74
I YEAR/I SEM
75
I YEAR/I SEM
While Do while
Conditionistestedfirstandthen statements are Statements are executed at least
executed. once. then the conditions are tested.
While loop is entry controlled loop Do wile loop is exit control
loop.
76
I YEAR/I SEM
for loop:
for loop is usedtoexecutea set of statements repeatedlyuntilaparticularconditionis satisfied.
Flow of Execution:
i. The initialization step is executed first, and only once. This step allows to declare and initialize
any loop control variables.
ii. Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the
body of the loop will not be executed and flow of control jumps to the next statement just after
the for loop.
iii. After the body of the for loop executes, the flow of control jumps back up to the
increment statement. This statement allows to update any loop control variables.
iv. The condition is now evaluated again. If it is true, the loop executes and the process repeats itself
(body of loop, then increment step, and then again condition). When the condition becomes
false, the for loop terminates.
Different ways of implementing for loop:
Form Comment
for(i=0;i<10;i++) Statement1;
Single Statement
for ( i=0 ; i < 10;i++) ; For Loop with no Body ( Carefully Look at
the Semicolon )
78
I YEAR/I SEM
79
I YEAR/I SEM
{
int i, n, a = 0, b = 1, next; printf("Enter
the number of terms: "); scanf("%d",
&n);
for (i = 1; i <= n; ++i)
{
printf("%d,",a); next=a+b;
a=b;
b=next;
}return 0;
80
I YEAR/I SEM
Flowchart:
81
I YEAR/I SEM
2) continue statement:
C Continue statement are used to skips the rest of the current iteration in a loop and returns to the top
of the loop.
Syntax:
continue;
82
I YEAR/I SEM
Example:
Use of break statement to Output: Use of continue statement to Output:
print numbers: print numbers:
#include <stdio.h> enter the enter the
int main()
number: 10 #include <stdio.h> number: 10
{ int main()
int i,num; 1 { 1
printf("enter the number: "); 2 int i,num; 2
scanf("%d",&num);
3 printf("enter the number: "); 3
for(i=1;i<=num;i++)
{ 4 scanf("%d",&num); 4
if(i==5) for(i=1;i<=num;i++) skipped
{ { 6
printf("stop"); break; if(i==5)
7
} {
8
printf("%d\n",i); printf("skipped\n");
continue; 9
}
return(0); } 10
} printf("%d\n",i);
}
return(0);
}
Break Continue
Break statement is used to transfer the Continue is used to skip some statement of
controlof the program to outside loop or the loop and moves to the next iteration in the
switch case statement. loop.
It is used in loop as well as switch case. It is used only within the loop.
Syntax: break; Syntax: continue;
3) goto statement:
The goto statement is used for altering the normal sequence of program execution by
transferring control to some other part of the program.
When a goto statement is encountered in a C program, the control jumps directly to the label
mentioned in the goto statement.
It us used when loops are deeply nested and simple break statement cannot work
effieciently.
Syntax:
goto label_name;
…
…
label_name
83
I YEAR/I SEM
Preprocessor Directives:
Preprocessor is a program which will be executed automatically before passing the source program
to compiler. This process is called pre-processing.
The preprocessor provides the ability for the inclusion of header files, macro expansions,
conditional compilation, and line control.
Commands used in preprocessor are called preprocessor directives.
They begin with "#" symbol and should be not ended with (;)
Proprocessor Directive can be place any where in the program, but generally it place top of the program
before defining the first function.
Preprocessor directives in C:
Macro substitution directives. example: #define
File inclusion directives. example: #include
Conditional compilation directive. example: #if, #else, #ifdef, #undef, #endif
Miscellaneous directive. example: #error, #line
84
I YEAR/I SEM
Syntax Example
#include "filename" #include"example.c" #include<stdio.h>
#include <filename>
The filename is quoted in quotes (“ ”), then it searches that file in current directories.
When the filename is quoted in angle brackets (< >), then it searches the file in standard
directories only.
(iii) Conditional Directives:
#if, #else and #endif:
If given condition is true, "If" clause statement is included in source file . Otherwise, else clause statement
is included in source file for compilation and execution.
85
I YEAR/I SEM
Example: Tocheck the Vote eligibility using #if, #else and #endif
#include<stdio.h> Output:
#define AGE 5 Not eligible
int main()
{
#if (AGE>=18)
{
printf("Eligible for voting");
}
#else
{
printf("\n Not eligible");
}
#endif
return(0);
}
#ifdef, #else and #endif:
- #ifdef" directive checks whether particular macro is defined or not.
- If it is defined, "If" clause statements are included in source file. Otherwise, "else" clause
statements are included in source file for compilation and execution.
- In the below example1 macro is not defined. So, else part is executed.
Example: Example:
#include<stdio.h> #include<stdio.h>
int main() #define AGE 1
{ int main()
#ifdef AGE {
{ #ifdef AGE
printf("Eligible for voting\n"); {
} printf("Eligible for voting\n");
#else }
{ #else
printf("Not eligible\n"); {
} printf("Not eligible\n");
#endif }
return(0); #endif
} return(0);
}
Output: Output:
Not eligible Eligible for voting
undef
This directive undefines existing macro in the program.
In below program we first undefine age variable and again it is defined with new value.
Example: Undefining the macro Output:
#include<stdio.h> First define value for age is:
#define age 20 20
86
I YEAR/I SEM
PART A:
1. What are variables? Give Examples (M/J’16)(N/D’14)
2. Define implicit type conversion (M/J’16)
3. What is an array? Give Example (M/J’16) (M/J’15)
4. Define strings. Give examples(M/J’16)
5. What is meant by linking process? (N/D’15)
6. What are the input functions and output functions in C? (N/D’15) (M/J’15)
7. Write a C program to store Fibonacci series in an array. (N/D’15)
8. List the string functions available in C. (N/D’15)
9. List some pre-processor directives. (N/D’15)
10. What are the importance of keyword in C? (M/J’15)
11. How is a character string declared? (M/J’15)
12. Give the use of pre-processor directives. (M/J’15) (N/D’14) (M/J’14)
13. Give an Example of ternary operator. (N/D’14)
14. Describe float array of size 5 and assign 5 values in it. (N/D’14)
15. Give an example for initialization of string array.
16. Define static storage class. (N/D’14)
17. List different data types available in C. (M/J’14)
18. Write a C program to find factorial of the number using iteration. (M/J’14)
19. Write an example code to declare two dimensional array. (M/J’14)
20. List any 4 string handling functions (M/J’14)
PART B:
1. Explain different types of operators in detail.(M/J’16) (M/J’15) (N/D’14)
2. Discuss basic data types in C (M/J’16)
3. Describe various input and output statements in detail. (M/J’16)
4. Write a C program for the following series 1+2+3+4+…N (M/J’16)
5. Write a C program to convert the number of vowels in your name (M/J’16)
6. Write a C program to multiply two matrices/ Write a C program for two 3*3 Matrix
(M/J’16)/(N/D’15) (N/D’14)
7. Write a C program to check whether the given string is palindrome or not (M/J’16)
8. Write a C program to arrange the given 10 numbers in descending order (M/J’16
9. Explain various storage classes in detail. (M/J’16) (N/D’15) (M/J’15) (M/J’14)
10. Describe about pre-processors with suitable examples. (M/J’16)
87
I YEAR/I SEM
11. Describe the structure of C program using ‘calculator program’ example. (N/D’15)
12. Write short notes on branching statements in C. (N/D’15)
13. Write in detail about various looping statements with suitable example.(N/D’15) (M/J’15)
(N/D’14)
14. Write a C program to find determinant of the resultant matrix. (N/D’15)
15. Write the following programs (N/D’15)
(i) To sort the given set of strings alphabetically
(ii) To print whether each word is palindrome or not
(iii) To count the length of the string
16. What are constants? Explain various types of constants in C. (M/J’15)
17. Write a C program to solve(roots of) Quadratic Equation ((M/J’15) (M/J’14)
18. Write a C program to add two matrices. (M/J’15)
19. Write a C program to search a number in an array of elements. (M/J’15) (N/D’14)
20. Write a C program to arrange the given 10 numbers in ascending order/ Write a C program to
sort array of numbers. (N/D’14) (M/J’15) (M/J’14)
21. Explain various string handling functions in C. (M/J’15)
22. Explain various string operations. Write a C program to find the length of the string without
using build in function. (N/D’14)
23. Write a short notes on (i) #include<stdio.h> (ii) ifdef.. # endif (N/D’14)
24. Write a C program to check the given number is prime or not (M/J’14)
25. Write a C program to find sum of digits of a number (M/J’14)
26. Explain entry and exit checked conditional structure with example(M/J’14)
27. Write a C program to subtract two matrices and display the resultant matrix.(M/J’14)
28. (M/J’14)
***************