Unit 1
Unit 1
CS8251 - PROGRAMMING IN C
Unit 1
3 © 2021 UCEN
Problem Solving
(P) (S)
F:P S
Problem Solving Using Computers
5 © 2021 UCEN
Program
Input Output
F:I O
Programming Language
7 © 2021 UCEN
Introduction of Programming Paradigms
Paradigm can also be termed as method to solve
some problem or do some task
Programming paradigm is an approach to solve
problem using some programming language or also
we can say it is a method to solve a problem using
tools and techniques that are available to us following
some approach
There are lots for programming language that are
known but all of them need to follow some strategy
when they are implemented and this
methodology/strategy is paradigms.
8 © 2021 UCEN
9 © 2021 UCEN
Imperative programming paradigm
10 © 2021 UCEN
Procedural programming paradigm
11 © 2021 UCEN
Object oriented programming
12 © 2021 UCEN
Parallel processing approach
13 © 2021 UCEN
Declarative programming paradigm
14 © 2021 UCEN
Logic programming paradigms
It can be termed as abstract model of
computation.
It would solve logical problems like puzzles,
series etc
In logic programming we have a knowledge
base which we know before and along with
the question and knowledge base which is
given to machine, it produces result.
In normal programming languages, such
concept of knowledge base is not available
Example
Prolog
15 © 2021 UCEN
Functional programming paradigms
The functional programming paradigms has
its roots in mathematics and it is language
independent
The central model for the abstraction is the
function which are meant for some specific
computation and not the data structure.
Data are loosely coupled to functions.
Function can be replaced with their values
without changing the meaning of the program
Example:
perl
javascript
16 © 2021 UCEN
Database/Data driven programming
approach
This programming methodology is based
on data and its movement
Program statements are defined by data
rather than hard-coding a series of steps.
A database program is the heart of a
business information system and provides
file creation, data entry, update, query and
reporting functions
Examples:
SQL
17 © 2021 UCEN
Generation of programming
Languages
First – FORTRAN I, ALGOL 58
Second - FORTRAN II, Algol60, COBOL
Third – Pascal, C
Structured programming Approach
Fourth – C++, Java, C#
Object oriented programming
18 © 2021 UCEN
Types of Programming Languages
Based on closeness to computer
High Level - Closer to Human only
Assembly level - Closer to Human and Machine
Machine Level - Closer to Machine only
Based on the ways and means of dealing the logic
Imperative or Procedural or Structured - Collection of statements and
functions to manipulate data
Logical -Collection of logical reasoning with rules and inferences
Functional - Collection of mathematical functions
Object oriented - Collection of interacting objects
Based on Generation
First Generation -Machine Language
Second Generation -Assembly Language
Third Generation - Structured and Object oriented Language
Fourth Generation -Domain Specific and Data Management
Languages
Fifth Generation -Language for Artificial Intelligence
19 © 2021 UCEN
Structured programming Approach
20 © 2021 UCEN
Structured programming -contd
21 © 2021 UCEN
Evolution of new paradigm
22 © 2021 UCEN
Object model
Resulted in OOP
Function Verbs
Data Items Nouns
Structured programming is organized around
verbs
OOP is organized around nouns
OOP reflects the natural way of solving problems
23 © 2021 UCEN
Structured Programming Languages
C
Pascal
24 © 2021 UCEN
Basic Terminologies
25 © 2021 UCEN
Continue..
26 © 2021 UCEN
1. Machine Level Language - Binary numbers that
corresponded directly to specific machine
instructions and locations in the computer’s memory.
2. Low-Level Language (Assembly language) -
permits the programmer to use symbolic names to
perform various operations and to refer to specific
memory locations.
Assembler - A special program that translates the
assembly language program from its symbolic format
into the specific machine instructions of the
computer system
27 © 2021 UCEN
Disadvantage of Assembly language
Machine dependent -Different processor types have
different instruction sets. Assembly language
program will not run on a different processor type
without being rewritten.
Not Portable - Programmer learn the instruction set
of the particular computer system to write a program
in assembly language.
28 © 2021 UCEN
3. Higher-level languages (HLL)-came to overcome
the machine dependent issue of low-level language.
FORTRAN (FORmula TRANslation) was the first
higher-level language.
Merits: Machine independent - A program could be
written in any language is to be run on any machine
that supported the language with few or no changes.
29 © 2021 UCEN
Compiler
30 © 2021 UCEN
Operating system - A program that controls the entire
operation of a computer system.
All I/O operations that are performed on a computer
system are channelled through the operating
system.
Also manage the computer system’s resources.
Handle the execution of programs.
Most popular operating systems today is the Unix,
Microsoft Windows XP.
31 © 2021 UCEN
Compilation Process
1. Write Source Program using Text Editor
The program that is to be compiled is first typed
into a file on the computer system.
A text editor is usually used to enter the C program
into a file.
C programs can typically be given any name
provided the last two characters are “.c”.
For example, vi is a popular text editor used on Unix
systems. The program that is entered into the file is
known as the source program because it
represents the original form of the program
expressed in the C language.
32 © 2021 UCEN
2. Debugging Phase: Compiler checks each program
statement in source program to conforms the syntax
and semantics of the language.
*unbalanced parentheses (syntactic error)
* variable that is not “declared” (semantic error)
If any mistakes are discovered then it reported to the
user and the compilation process ends right there.
So errors have to be corrected in the source
program (with the use of an editor), and the
compilation process must be restarted.
33 © 2021 UCEN
Creation of Object code file
Once all syntactic and semantic errors have been
removed from the program, the compiler then
proceeds to take each statement of the program and
translate it into a “lower” form. (translated into the
equivalent statements in assembly language)
Next the assembler takes each assembly language
statement and converts it into a binary format known
as object code, which is then written into another
file on the system.
This file typically has the same name as the source
file with the last letter an “o” (in unix) or “obj” (in
windows) instead of a “c”.
34 © 2021 UCEN
3. Linking Process (Creation of executable object code)
Now object code is ready to be linked. If the program
uses other programs that were previously processed by
the compiler, then those programs are linked together.
Programs that are used from the system’s program
library are also searched and linked together with the
object program during this phase.
The process of compiling and linking a program is often
called building.
The final linked file is an executable object code which
is ready to be run or executed. It is stored in another file
on the system, (In Unix, this file is called “a.out”, In
Windows, same name as the source file, with “exe”
extension).
35 © 2021 UCEN
4. Loading & Execution
To run the program, an executable object code file must
be loaded into the computer’s memory and initiating its
execution.
When the program is executed, each of the statements of
the program is sequentially executed in turn.
If the program requests any data from the user, known as
input, the program temporarily suspends its execution so
that the input can be entered. Or, the program might
simply wait for an event, such as a mouse being clicked,
to occur.
Results that are displayed by the program, known as
output, appear in a window called the console. Or, the
output might be directly written to a file on the system.
36 © 2021 UCEN
If all goes well, the program performs its intended
functions.
If the program does not produce the desired results,
it is necessary to go back and reanalyze the
program’s logic. This is known as the debugging
phase, during which an attempt is made to remove
all the known bugs from the program.
To do this, make changes to the original source
program. So the entire process of compiling, linking,
and executing the program must be repeated until
the desired results are obtained.
37 © 2021 UCEN
38 © 2021 UCEN
Compiler Vs Language Interpreters
Another method used for analyzing and executing programs
developed in a higher-level language.
Source Programs are not compiled but are interpreted.
An interpreter analyzes and executes the statements of a
program at the same time. This method usually allows
programs to be more easily debugged.
It is slower than compilation because statements are not
converted into their lowest-level form in advance of their
execution.
Example
BASIC and Java are two programming languages in which
programs are often interpreted and not compiled.
Other examples include the Unix system’s shell and Python.
Some vendors also offer interpreters for the C programming
language.
39 © 2021 UCEN
Integrated Development Environment
The process of editing, compiling, running, and
debugging programs is managed by a single integrated
application known as an IDE.
An IDE is a windows-based program that allows you to
easily manage large software programs, edit files in
windows, and compile, link, run, and debug your
programs.
Most IDEs also support program development in several
different programming languages in addition to C, such
as C# and C++.
Example
In Mac OS X, CodeWarrior and Xcode are two IDEs
used.
In Windows, Microsoft Visual Studio is a popular IDE.
Kylix is a popular IDE for developing applications under
Linux.
40 © 2021 UCEN
Programming paradigms
Way to classify programming languages based on
their features.
Languages can be classified into multiple paradigms.
Some paradigms are concerned mainly with
implications for the execution model of the
language,
Other paradigms are concerned mainly with the way
that code is organized.
Yet others are concerned mainly with the style of
syntax and grammar.
41 © 2021 UCEN
Execution model & Side effects
Execution model specifies how work takes
place.
Every programming language has an execution model cover
What is an indivisible unit of work? & What are the
constraints on the order in which those units of work take
place?
This order may be chosen ahead of time, or it can be
dynamically determined as the execution proceeds.
The implementation of an execution model can be
via compiler/ interpreter, and includes a runtime system.
Side effects -way that a program interacts with the
outside world (people, file systems, other computers on
networks). But the degree to which side effects are used
depends on the programming paradigm.
42 © 2021 UCEN
Example:
C programming language has a concept called a
statement.
Statements are indivisible units of work and that they
proceed in the same order as their syntactic
appearance in the code (except when a control
statement such as IF or WHILE modifies the order).
The C language actually has an additional level to its
execution model, which is the order of precedence. It
states the rules for the order of operations within a
single statement.
43 © 2021 UCEN
Common programming paradigms
45 © 2021 UCEN
Languages support single/multiple
paradigms
47 © 2021 UCEN
C programming
48 © 2021 UCEN
Evolution of C - ALGOL, CPL and BCPL
• ALGOL 60 - Algorithmic language Developed by an International
Committee, 1960
CPL – Cambridge Programming Language or Combined
Programming Language or Cambridge Plus London (1963)
Invented by D.W. Barron and Christopher Strachey, et al.
Jointly from University of Cambridge and University of London
Heavily influenced by Algol 60
49 © 2021 UCEN
B Programming Language
50 © 2021 UCEN
Evolution of C
51 © 2021 UCEN
Taxonomy of C Language
ALGOL
BCPL
Traditional C
K&RC
ANSI C
ANSI / ISO C
C 95
C99
52 © 2021 UCEN
Standards of C
53 © 2021 UCEN
Characteristics of C
It is a robust language with a rich set of built-in
functions and operators that can be used to write any
complex program.
It is a high level programming language
Small Size- only 32 keywords
Function Call
Well suited structured programming
Stable language
Quick
Facilitate low level programming (Bitwise operator)
Supports pointer
Core language (Any other language is easy)
Portable
54 Extensible © 2021 UCEN
Structure of C program
Preprocessor Directives
Global Declaration
main()
{
Local Declarations
Statements
}
Function 1()
{
Local Declarations
Statements
}
………………………………………….
Function N()
{
Local Declarations
Statements
}
55 © 2021 UCEN
Writing First C Program
56 © 2021 UCEN
C program
57 © 2021 UCEN
Escape Sequence
Escape Sequence Meaning
\a Alarm or Beep
\b Backspace
\f Form Feed
\n New Line
\r Carriage Return
\t Tab (Horizontal)
\v Vertical Tab
\\ Backslash
\' Single Quote
\" Double Quote
\? Question Mark
\nnn octal number
\xhh hexadecimal number
59 © 2021 UCEN
Tokens
A token may be a single character or a group of
characters which has a specific meaning.
The following are the tokens that can be identified by a
C compiler during the translation process.
Tokens in C
Keywords
Variables
Constants
Strings
Special Characters
Operators
60 © 2021 UCEN
Character set
Alphabets
Upper Case(A-Z)
Lower Case (a-z)
Digits (0-9)
Special characters
~%|@+<_->#=&$/()*\':[]";!,{}?.
Escape Sequence
whitespace characters
\b blank space
\t horizontal tab
\v vertical tab
\r carriage return
\f form feed
61 \n new line © 2021 UCEN
Keywords
62 © 2021 UCEN
identifiers
63 © 2021 UCEN
Example
valid identifiers
total, sum, average, _m _, sum_1, etc.
Invalid identifiers
2sum (starts with a numerical digit)
int (reserved word)
char (reserved word)
m+n (special character, i.e., '+')
64 © 2021 UCEN
DataTypes
Data types in c refer to an extensive system used
for declaring variables or functions of different
types.
The type of a variable determines how much
space it occupies in storage and how the bit
pattern stored is interpreted.
65 © 2021 UCEN
Types- Data Types
2 Enumerated types
They are again arithmetic types and they are used to define
variables that can only assign certain discrete integer values
throughout the program.
- Enum
4 Derived types
They include (a) Pointer types, (b) Array types, (c) Structure types,
(d) Union types and (e) Function types.
66 © 2021 UCEN
Basic Data Types - Integer
Type Storage size Value range
char 1 byte -128 to 127 or 0 to 255
unsigned char 1 byte 0 to 255
signed char 1 byte -128 to 127
Int 2 bytes -32,768 to 32,767
unsigned int 2 bytes 0 to 65,535
signed int 2 bytes -32,768 to 32,767
short int 2 bytes -32,768 to 32,767
unsigned short int 2 bytes 0 to 65,535
68 © 2021 UCEN
The void Type
The void type specifies that no value is available.
It is used in three kinds of situations
Sr.No. Types & Description
1 Function returns as void
There are various functions in C which do not return any value
or you can say they return void. A function with no return value
has the return type as void. For example, void exit (int
status);
2 Function arguments as void
There are various functions in C which do not accept any
parameter. A function with no parameter can accept a void. For
example, int rand(void);
3 Pointers to void
A pointer of type void * represents the address of an object,
but not its type. For example, a memory allocation
function void *malloc( size_t size ); returns a pointer to void
which can be casted to any data type.
69 © 2021 UCEN
Variables
A variable is nothing but a name given to a storage area
that our programs can manipulate
Each variable in C has a specific type, which determines
the size and layout of the variable's memory; the range of
values that can be stored within that memory; and the set
of operations that can be applied to the variable.
Two basic kinds of variables
Numeric variables
Store integer or float values
Character variables
Single character enclosed with ‘’
70 © 2021 UCEN
Variable Declaration
71 © 2021 UCEN
Initializing variable
72 © 2021 UCEN
Constants / Literals
73 © 2021 UCEN
Integer Constants
An integer literal can be a decimal, octal, or hexadecimal
constant.
A prefix specifies the base or radix: 0x or 0X for hexadecimal,
0 for octal, and nothing for decimal.
An integer literal can also have a suffix that is a combination
of U and L, for unsigned and long, respectively.
The suffix can be uppercase or lowercase and can be in any
order.
Example
85 /* decimal */
0213 /* octal */
0x4b /* hexadecimal */
30 /* int */
30u /* unsigned int */
30l /* long */
30ul /* unsigned long */
74 © 2021 UCEN
Floating-point Literals / Constant
75 © 2021 UCEN
Character Constants
76 © 2021 UCEN
String Literals / Constants
String literals or constants are enclosed in double
quotes "".
A string contains characters that are similar to
character literals: plain characters, escape
sequences, and universal characters.
You can break a long line into multiple lines using
string literals and separating them using white
spaces.
Here are some examples of string literals. All the
three forms are identical strings.
"hello, dear" "hello, \ dear"
77 © 2021 UCEN
Declaring constants
There are two simple ways in C to define
constants −
Using #define preprocessor.
Using const keyword.
The #define Preprocessor
Syntax: #define identifier value
It is also called symbolic constant
78 © 2021 UCEN
Example
#include <stdio.h>
#define LENGTH 10
#define WIDTH 5
#define NEWLINE '\n'
int main()
{
int area;
area = LENGTH * WIDTH;
printf("value of area : %d", area);
printf("%c", NEWLINE);
return 0;
}
79 © 2021 UCEN
The const Keyword - Example
#include <stdio.h>
int main()
{
const int LENGTH = 10;
const int WIDTH = 5;
int area; area = LENGTH * WIDTH;
printf("value of area : %d", area);
return 0;
}
80 © 2021 UCEN
Input & Output Statments
81 © 2021 UCEN
Input / Output statements
Streams
A Stream act in to ways. It is the source of data as well
as destination of data.
C uses two forms of streams
Text Streams
Binary Streams
Input Text
Keyboard Data
Stream
Output Text
Monitor Data
Stream
82 © 2021 UCEN
Formatting Input / Output
The most fundamental operation in a C program is to accept input values
from a standard input device(keyboard) and output the data produced by
the program to a standard output device(Monitor).
we can assign values to variables using the assignment operator ‘=’.
Example: int a = 3;
What if we want to assign value to variable a that is inputted from the user
at run-time?
This is done by using the scanf function that reads data from the
keyboard.
for outputting results of the program, printf function is used that sends
results to a terminal.
Like printf and scanf, there are different functions in C that can carry out
the input–output operations.
These functions are collectively known as Standard Input/Output Library.
A program that uses standard input/output functions must contain the
following statement at the beginning of the program:
#include <stdio.h>
83 © 2021 UCEN
printf ()
The printf function is used to display information required by the user
and also prints the values of the variables
Printf- print Formatting
It takes data values and convert into the text stream is described using
a separate conversion specification in Control string
Syntax
printf ("control string", variable list);
Control string may contain text to be printed like instructions to the user,
captions, identifiers or any other text to make the output readable
Control characters also included in control string, like \n,\t,\a etc.,
Prototype of control string can be given below
%[flags][width][.precision][length modifier] type specifier
Each control string must begin with a % sign
flags is an optional argument, which specifies output justification like
decimal point, numerical
sign, trailing zeros or octadecimal or hexadecimal prefixes.
84 © 2021 UCEN
printf () - Continues
Flag
Flags Description
– Left–justify within the given field width
+ Displays the data with its numeric sign (either + or –)
Used to provide additional specifiers like o, x, X, 0, 0x, or 0X for
#
octal and hexadecimal values respectively for values different than zero
0 The number is left–padded with zeroes (0) instead of spaces
Note : When data is shorter than specified width, by default data is right justified
To left justify data use minus symbol in the flag field
Padding is used to fill unused space
Defualt padding symbol is space
width is an optional argument which specifies the minimum number of
positions that the output characters will occupy.
If the number of output characters is smaller than the specified width, then the
output would be right justified with blank spaces to the left.
However, if the number of characters is greater than the specified width, then
all the characters would be printed.
85 © 2021 UCEN
printf () - Continues
Flag
Flags Description
– Left–justify within the given field width
+ Displays the data with its numeric sign (either + or –)
Used to provide additional specifiers like o, x, X, 0, 0x, or 0X for
#
octal and hexadecimal values respectively for values different than zero
0 The number is left–padded with zeroes (0) instead of spaces
Note : When data is shorter than specified width, by default data is right justified
To left justify data use minus symbol in the flag field
Padding is used to fill unused space
Defualt padding symbol is space
width is an optional argument which specifies the minimum number of
positions that the output characters will occupy.
If the number of output characters is smaller than the specified width, then the
output would be right justified with blank spaces to the left.
However, if the number of characters is greater than the specified width, then
all the characters would be printed.
86 © 2021 UCEN
printf () - Continues
Precision is an optional argument which specifies the maximum number of
characters to print.
For integer specifiers (d, i, o, u, x, X) : precision flag specifies the minimum
number of digits to be written.
However, if the value to be written is shorter than this number, the result is
padded with leading zeros.
Otherwise, if the value is longer, it is not truncated.
For character strings, precision specifies the maximum number of characters to
be printed.
For floating point numbers, the precision flag specifies the number of decimal
places to be printed.
Its format can be given as .m, where m specifies the number of decimal digits.
When no precision modifier is specified, printf prints six decimal positions.
When both width and precision fields are used, width must be large enough to
contain the integral value of the number, the decimal point and the number of
digits after the decimal point.
Therefore, a conversion specification %7.3f means print a floating point value of
maximum 7 digits where 3 digits are allotted for the digits after the decimal point
87 © 2021 UCEN
printf () - Continues
Length Modifiers
Length Description
h When the argument is a short int or unsigned
short int
l When the argument is a long int or unsigned
long int for integer specifiers
L When the argument is a long double (used for
floating point specifiers)
88 © 2021 UCEN
printf () - Continues
Type Specifiers
used to define the type and the interpretation of the value of the corresponding argument
90 © 2021 UCEN
char str[] = "Good Morning";
printf ("\n %s", str);
printf("\n %20s", str);
printf ("\n %20.10s", str);
printf("\n %.7s", str) ;
printf ("\n %-20.10s", str);
printf("\n %7s", str);
Good Morning
Good Morning
Good Morni
Good Mo
Good Morni
Good Morning
91 © 2021 UCEN
scanf()
The scanf()function is used to read formatted data from the keyboard.
scanf- scan formatting
The syntax of the scanf() function can be given as
scanf ("control string", arg1, arg2, arg3...argn);
The control string specifies the type and format of the data that has to be obtained from the
keyboard and stored in the memory locations pointed by the arguments, arg1, arg2,
...,argn.
The prototype of the control string can be given as,
%[*][width][modifier]type
* is an optional argument that suppresses assignment of the input field. That is, it indicates
that data should be read from the stream but ignored (not stored in the memory location).
width is an optional argument that specifies the maximum number of characters to be
read. However, if the scanf function encounters a white space or an unconvertible
character, input is terminated.
modifier is an optional argument (h, l, or L) , which modifies the type specifier. Modifier h
is used for short int or unsigned short int, l is used for long int, unsigned long int, or double
values.
Finally, L is used for long double data values.
type specifies the type of data that has to be read. It also indicates how this data is
expected to be read from the user.
(refer printf table)
92 © 2021 UCEN
scanf()
The scanf function ignores any blank spaces, tabs, and newlines entered
by the user.
The function simply returns the number of input fields successfully
scanned and stored
Now let us quickly summarize the rules to use a scan function in our C
programs
Rule 1: The scanf function works until
(a) the maximum number of characters has been processed,
(b) a white space character is encountered,
(c) an error is detected.
Rule 2: Every variable that has to be processed must have a conversion
specification associated with it.
Therefore, the following scanf statement will generate an error as num3
has no conversion specification associated with it
scanf(“%d %d”, &num1, &num2, &num3);
93 © 2021 UCEN
scanf()
Rule3: There must be a variable address for each conversion specification, Therefore, the
following scanf statement will generate an error as no variable address is given for the third
conversion specification
scanf (“%d %d %d", &num1, &num2);
Remember that the ampersand operator (& before each variable name specifies the
address of that variable name
Rule 4: An error would be generated if the format string is ended with a white space
character
Rule 5: The data entered by the user must match the character specified in the control
string (except white space or a conversion specification), otherwise an error will be
generated and scanf will stop its processing.
For example, consider the scanf statement given below.
scanf (“%d / %d", &num1, &num2);
Here, the slash in the control string is neither a white space character nor a part of conversion
specification, so the users must enter data of the form 21/46.
Rule 6: Input data values must be separated by spaces
Rule 7: Any unread data value will be considered as a part of the data input in the next call
to scanf.
Rule 8: When the field width specifier is used, it should be large enough to contain the
input data size
94 © 2021 UCEN
Scanf() examples
int num;
scanf(“%d”, &num);
float num;
scanf(“%f”, &num);
char ch;
scanf(“%c”, &ch);
char str[10];
scanf(“%s”, str);
95 © 2021 UCEN
Program
#include <stdio.h>
main()
{
int a, b;
printf("\n Enter two four digit numbers : ");
scanf("%2d %4d", &a, &b);
printf("\n The two numbers are : %d and %d", a, b);
return 0;
}
96 © 2021 UCEN
Output
97 © 2021 UCEN
Program
Write a program to demonstrate the use of printf statement to
print values of variables of different data types
#include <stdio.h>
Int main()
{
// Declare and initialize variables
int num = 7;
float amt = 123.45;
char code = 'A';
double pi = 3.1415926536;
long int population_of_india = 10000000000;
char msg[] = "Hi";
// Print the values of variables
printf("\n NUM = %d \t AMT = %f \t CODE = %c \n PI = %e \t
POPULATION OF INDIA = %ld \n MESSAGE = %s", num, amt, code,
pi, population_of_india, msg);
return 0;
}
98 © 2021 UCEN
Output
NUM = 7
AMT = 123.450000
CODE = A
PI = 3.141590e+00
POPULATION OF INDIA = 10000000000
MESSAGE = HI
99 © 2021 UCEN
Write a program to demonstrate the use of printf and scanf
statements to read and print values of variables of
different data types
#include <stdio.h>
Int main()
{
int num;
float amt;
char code;
double pi;
long int population_of_india;
char msg[10];
printf("\n Enter the value of num : ");
scanf("%d", &num);
printf("\n Enter the value of amt : ");
scanf("%f", &amt);
printf("\n Enter the value of pi : ");
scanf("%e", &pi);
printf("\n Enter the population of india : ");
scanf("%ld", &population_of_india);
printf("\n Enter the value of code : ");
scanf("%c", &code);
printf("\n Enter the message : ");
scanf("%s", msg);
printf("\n NUM = %d \n AMT = %f \n PI = %e \n POPULATION OF INDIA = %ld \n CODE = %c \n MESSAGE = %s", num, amt, code,
pi, population_of_india, msg);
return 0;
}
#include <stdio.h>
#include <conio.h>
int main()
{
int num1, num2;
int add_res=0, sub_res=0, mul_res=0, idiv_res=0, modiv_res=0; float fdiv_res=0.0;
clrscr();
printf("\n Enter the first number : ");
scanf("%d", &num1);
printf("\n Enter the second number : ");
scanf("%d", &num2);
add_res= num1 + num2;
sub_res= num1 - num2;
mul_res = num1 * num2;
idiv_res = num1/num2;
modiv_res = num1%num2;
fdiv_res = (float)num1/num2;
printf("\n %d + %d = %d", num1, num2, add_res);
printf("\n %d - %d = %d", num1, num2, sub_res);
printf("\n %d ¥ %d = %d", num1, num2, mul_res);
printf("\n %d / %d = %d (Integer Division)", num1, num2, idiv_res);
printf("\n %d %% %d = %d (Moduluo Division)", num1, num2, modiv_res);
printf("\n %d / %d = %.2f (Normal Division)", num1, num2, fdiv_res);
return 0;
}
10 < 20 = 1
10 == 20 = 0
10 != 20 = 1
10 > 20 = 0
10 >= 20 = 0
10 <=20 = 1
A B A|| B
0 0 0
0 1 1
1 0 1
1 1 1
A !A && B
0 1
1 0
m = 5;
y = m++; (post fix) //y=m+1;
value of y will be 5 and that of m will be 6.
O/P:
The value of num = 3
The value of num++ = 3
The new value of num = 4
#include <stdio.h>
#include <conio.h>
int main()
{
int num1, num2, num3, large;
clrscr();
printf("\n Enter the first number: ");
scanf("%d", &num1);
printf("\n Enter the second number: ");
scanf("%d", &num2);
printf("\n Enter the third number: ");
scanf("%d", &num3);
large = num1>num2?(num1>num3?num1:num3):(num2>num3?num2:num3);
printf("\n The largest number is: %d", large);
return 0;
}
O/P:
Enter the first number: 12
Enter the second number: 34
Enter the third number: 23
The largest number is: 34
Operator Meaning
0 0 0 0 0 1 1
0 1 0 1 1 0
1 0 0 1 1 0 1
1 1 1 1 1 0
#include <stdio.h>
main()
{
int num1 = 3, num2 = 5;
printf("\n Initial value of num1 = %d and num2 = %d", num1,
num2);
num1 += num2 * 4 - 7;
printf("\n After the evaluation of the expression num1 = %d and
num2 = %d", num1, num2);
return 0;
}
O/P:
Initial value of num1 =3 and num2 = 5
After the evaluation of the expression num1 = 16 and num2 = 5
#include <stdio.h>
int main()
{
int a = 16;
printf("Size of variable a : %d\n",sizeof(a));
printf("Size of int data type : %d\n",sizeof(int));
printf("Size of char data type : %d\n",sizeof(char));
printf("Size of float data type : %d\n",sizeof(float));
printf("Size of double data type : %d\n",sizeof(double));
return 0;
}
Output
Size of variable a : 4
Size of int data type : 4
Size of char data type : 1
Size of float data type : 4
Size of double data type : 8
#include <stdio.h>
#include <conio.h>
int main()
{
float f_num;
int i_num;
clrscr();
printf("\n Enter any floating point number: ");
scanf("%f", &f_num);
i_num = (int)f_num;
printf("\n The integer variant of %f is = %d", f_num, i_num);
return 0;
}
#include <stdio.h>
#include <conio.h>
int main()
{
float f_num;
int i_num;
clrscr();
printf("\n Enter any integer: ");
scanf("%d", &i_num);
f_num = (float)i_num;
printf("\n The floating point variant of %d is = %f", i_num,
f_num);
return 0;
}
If For Break
switch
}
statement-x; True
test expression ?
statement–block
False
Statement-x
Statement-x
#include <stdio.h> ch = ‘ ‘
main( )
{
char ch;
Input ch
ch = getchar( );
fflush(stdin);
if (ch = = ‘*’) true
puts (“You have entered the star is ch = ‘*’ Print *
character”);
else false
puts (“You have not entered the star
character”);
Not a *
}
stop
#include <stdio.h>
#include <conio.h>
main()
{
int num;
clrscr();
printf("\n Enter any number: ");
scanf("%d",&num);
if(num%2 == 0)
printf("\n %d is an even number", num);
else
printf("\n %d is an odd number", num);
return 0;
}
#include <stdio.h>
#include <conio.h>
main()
{
char ch;
clrscr();
printf("\n Enter any character: ");
scanf("%c", &ch);
if(ch ='a' ||ch =='e' ||ch=='i' ||ch=='o' ||ch=='u' || ch=='A' ||ch=='E' ||ch=='I' ||ch=='O'
||ch=='U' )
printf("\n %c is a VOWEL", ch);
else
printf("\n %c is not a vowel");
getch();
return 0;
}
154 © 2021 UCEN
Example
/* Write a program to fi nd whether a given year is a leap year or not.*/
#include <stdio.h>
#include <conio.h>
int main()
{
int year;
clrscr();
printf("\n Enter any year: ");
scanf("%d",&year);
if((year%4 == 0) && ((year%100 !=0) || (year%400 == 0)))
printf("\n Leap Year");
else
printf("\n Not A Leap Year");
return 0;
}
#include <stdio.h>
{
int x, y;
printf("\n Enter two numbers: ");
scanf("%d %d", &x, &y);
if(x == y)
printf("\n The two numbers are equal");
else if(x > y)
printf("\n %d is greater than %d", x, y);
else
printf("\n %d is less than %d", x, y);
return 0;
}
158 © 2021 UCEN
/*Write a program to test whether a number entered is positive, negative or
equal to zero.*/
#include <stdio.h>
main()
{
int num;
printf("\n Enter any number: ");
scanf("%d", &num);
if(num==0)
printf("\n The value is equal to zero");
else if(num>0)
printf("\n The number is positive");
else
printf("\n The number is negative");
return 0;
}
The break statement at the end of each block signals the end
of particular case and causes an exit from the switch
statement, transferring the control to the statement-x.
General form
while(test-condition)
{
body of the loop
}
#include <stdio.h>
int main()
{
int i = 0, sum = 0;
while(i<=10)
{
sum = sum + i;
i = i + 1; // condition updated
}
printf("\n SUM = %d", sum);
return 0;
}
#include <stdio.h>
int main()
{
int n, i = 0, sum =0;
float avg = 0.0;
printf("\n Enter the value of n: ");
scanf("%d", &n);
do
{
sum = sum + i;
i = i + 1;
}
while(i<=n);
avg = sum/n;
printf("\n The sum of first n numbers = %d", sum);
printf("\n The average of first %d numbers = %f", n, avg);
return 0;
}
for(initialization;test-
condition;increment)
Inc / Decrement
{
}
body of the loop
Body of the loop
condition
Initialization of the True
control variable is false
done first, using
assignment
statements
179 © 2021 UCEN
Example – for loop
#include <stdio.h>
/* this function displays a message 10
times */
main( )
{
int i;
for( i = 0; i <= 9; i = i + 1)
{
puts( “message %d”,i);
}
}
The for statement allows for negative increments. More than one
variable can be initialized at a time.
for (p=1,n=0;n<17;++n)
The increment section can also have more than one part.
for (n=1,m=50;n<=m;m++,n--)
When the loops are nested,the break would only exit from the
loop containing it.
#include <stdio.h>
int main()
{
int num,i=1;
printf("Enter the number whose table you want to print?“
scanf("%d",&num);
table:
printf("%d x %d = %d\n",num,i,num*i);
i++;
if(i<=10)
goto table;
}
Expression
Conditional
if (expr) { … } else {…}
switch (expr) { case c1: case c2: … }
Iteration
while (expr) { … } zero or more iterations
do … while (expr) at least one iteration
for ( init ; valid ; next ) { … }
Jump
goto label
continue; go to start of loop
break; exit loop or switch
return expr; return from function
Output:
20 10
O/P: 0
Unconditional Conditional
Define If
Line Else
undef Elif
Include Ifdef
Error Ifndef
pragma endif
int main()
{
float radius, area;
printf("Enter the radius: ");
scanf("%f", &radius);
printf("Area=%.2f",area);
return 0;
}
#define Preprocessor Directive:
A macro definition also include an expression
EX1
#define ROWS 3
#define COLUMNS 3
#define SIZE (ROWS * COLUMNS)
EX2
#include<stdio.h>
#include<conio.h>
#define INPUT printf(“\n Enter a number”); scanf(“%d”,&num);
define EQUALS ==
#define PRINT1 printf(“Great”);
#define PRINT2 printf(“Try Again”);
#define START main()
#define END getch(); \
return 0; }
START
int num;
INPUT
if(num EQUALS )
PRINT1;
else
PRINT2;
END
#define Preprocessor Directive:
Function Like Macros
More complex than object like macros
They stimulates functions
It includes list of parameters
Syntax:
#define identifier(arg1,arg2,….argn)
String
Consider the following macro definition with one argument
for the area of a circle:
#define CIRCLE_AREA( x ) ( ( PI ) * ( x ) * ( x ) )
Wherever CIRCLE_AREA(y) appears in the file, the value of
y is substituted for x in the replacement-text, the symbolic
constant PI is replaced by its value (defined previously) and
the macro is expanded in the program.
#define Preprocessor Directive:
For example, the statement
area = CIRCLE_AREA( 4 );
is expanded to
area = ( ( 3.14159 ) * ( 4 ) * ( 4 ) );
int main() {
float radius, area;
return 0;
}
#define Preprocessor Directive:
Macro CIRCLE_AREA could be defined as a function.
Function circleArea
double circleArea( double x )
{
return 3.14159 * x * x;
}
performs the same calculation as macro CIRCLE_AREA, but
the overhead of a function call is associated with function
circleArea.
#define Preprocessor Directive:
The advantages of macro CIRCLE_AREA are that macros
insert code directly in the program—avoiding function call
overhead—and the program remains readable because the
CIRCLE_AREA calculation is defined separately and named
meaningfully.
A disadvantage is that its argument is evaluated twice.
#define Preprocessor Directive:
The following is a macro definition with two arguments for
the area of a rectangle:
#define RECTANGLE_AREA( x, y ) ( ( x ) * ( y ) )
Wherever RECTANGLE_AREA(x, y) appears in the
program, the values of x and y are substituted in the macro
replacement text and the macro is expanded in place of the
macro name.
For example, the statement
rectArea = RECTANGLE_AREA( a + 4, b + 7 );
is expanded to
rectArea = ( ( a + 4 ) * ( b + 7 ) );
#define Preprocessor Directive:
The value of the expression is evaluated and assigned to
variable rectArea.
The replacement text for a macro or symbolic constant is
normally any text on the line after the identifier in the
#define directive.
If the replacement text for a macro or symbolic constant is
longer than the remainder of the line, a backslash (\) must be
placed at the end of the line, indicating that the replacement
text continues on the next line.
#define Preprocessor Directive: Nesting
of Macros
#define SQUARE(X) ((X)*(X))
#define CUBE(X) (SQUARE(X)*(X))
#define FOURTH_POWER(X) (CUBE(X)*(X))
Nested Upto 31 levels
Rules
Macro Name and formal arguments must follow identifier
rules
Space, tabs and comments are allowed within #define
directive
White space in between the identifier and the left
parentheses that introduces the parameter list is not
allowed
Number of arguments must match
#operator to convert to string literals
#include <stdio.h>
#define PRINT(num) printf(#num”=%d”, num)
main()
{
PRINT(20);
}
PRINT(20); is replaced as printf(num”=%d”, num)
Anoterh Example
#define MAC(x) #x
MAC(“10”) gives string literal “10”
MAC(“HI”) gives string literal “HI”
Rules of using #operator I function like macro
definition
A parameter following # operator in a function-like macro is converted into
a string literal containing the argument passed to the macro.
Leading and trailing white-space characters (those that appear before or
after) in the argument passed to the macro are deleted.
If the argument passed to the macro has multiple white space characters,
then they are replaced by a single space character.
If the argument passed to the macro contains a string literal and if a
\(backslash) character appears within the literal, then on expansion of the
macro, a second\ character is inserted before the original \.
If the argument passed to the macro contains a " (double quotation mark)
character, then on expansion of the macro, a character is inserted before
the ".
The conversion of an argument into a string literal occurs before macro
expansion on that argument.
If there is more than one # operator in the replacement list of a macro
definition, the order of evaluation of the operators is not defined.
If the result of the macro expansion is not a valid character string literal,
the behaviour is undefined.
# and ## Operators
The # and ## preprocessor operators are available in Standard
C.
The # operator causes a replacement text token to be converted
to a string surrounded by quotes.
Consider the following macro definition:
#define HELLO(x) printf( "Hello, " #x "\n" );
indicates that lines are numbered from 100 beginning with the
next source code line and that the name of the file for the
purpose of any compiler messages is "file1.c".
The directive normally is used to help make the messages
produced by syntax errors and compiler warnings more
meaningful.
The line numbers do not appear in the source file.
EXAMPLE
#include<stdio.h>
main()
{
#line 10 “Error.c”
Int a=10:
#line 20
printf(“%d”,a);
}
Pragma Directives
#pragma directive is used to control the actions of the
compiler in a particular portion of a program without affecting
the program as a whole.
You can include the pragma directive in your C program from
the point where you want them to take effect.
The effect of pragma will be applied from the point where it is
included to the end of the compilation unit or until another
pragma changes its status.
A #pragma directive is an instruction to the compiler and is
usually ignored during preprocessing.
The syntax of using a pragma directive can be given as
#pragma string
Here, string can be one of the instructions given to the
compiler with any required parameters.
Instruction Description