Unit - 2 Notes
Unit - 2 Notes
C PROGRAMMING BASICS
Problem formulation is an approach that allows the user to identify the problem, define the problem and find
solution to the problem in an organized way.
There are certain steps that should be followed in formulating the problem.
Example
In order to solve the odd/even problem we need to know what is an odd number and what is an even number.
Modulus operator (%) gives the remainder of the number when divided by another number.
For example the value of 15%7 =1, because when 15 is divided by 7, the remainder is 1.
An algorithm can also be called as “rough program”. An algorithm is a previous step to a program. Once the
logic has been identified the algorithm can be developed easily. To develop algorithm the following steps
should be followed.
Example
Step a - start
Step f – End
So first we need to convert the algortithm into a programming language code, for example a high level
programming language code such as C. Then we need to use system software such as compiler to convert the
high level language into machine level language.
The process of converting the algorithm into programming language is called as “developing code”.
int a;
if(a%2==0)
{
printf(“EVEN”);
}
else
{
printf(“ODD”);
}
2.1.6 Testing
Testing is the process of identifying the error/bugs in a program.
There are two main types of errors, syntax and logic error(s).
Syntax errors
Syntax errors are mistakes in syntax, spelling, or punctuation. A compiler will notify the syntax error, if any
In the above C program if you have typed “eles” instead of “else” then it is a syntax error.
Note: if you have a syntax error, the program will not execute.
Logic Errors
These are errors that make a program to produce unexpected results. These are more difficult to find. No
compiler will inform or notify about a logic error. The programmer only has to find the logic errors by
themselves.
In the above C program if you have typed “a%5” instead of “a%2” then it is a logical error.
Note: if you have a logical error, the program will execute but it will not give you the expected output.
2.2.1 Introduction
Problem solving is a complicated process that needs in depth understanding of the problem ,ability to think
logically and careful planning. Problem solving means developing an algorithm that solves the problem. An
algorithm corresponds to a solution to a problem that is independent of any programming language.
Usually a program accepts the input ,manipulates the input according to the instructions and produces an
output, which is a solution to the given problem
What is the information that I have to process in order the find the solution?
What are the suitable ideas that will lead to the solution?
We should develop an Outline about the problem and its requirements. Then we should Design steps
(algorithm) to solve the problem
Maintenance
Brute force is a straightforward approach to solve a problem. It is based on the problem’s statement and
definitions. It is considered as one of the easiest approach. It is useful for solving small instances of a problem.
Greedy Algorithms
The solution is constructed through a sequence of steps by choosing the best option available at each step.
It is the process of splitting the problem into several smaller problems. Then each of these sub problems are
solved independently. Finally the solutions of the sub problems are combined to obtain a solution for the
original problem.
Top-down approach starts with the top level module and progresses downward to the lowest level module
Dynamic Programming is a Bottom-Up Technique in which the smallest sub problems are explicitly solved
first and the results of these are used to construct solutions for larger sub-problems.
Bottom-up approach proceeds with the design of lowest level module or subsystem, to the highest module or
subsystem.
Transform-and-Conquer
These methods work as two-stage process. First, the problem is modified into form that will be suitable to
obtain the solution. In the second stage the problem is solved.
user user
kernel
os +
application
computer computer
ADVANTAGES
It is readily available in computer understandable form.
No need for translation
Since there is no need for conversion, it executes very fast
DISADVANTAGES
Difficult to memorize the OPCODE
Varies from machine to machine
Not user-friendly
Prone to errors
Difficult and tedious to write.
ADVANTAGES
Since numerical codes are replaced by mnemonics, it is easy to understand and use.
Less error prone
It occupies less memory space.
It executes faster than high level
DISADVANTAGES
It is difficult to memorize all the mnemonics
Since different machines support different instructions set and hence different assembly language, there
is no standard assembly language.
It takes more time to develop an assembly language
It does not support modern software technologies
High Level Language is Portable. To write assembly code it is necessary to know the architecture of the
processor or controller. To write a High Level Program it is not necessary to know the architecture
completely.
ADVANTAGES
Since high level language is simple English, it is easy to understand and interpret without much effort.
It is machine independent and not specific to any particular architecture. A high level language written
on one machine can run on any machine.
Supports debugging and error handling with the help of debugger
DISADVANTAGES
It does not directly communicate with hardware
Computation time is more, since a program in a high level language needs to be converted into an
assembly language and then into machine language.
Why use C?
1. Because it produces code that runs nearly as fast as code written in assembly language.
2. Because it supports all the features of high level language.
Since C connects the features of assembly language and the functionalities of high level language, it is also
called as middle level language.
C is used to develop :
Operating Systems
Language Compilers
Assemblers
Text Editors
Print Spoolers
Network Drivers
Modern Programs
Data Bases
Language Interpreters
Utilities
The following is a partial list of areas where C language is used:
Embedded Systems
Systems Programming
Artificial Intelligence
Industrial Automation
Computer Graphics
Space Research
Image Processing
Game Programming
2.4.3 Evolution of C
Where C Stands?
Computer Languages can be categorized two ways
1. Machine Oriented Languages (Ex-Assembly Languages)
2. Problem Oriented Languages (Ex-Basic, Fortran, Pascal)
Machine oriented languages have better machine efficiency and so called as Low Level Languages (LLL).
Problem oriented languages have better program efficiency and so called as High Level Languages (HLL).
C does not follow any of these categories. C falls in between two category. C is a neither High level nor Low
level. C is a Middle Level Language (MLD).
Documentation Section
Linker/Preprocessor Section
Definition Section
main()
{
Variable declaration section;
Function declaration section
Executable statements;
}
Documentation Section
The documentation section consists of a set of comment lines specifying the name of the program, description
about a statement and other details, which the programmer would like to use later.
Example :
/* This program developed by Mr dennis ritchie
on 1/2/1988 */
//Sum of 2 number
Note: // it indicates single line comment and /* */ indicates multi-line comment
Link/Preprocessor Statements
The preprocessor statement begins with # symbol and is also called as the preprocessor directive.
These statements instruct the compiler to include C preprocessors such as header files and symbolic constants
before compiling the C program.
Some of the preprocessor statements are listed below.
#include<stdio.h>
#include<conio.h> Header files
#include<math.h>
#include<stdlib.h>
Definition Section
It is used to define or set values to variables and define symbolic constants
Example: #define PI 3.14
Symbolic Constants
#define TRUE 1
#define TN TamilNadu
Global Declaration Section
In C There are two types of declarations
1. Local variable declaration
2. Global variable Declaration
Global variables are declared outside the main function. Local variables are declared inside the main function.
These global variables can be accessed by all the user defined functions including main ( ) function, whereas a
local variable can be accessed by only the main() function.
main() function
Every C program must have one main function section. This section contains two parts, declaration and
executable part.
Note: The C program execution starts with main ( ) function.
General form:
main()
{
local variables declaration
computational part
logical part
}
Variable Declaration
It declares all the variables that will be used in the executable part.
All statements in the declaration part should end with the semicolon.
Syntax:
Data-Type Variable-Name;
Example:
int a,x;
float b,c;
char name;
Executable part
It consists if single statement or block of statements that contain instructions to perform certain task.
Example:
a=x*x;
Subprogram Section
The Subprogram Section contains all the user defined functions that are called in the main function.
Explanation
//Program for calculating the area of a circle Comment
Preprocessor Directive
#define pi 3.14
The Semicolon
The semicolon serves as the statement terminator. Each executable statement should have a “;” to inform the
compiler that the statement has ended. Thus, in ‘C’ the semicolon terminates each statement.
Note: if you forget to place a semicolon before a statement, then “statement missing” error will be generated by
the compiler
Compiler: If the translator translates a high level language into a lower level language it is called a Compiler.
Interpreter: If the translator translates each statement in a high level language into an intermediate code
immediately before executing the next statement in a line by line manner, it is called an Interpreter.
When an error is encounter, the execution will not go to the next instruction.
Decompiler: If the translator translates target/machine code to source language it is called a Decompiler.
Assembler: If the translator translates assembly language to machine code it is called an Assembler.
Disassembler: If the translator translates machine code into assembly language it is called a Disassembler.
Need for a linker : It is a Tool that merges the object files produced by the compilation process and creates an
executable file
Need for a loader: Loader is a Part of the Operating System that brings an executable file residing on disk into
memory and allows the file to be executed.
#include<stdio.h>
void main()
Source Code
{
printf(“Hai”);
}
i.e., AltIf+compilation
F9 errors
Object File
i.e., Ctrl + F9
Executable
Code
Entering, Translating, and Running a High-Level Language Program
Flow of Execution
Source Code Object Code Execute Code
Compile Run
Program.C Program.obj Program.exe
Save
Program.bak
Backup Code
Step1:
Whenever you create a program, it is called as source code (Program.c). When you save the program, the
compiler automatically creates a file with “bak” extension (Program.bak).
Step2:
After compiling the program, an object file is created (Program.obj).
Step3:
After executing the code an executable file is generated.(Program.exe).
Alphabets: A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
abcdefghijklmnopqrstuvwxyz
Digits: 0123456789
Symbols:
~ Tilde “ Quotation mark ` Apostrophe
! Exclamation mark ; Semicolon - Minus sign
# Number sign < Opening angle bracket = Equal to sign
$ Dollar sign > Closing angle bracket { Left brace
% Percent sign ? Question mark } Right brace
^ Caret , Comma [ Left bracket
& Ampersand . Period ] Right bracket
* Asterisk / Slash : Colon
( Left parenthesis _ Underscore + Plus sign
) Right parenthesis | Vertical bar \ Backslash
Delimiters:
Symbol Delimiters Use
: colon used at the end of a label
; Semicolon Used at the end of the statement
() Parenthesis Used in expressions and function
[] Square bracket Used for array declaration
{} Curly braces Used to represent block of statements
# Hash Used in pre processor directives
, Comma Used to separate values
2.6.3 C Tokens
Smallest individual units in C program are known as token.
Example: Data Types, Constants, variables and Keywords
C token is any individual word present in the c-language.
There are classified into six types
Keywords
Keywords are special word reserved by the compiler.
Each keyword has a specific purpose.
In c language there are 32 keywords
Constants:
The value which will not be changed during the execution of the program are called constants
Example: 5,7.25,’a’ etc
Note: usually a constant will be place on the right hand side of the assignment operator (=).
variables:
The values which may be changed during the execution of the program are called variables.
Example: marks, height, sum etc
Note: usually a constant will be place on the left hand side of the assignment operator (=).
marks = 70
variable Constant
Assignment
operator
Strings:
Group of characters enclosed within double quotes " "
Example:”I am a string”
Operators:
Operators are mathematical symbols which are used in evaluation of expression.
Example: +,-*,/ etc
Special Symbols:
Each special symbol has its own meaning
Comma (,) – It is used to separate values.
Semi colon (;) –It is used to notify the end of a statement.
Ampersand (&) –It is used to print the address of a variable.
2.6.4 Constants
Why Constants?
Constants can be very useful in C programming whenever you have a value that will be repeated in a program.
You can declare a constant and use it in your program as many times you want, and if you want to change the
value of the constant you need not change every occurrence of the constant but only its declaration.
What is Constants?
Constants are values that never change. (The constants value is locked for the entire duration of the program).
Pi for instance is a good example to declare as a constant.
Example pi =3.14;
Types of Constants
Constant can be classified into the following.
1. Primary Constants
2. Secondary Constants
Primary constants are further classified into Integer constant, real constant, single character constant, string
constant, string constant Backlash character constants.
Constants
Character Constant
A character constant is a character which is enclosed in single quotes.
The size of a character constant is 1 byte and can contain only 1 character.
A character can be an lowercase alphabet like a, b etc or an uppercase alphabet like A,C etc or a special
character like &,^, $, #,@ etc or a single digit from 0 to 9.
It can also be an escape sequence character like space ‘ ‘ , a null character ‘\o’ or a new line character ‘\n’ etc.
Rules for Constructing character Point Constants
- A character constant should be an alphabet, a single digit or a single special symbol enclosed within
inverted commas.
- Both the inverted commas should point to the left. For example, ’R’ is a valid character constant
whereas ‘R’ is not.
- The maximum length of a character constant can be 1 character. 1 byte of memory is allocated
Example: ‘A’ ‘a’ ‘b’ ’8′ ‘#’ etc.
String Constants
A string constant is a collection of characters enclosed in double quotations “”. It may contain alphabets, digits,
special characters and blank space.
Rules for Constructing String Constants
- A character string, a string constant consists of a sequence of characters enclosed in double quotes.
- A string constant may consist of any combination of digits, letters, escaped sequences and spaces.
Note: A character constant ’A’ and the corresponding single character string constant "A" are not equivalent.
Example: “Monday” “C programming” “123”
Difference between character constant and string constant
Character Constant String Constant
A character constant is enclosed within single A sequence of characters enclosed in double
inverted commas. quotes
The maximum length of a character constant is one A string constant can be of any length.
character.
A single character string constant has an equivalent A single character string constant does not
integer value (ASCII value). have an equivalent integer value.
Example: Equivalent value of lowercase letter ‘d’
is 100
A single character requires one byte. A single string constant requires two bytes.
One byte for the character constant and another
byte for “null” (\0) character.
Example: Example:
char a = ‘d’; char a[] = ‘d’;
d d \0
1010 1010 1011
Every character constant does not end up with a Every string constant ends up with a NULL
NULL character. character (‘\0’). It is automatically assigned by
the compiler
void main()
{
int a =10; // integer constant
float b = 7.25; // floating point constant
char c =’a’; // character constant
char d[4] = “hai”; // string constant
char d[2] = “a”; // single string constant
}
1. ‘\t’ Character
It is Horizontal Tab
The cursor is moved forward 8 spaces
#include<stdio.h>
int main()
{
printf("Hello\t");
return(0);
}
Hello _
2. ‘\n’ Character
#include<stdio.h>
int main()
{
printf("Hello\n");
return(0);
}
Hello
_
3. ‘\b’ Character
It is Backslash Character
It moves cursor one position back
#include<stdio.h>
int main()
{
printf("Hello\b");
return(0);
}
Hello
4. ‘\r’ Character
#include<stdio.h>
int main()
{
printf("Hello\r");
return(0);
}
Hello
Note : the cursor is on ‘h’ character in the Word “Hello”
5. ‘\a’ Character
printf("Hello\a");
Hello_
Note: After printing hello, the System will give a Beep sound.
.
2.6.5 Variables
Introduction
The variables are nothing but the name given to a value.
Example: marks=72
In the above example 72 is a value and we give a name called “marks” to that value. Here the “marks” is a
variable.
We usually remember a person by their name rather than by their mobile number. So we can store their mobile
number(value) by their name(which we can easily remember)
Example: Raja=987654321
In the above example Raja(name) is the variable and 987654321(mobile number) is the value
Note: similar to the constants, variables are also classified into different types but the value of the variable
can be changed during the execution of the program.
Example 1: 3ab
It is Contrary to rule 1 as it starts with a number
Example 2: $marks
It is Contrary to rule 2 as it contains the special symbol $
Storage class
Here memory space is reserved for the variable value b under auto storage class.
Initialization
The purpose of initialization is to assign a value to the variable.
E.g.: a=5;
Here the value 5 is assigned to the variable a.
Note: If the variable is not initialized after declaration, it will contain some random value called the
garbage value.
Datatype
User
primary Derived
defined
Note: so one should know the range of the data type to avoid the above problem
Format specifier:
Format specifiers are the operators used in printf() function to print the value which is referred by a
variable.
We can retrieve the data stored in the variables and can print them on to the console screen by using
these format specifiers in a printf() function.
It tells the compiler whether the integer, character or floating point value should be printed
Format specifiers start with a percentage (%) symbol and follow a special character to identify the type
of the data.
Example %d, %f etc
Type Definition
In C language a user can give a new name to an existing data type. The user defined data type identifier can later
be used to declare variables.
Syntax:
typedef type identifier
Here ‘typedef’ is the keyword, ‘type’ represents existing data type and ‘identifier’ refers to the new name given
to the data type.
Example:
typedef int salary;
Now we can declare a variable by using
salary abc;
instead of using
int abc;
Program
//Typedef Example
#include <stdio.h>
#include <stdlib.h>
void main()
{
typedef int salary;
salary a=100;
printf("My Salaray = %d",a);
}
Output :
My Salary = 100
Enumerated Data Type
The enumerated data type also called as enum is user defined data type
Enumerated data types are particularly useful while creating a new data types that can take only a restricted
range of values.
For Example, the direction can take only four values such as north, south, east and west.
If set the value of direction to be 123, then it would be meaningless so we use enumerated data types to restrict
such meaningless assignment.
Syntax:
enum identifier {value1,value2,value3…..valueN}
Example :
enum directions { NORTH,SOUTH,EAST,WEST };
2.6.7 Type Conversion
A type conversion is the process of converting one data type into another data type. This is sometimes also
called as type casting.
For example if you want to store a float value into an integer then you can type cast float to int.
Casting
Conversion between data types can be done in two ways by casting:
Implicit casting
Explicit casting
Implicit casting
Implicit casting doesn't require a casting operator. This casting is normally used when converting data from
smaller integral types to larger integral types.
int x = 123;
float y = x;
In the above statement, the conversion of data from int to float is done implicitly, in other words programmer
doesn’t need to specify any casting operators.
It is also called as automatic Type casting.
Explicit casting
This casting is normally used when converting a larger data type to smaller data types. Explicit casting requires a
casting operator.
Syntax
<variable>=(datatype)<expression>
Example
float y = 123;
int x = (int)y;
In the above Example, we have to specify the casting operator (int) explicitly when converting from float to int,
because the size of the float is 4 bytes and size of the integer is 2 bytes and we cannot fit 4 byte value into a 2
byte value.
2.6.8 Keywords
Pre increment operator first increments the value and then assigns the value to the variable.
Example
c=++a;
If the value of a=5 ,then the value of c will be 6
Post increment operator first assigns the value to the variable and then increments the value.
Example
C=a++;
If the value of a=5 ,then the value of c will remain 5 as it will be incremented only after assigning
Decrement operator
It is used to decrease the value of operand by 1;
It can be written as
a-- or a=a-1;
If the value of a is 5 then after decrement the value of a will be 4.
The test expression contains the expression to be evaluated and if the value of the test expression is true then
Expression1 is executed and if the value of the test expression is false then the value of the Expression2 is
executed
Output:
positive
If the value is greater than zero the compiler prints as positive, else it prints as negative
Example
int i , j;
i=(j=10,j+20);
Here the expression j=10 is first evaluated (the value of j is 10) and then the expression j+20 is then evaluated
(now the value of j is 30) and finally the value of j is assigned to i.
sizeof operator
The sizeof operator returns the size of its operand in bytes.
The general syntax of the sizeof operator is
sizeof(operand)
Example
int i;
char j;
We already know that the length of the integer is 2 bytes and length of the character is 1 byte.
so,
sizeof(i) returns the value of 2 and
sizeof(j) returns the value of 1
Remark
Operator Left Right
So only for the / operator the left operand is unambiguous and so it will be evaluated first.
Now x = 2* 6.
Here * has higher priority than = and it is evaluated(2*6 = 12)
Now x = 12
Finally the assignment operator = is evaluated and the value of 12 is assigned to the variable x
Console I/O in general means communications with the computer's keyboard (input) and display (output).
The program uses console I/O
To simply read its "standard input (stdin)" - which might be the keyboard, a file dump, or the output of
some other program.
To print its "standard output (stdout)" -- which might be the monitor or printer or another program or a
file.
I/O can be classified into two broad categories
(a) Console I/O functions - Functions to receive input from keyboard and write output to display screen.
(b) File I/O functions - Functions to perform I/O operations on a disk or file.
2.8.2 Input and Output Functions
There are numerous I/O functions and are listed below
2.8.3 Formatted I/O Functions
In the formatted I/O functions, the input data or the output function are formatted as per requirement.
It gives a clear and legible view of the output.
With the formatted I/O functions one can decide how the output should appear on the screen.
The formatted I/O functions have a format string (%d, %s) in the function.
2.8.3.1 printf()
The formatted function used to display the output is printf().
If you are going to print any message ,you can simply include the message within the double quotes in the
printf() function
Example
void main()
{
printf(“my message”);
}
If a variable has to be printed, then the data type of the variable should also be specified using the format
specifier.
Syntax
printf(“format specifier”, variableName);
Example
void main()
{
printf(“%d”,a);
}
Generally, the variable will be printed only in the format specified by the format specifier.
Consider the example program
void main()
{
char variable=’a’;
printf(“%d”,a);
}
Output:
97
Now we may not able to predict the output as the variable a is declared as character data type and the
format specifier is given as %d (integer data type)
As it is mentioned earlier the variable a will be converted into integer data type (the corresponding ASCII value
of a is 97) and the output will be displayed as 97.
Here the string welcome consists of seven characters (7 bytes) and so the output will be printed as 7.
unsigned char c
int or signed int d or i
unsigned int u
short int or signed short d or i
int
unsigned short int u
long int or signed long int ld
unsigned long int lu
float f or g
double lf
long double lf
Note : printf() based other formated I/O funcation are cprintf(), fprintf(), sprintf(), vfprintf(), vprintf(),
vsprintf()
2.8.3.2 scanf()
The formatted function used for getting the input from the user is scanf().
Syntax
scanf(“control string ”,&variable)
Example
scanf(“%d”,&a);
In the above example, an integer value is obtained from the user and it is stored in the variable a.
%d is the format specifier and it specifies the data type of the input variable.
The format specifier should be enclosed within the double quotes. Few basic format specifiers are listed below.
%d-the data is taken as integer
%c-the data is taken as character
%f-the data is taken as float
%s-the data is taken as string
Output:
C
0XC
14
014
12
12.0
+10
printf( "|%-5d|%-5d|\n", 1, 2 );
output:
|1 |2 |
Here the width is set as 5(%5d) and a minus flag has been included (%-5d), but the number 10 has only two
digits, so the remaining three spaces will be filled by blank spaces after the number 10.
Example program
void main()
{
printf( "%05d\n", 1);
printf( "%04d\n", 1);
printf( "%03d\n", 1);
printf( "%02d\n", 1);
printf( "%01d\n", 1);
printf( "|%-5d|\n",2 );
printf( "|%-4d|\n",2 );
printf( "|%-3d|\n",2 );
printf( "|%-2d|\n",2 );
printf( "|%-1d|\n",2 );
}
Output:
00001
0001
001
01
1
|2 |
|2 |
|2 |
|2 |
|2|
Precision
The "precision" modifier is written as ".number".
It has slightly different meanings for the different conversion specifiers (like %d or %g).
If the number has less precision than specified, it will be filled with zeros.
For example:
Example program:
void main()
{
printf( "%.6f\n", 1.2348 );
printf( "%.5f\n", 1.2348 );
printf( "%.4f\n", 1.2348 );
printf( "%.3f\n", 1.2348 );
printf( "%.2f\n", 1.2348 );
printf( "%.1f\n", 1.2348 );
printf( "%.0f\n", 1.2348 );
}
Output:
1.234800
1.23480
1.2348
1.235
1.23
1.2
1
Example:
printf( "%.3f\n%.3g\n%.3f\n%.3g\n", 100.2, 100.2, 3.1415926, 3.1415926 );
For integers(%d)
It controls the minimum number of digits that is to be printed.It fills the remaining spaces with zeros at the
beginning
Example 1
printf( "%.3d", 10 );
output:
010
For strings(%s)
It controls the maximum length of the string displayed
Example:
printf( "%.5s\n", "abcdefg" );
output:
"abcde"
Note: if you specify as '.0', then the number will have no output:
Example:
printf( "%.0s", “abcdefg” );
It has no output!
Example program:
void main()
{
printf( "%.6d\n", 125 );
printf( "%.5d\n", 125 );
printf( "%.4d\n", 125 );
printf( "%.3d\n", 125 );
printf( "%.2d\n", 125 );
printf( "%.1d\n", 125 );
printf( "%.8s\n", "abcdefg" );
printf( "%.7s\n", "abcdefg" );
printf( "%.6s\n", "abcdefg" );
printf( "%.5s\n", "abcdefg" );
printf( "%.4s\n", "abcdefg" );
printf( "%.3s\n", "abcdefg" );
printf( "%.2s\n", "abcdefg" );
printf( "%.1s\n", "abcdefg" );
printf( "%.0s\n", "abcdefg" );
}
Output:
000125
00125
0125
125
125
125
abcdefg
abcdefg
abcdef
abcde
abcd
abc
ab
a
Width
It has the same format as precision, but does not have a decimal point.
For integers(%d)
It controls the minimum number of digits that is to be printed.It fills the remaining spaces with blankspaces at
the beginning .
Example 1
printf( "|%3d", 10 );
output:
| 10
For strings(%s)
It controls the minimum length of the string displayed
Example:
printf( "|%8s\n", "abcd" );
output:
| abcd
Example program
void main()
{
printf( "|%6d\n", 125 );
printf( "|%5d\n", 125 );
printf( "|%4d\n", 125 );
printf( "|%3d\n", 125 );
printf( "|%2d\n", 125 );
printf( "|%1d\n", 125 );
printf( "|%8s\n", "abcd" );
printf( "|%7s\n", "abcd" );
printf( "|%6s\n", "abcd" );
printf( "|%5s\n", "abcd" );
printf( "|%4s\n", "abcd" );
printf( "|%3s\n", "abcd" );
printf( "|%2s\n", "abcd" );
printf( "|%1s\n", "abcd" );
printf( "|%0s\n", "abcd" );
}
Output:
| 125
| 125
| 125
|125
|125
|125
| abcd
| abcd
| abcd
| abcd
|abcd
|abcd
|abcd
|abcd
|abcd
Output:
| 34.8
| 34.77
| 34.769
| 34.7689
| 34.76890
| 34.768900
| 34.7689000
|34.76890000
Note: the width considers the entire number including the digits after the decimal point,whereas the precision
considers only the digits after the decimal point.
Note: Macro is a piece of text that is expanded by the preprocessor. This is used to expand the text before
compiling.
Declaration
int getchar(void);
Example Declaration
char ch;
ch = getchar();
Return Value:
This function returns the character read from the keyboard.
Example Program:
void main()
{
char ch;
ch = getchar();
printf("Input Char Is :%c",ch);
}
Program Output:
A
Input Char Is:A
Working of getchar()
During the program execution, a single character is read through the getchar () function.
The given value is displayed on the screen and the compiler wait for another character to be
typed.
If the enter key is pressed, the given character is printed through the printf function.
getch()
getch() gets a character from console but does not print on the screen.
This function reads a character and never waits for Enter key. It just gets processed after the first
key is being pressed.
Declaration:
int getch(void);
Example Declaration:
char ch;
ch = getch(); (or ) getch();
Return Value:
This function return the character read from the keyboard.
Example Program:
void main()
{
char ch;
ch = getch();
printf("Input Char Is :%c",ch);
}
Output:
Input Char Is : A
Working of getch()
During the program execution, a single character is read through the getch().
The given value is not displayed on the screen and the compiler does not wait for another character to be
typed.
As soon as a key is pressed, it returns the character to the getch() function and the returned character is
printed through the printf function.
Note: usually a getch() is given at the last line of the main function ,to ensure that the program waits for
a key to pressed by the user before terminating.
It is done so that the user can view the output screen, otherwise the output screen will go off like a flash.
getche()
getche() is used to get a character from console, and prints to the screen.
This function reads a character and never waits for Enter key. It just gets processed after the first
key is being pressed.
Declaration:
int getche(void);
Example Declaration:
char ch;
ch = getche();
Return Value:
This function return the character read from the keyboard.
Example Program:
void main()
{
char ch;
ch = getche();
printf("Input Char Is :%c",ch);
}
Program Output:
Input Char Is : A
Working of getche()
During the program execution, a single character is read through the getche().
The given value is displayed on the screen and the compiler does not wait for another character to be
typed.
As soon as a key is pressed, it returns the character to the getche() function and the returned character is
printed through the printf function.
putch()
Outputs character to the text window on the screen.
Declaration:
int putch(char ch);
Example Declaration:
ch =getch();
putch(ch);
Return Value:
On success, putch() returns the character printed.
On error, it returns EOF.
Example Program:
void main()
{
char ch = 0;
printf("Input a string:");
while ((ch != '\r'))
{
ch = getch();
putch(ch);
}
}
Program Output:
Input a string : welcome
putchar()
It outputs a single character to the console output(the display screen)
It is used to display single character.
putchar is a macro that outputs a character on stdout.
Declaration
int putchar(char c);
Example Declaration
char c;
c = ‘a’;
putchar(c);
Return Value
putchar returns the character that is displayed
Example Program
void main()
{
int c;
c = getchar();
while(c != EOF)
{
putchar(c);
c = getchar();
}
}
Output:
Welcome to C World
Welcome to C World
Note: We can make putc() work similar to the putchar() by specifying the filename as “stdout”. By doing so the
putc() prints the character directly to the console output.
Declaration Example
char string[80];
gets(string);
Retrun Value:
On success, gets () returns the string argument s.
On error or end-of-file, gets returns null
Example Program:
void main(void)
{
char string[80];
printf("Input a string:");
gets(string);
printf("The string input was: %s\n", string);
}
Output:
Input a string: Welcome To C
The string input was: Welcome To C
puts()
It prints a string to the standard output
Declaration:
int puts(const char *s);
Remarks:
puts() copies the null-terminated string s to the standard output stream stdout and appends a newline character.
Declaration Example
char string[] = "Hai\n";
puts(string);
Example Program:
void main(void)
{
char string[] = “This is Test\n”;
puts(string);
}
Output:
This is Test
Important Points
gets() Vs scanf()
• gets() - Reads characters from stdin and stores them as a string into str until a newline character ('\n') or
the End-of-File is reached.
• scanf()- Reads data from stdin and stores them according to the parameter format into the locations
pointed by the additional arguments(address).
• gets() read the string values which allows white spaces also.
• scanf() doesn't allow white spaces in string values.
puts() Vs printf()
• printf() returns the number of character written
• puts() returns a non-negative value in case of success.
• In printf() you have to use '\n' to do this.
• puts() moves the cursor to next line.
Generally every decision making part will have a condition and if the condition is satisfied one part of the
program will be executed otherwise a different part of the program will be executed. The if and else are two
important keywords in decision making.
Output:
You are Eligible for Vote
Syntax
if(condition)
{
Block1 of statements;
}
else
{
Block2 of statements;
}
Example
if(marks>50)
{
printf(“you passed”);
}
else
{
printf(“you failed”);
}
In the above example the program will print “you passed” only if the mark is greater than 50 else it will print
“you failed”.
Example Program
//Example of if statement
#include<stdio.h>
void main()
{
int age=17;
if(age>=18)
printf("You are Eligible for Vote");
else
printf("You are Not Eligible for Vote");
}
Output:
You are Not Eligible for Vote
Note: Both if and else statements will not end with a semicolon. else statement will not have a condition.
else statement should definitely follow an if statement.
2.9.4 The Nested if Statement
Definition
If the condition1 is true it will check condtion2 and if condition2 is true, it will check condition3…conditionN,
and if all the conditions are true,then the block of statements will be executed.
Syntax
if(condition1)
{
if(condition2)
{
…….
…….
if(conditionN)
{
Block of statements;
}
}
}
Example Program
//Example of Nested if statement
#include<stdio.h>
void main()
{
int a = 100;
int b = 20;
int c = 50
if( a > b )
{
if(a > c)
{
printf("a is the biggest number" );
}
}
}
Output:
a is the biggest number
Note: If any one of the condition in the nested-if structure is not satisfied then the successive conditions
will be skipped and will not be checked.
When we check for an equality condition, double equalto(==) should be used.
Example Program
//Example of if else ladder
#include<stdio.h>
void main()
{
int marks = 67;
if(marks = = 100)
{
printf("You got centum");
}
else if(marks > 80)
{
printf("You got A grade");
}
else if(marks > 60)
{
printf("You got B grade");
}
else if(marks > 40)
{
printf("You got C grade");
}
else
{
printf("you failed");
}
getch();
}
Output:
You got B grade
2.9.6 The switch Statement
Introduction
The switch statement is used to select a particular block of statement among N block of statements for
execution.
It is also called as multiway decision statement
A switch statement allows a variable to be tested for equality against a list of values. Each value is called
a case.
Each case will have a
o test value,
o a block of a statement and
o a break statement at the end.
Switch statements simulate the use of multiple if statement.
1. Play game\n
2. Load game
3. Play multiplayer
4. Exit
Selection:2
Loading the game
}
Output:
press 0 to stop:
Enter a number : 5
Enter a number : 4
Enter a number : 3
Enter a number : 2
Enter a number : 1
Enter a number : 0
sum: 15
Note: Though goto statement is included in ANSI standard of C, use of goto statement should be reduced
as much as possible in a program.
Syntax
for(initialization; condition; increment/decrement)
{
Block of statement;
}
Stepwise execution of for loop:
Step1: A value will be initialized.
Step2: Condition will be checked and if the condition is true then step3,otherwise step 6
Step3: Execute the block of statements
Step4: Increment/Decrement the initialized value
Step5: Goto Step2
Step6: End of for loop
Example:
for(a=10;a<=20;a++)
{
printf(“hai”);
}
In the above example the initial value of the variable a is 10 ,the condition will not be satisfied when the variable
a reaches the value of 21 and so it will come out of the for loop after printing “hai” ten times.
Note :
For Single Line of Code – Opening and Closing braces are not needed.
For Loop can be without a body (it just introduces delay).
For Loop is Entry Controlled Loop.[i.e. conditions are checked and if it is found true, then only code is
executed ]
Program:
Write a program to find the sum of first n natural numbers where n is entered by user.
#include <stdio.h>
void main()
{
int n, count, sum=0;
printf("Enter the value of n.\n");
scanf("%d",&n);
for(count=1;count<=n;++count) //for loop terminates if count>n
{
sum+=count; /* this statement is equivalent to sum=sum+count */
}
printf("Sum=%d",sum);
}
Output:
Enter the value of n.
5
Sum=15
Explanation:
Iteration Value Value Value Condition Value of
of of of Count <= N conditional
N count sum Expression
Initially 5 - 0 - -
Iteration1 5 1 1 1 <= 5 TRUE
Iteration2 5 2 3 2 <= 5 TRUE
Iteration3 5 3 6 3 <= 5 TRUE
Iteration4 5 4 10 4 <= 5 TRUE
Iteration5 5 5 15 5 <= 5 TRUE
Iteration6 5 6 15 6<= 5 FALSE
Example Program:
The following program uses a nested for loop to find the prime numbers from 2 to 10:
/* program to demonstrate the working of nested for loop*/
#include <stdio.h>
void main ()
{
int i, j; /* local variable definition */
for(i=2; i<10; i++)
{
for(j=2; j <= (i/j); j++)
{
if(!(i%j))
break; // if factor found, not prime
}
if(j > (i/j))
printf("%d is prime\n", i);
}
}
Output:
2 is prime
3 is prime
5 is prime
7 is prime
2.10.7 The while loop
Syntax:
…
…
Initialization;
…
…
while(condition)
{
Block of statement;
Increment/decrement;
}
The difference between the for loop and the while loop is that the initialization, condition,
increment/decrement are in a single line in the for loop and it is kept separately in the while loop.
Example
a=10;
while(a>=20)
{
printf(“hai”);
a++;
}
Program
Write a C program to find the factorial of a number, where the number is entered by user. (Hints:
factorial of n = 1*2*3*...*n
/* program to demonstrate the working of while loop*/
#include <stdio.h>
void main()
{
int number,factorial;
printf("Enter a number.\n");
scanf("%d",&number);
factorial=1;
while (number>0)
{
factorial=factorial*number;
--number;
}
printf("Factorial=%d",factorial);
}
Output:
Enter a number.
5
Factorial=120
2.10.8 The do-while loop
In C, do...while loop is very similar to while
loop. Only difference between these two
loops is that, in while loops, test expression is
checked at first but, in do...while loop code is
executed at first then the condition is
checked. So, the code are executed at least
once in do...while loops.
Syntax
…
…
Initialization;
…
…
do
{
Block of statement;
Increment/decrement;
}while(condition);
Example Program
Write a C program to add all the numbers entered by a user until user enters 0.
/*C program to demonstrate the working of do...while statement*/
#include <stdio.h>
void main()
{
int sum=0,num;
do
{
printf("Enter a number\n");
scanf("%d",&num);
sum+=num;
}
while(num!=0); // do..while loop must end with semicolon
printf("sum=%d",sum);
}
Output
Enter a number
3
Enter a number
-2
Enter a number
0
sum=1
Note: do..while loop must end with semicolon (;)
The figure below explains the working of break statement in all three type of loops.
Explanation
In this program, when the user inputs number less than zero, the loop is terminated using break statement with
executing the statement below it i.e., without executing sum=sum+num.
In C, break statements are also used in switch...case statement.
Note : if statement is not an loop, it’s an conditional statement. So we can’t use break for if statement.
2.10.11 The continue Statement
It is sometimes desirable to skip some statements inside the loop. In such cases, continue statements are used.
Syntax
continue;
Just like break, continue is also used with conditional if statement.
For better understanding of how continue statements works in C programming. Analyze the figure below which
bypasses some code/s inside loops using continue statement.
Output:
Enter num1:5
Enter num2:0
Enter num3:4
Enter num4:0
Enter num5:3
Enter num6:0
Enter num7:2
Enter num8:0
Enter num9:1
Enter num10:0
product=120
break Vs continue
The break statement in C completely terminates the execution of the current loop, and processes the
statement which is placed immediately after the loop.
The continue statement just skips the current iteration of the loop and processes the next iteration in the loop.
break continue
When a compiler encounters a break ,the control is When a compiler encounters a continue,the control is
moved to the end of the loop. moved to the beginning of the loop.
It terminates the execution of the loop It terminates the current iteration of the loop
It moves to the statement immediatley after the loop It continues to the next iteration
It skips an entire loop It skips only a particular iteration
Keyword is break Keyword is continue