SlideShare ist ein Scribd-Unternehmen logo
1 von 207
Introduction to C Programming
By
Mr.S.Selvaraj
Asst. Professor (SRG) / CSE
Kongu Engineering College
Thanks to and Resource from : Sumitabha Das, “Computer Fundamentals and C Programming”, 1st Edition, McGraw Hill, 2018.
20CST11 – Problem Solving and Programming
2/8/2021 Introduction to C Programming 2
Syllabus
Contents
1. Life Cycle of a C Program
2. Features of C
3. Data Variables
– Declaring, Assigning and Printing Variables
4. Data Type Classification
– Integer, Float, Character and Constants
5. Operators and expressions
6. Control Structures
– Decision making and Looping statements
7. Input and output functions
2/8/2021 3
Introduction to C Programming
Why to Learn C Program
• C programming language is a MUST for students
and working professionals to become a great
Software Engineer specially when they are
working in Software Development Domain.
• Some of the key advantages of learning C
Programming:
– Easy to learn
– Structured language
– It produces efficient programs
– It can handle low-level activities
– It can be compiled on a variety of computer platforms
2/8/2021 Introduction to C Programming 4
History of Computer Languages
• Fortran formerly FORTRAN, derived from ”Formula Translation” is a general-
purpose, compiled imperative programming language that is especially suited to numeric
computation and scientific computing. Originally developed by IBM in 1957.
• ALGOL short for "Algorithmic Language“ is a family of imperative computer programming
languages originally developed in 1958.
• BASIC (Beginners' All-purpose Symbolic Instruction Code) is a family of general-
purpose, high-level programming languages whose design philosophy emphasizes ease of
use. The original version was designed by John G. Kemeny and Thomas E. Kurtz and
released at Dartmouth College in 1964.
• BCPL ("Basic Combined Programming Language") is a procedural, imperative,
and structured programming language. BCPL was first implemented by Martin
Richards of the University of Cambridge in 1967.
• B was derived from BCPL, and its name may be a contraction of BCPL. B is a programming
language developed at Bell Labs circa 1969. It is the work of Ken Thompson with Dennis
Ritchie.
• C is a successor to the programming language B. C is a general-purpose, high-level
language that was originally developed by Dennis Ritchie to develop the UNIX operating
system at AT & T Bell Labs (Now Lucent). C was originally first implemented on the DEC
PDP-11 computer in 1972.
• The language was formalized in 1988 by the American National Standard Institute
(ANSI).
2/8/2021 5
Introduction to C Programming
Computer Language Timeline
YEAR LANGUAGE Developed By
1957 FORTRAN John Backus
1958 ALGOL ---
1964 BASIC John G. Kemeny
Thomas E. Kurtz
1967 BCPL Martin Richards
1970 Pascal Niklaus Wirth
1968 B Ken Thompson
1972 C Dennis Ritchie
1985 C ++ Bjarne Stroustrup
1988 ANSI C ---
1991 Python Guido van Rossum
1995 Java James Gosling
2000 C # Microsoft
2/8/2021 Introduction to C Programming 6
Introduction to C
• C is a simple but powerful third-generation language.
• The UNIX OS and RDBMS MySQL was totally written in
C.
• C has replaced BASIC and Pascal for introducing
students to the programming world.
• It has also influenced the development of object-
oriented languages like C++, C# and Java.
• C can be considered to be both a high- and low-level
language. While it is sufficiently low-level to enable
access to specific memory locations, it is also a high-
level language with all the standard constructs and
operators found in any 3GL language
2/8/2021 7
Introduction to C Programming
Introduction to C
• Its rich library of functions enables the
development of modular applications.
• Its support of a variety of constructs for decision
making (if and switch) and repetition (while, for
and do-while) also makes it suitable for
structured programming.
• But the language derives its power from the vast
arsenal of operators that permit low-level
operations like
– (i) direct access to memory, and
– (ii) manipulation of every bit in memory
2/8/2021 Introduction to C Programming 8
Life Cycle of a C Program
2/8/2021 Introduction to C Programming 9
Preprocessor and Compiler
• a preprocessor is a program that processes its input data to
produce output that is used as input to another program.
• a compiler is a computer program that translates
computer code written in one programming
language (the source language) into another language
(the target language).
• OR
• The name "compiler" is primarily used for programs that
translate source code from a high-level programming
language to a lower level language (e.g., assembly
language, object code, or machine code) to create
an executable program.
2/8/2021 Introduction to C Programming 10
Assembler
• An assembler program creates object
code by translating combinations
of mnemonics and syntax for operations and
addressing modes into their numerical equivalents.
• OR
• An assembler is a program that converts assembly
language into machine code. It takes the basic
commands and operations from assembly code and
converts them into binary code that can be recognized
by a specific type of processor.
• Assemblers are similar to compilers in that they
produce executable code.
2/8/2021 Introduction to C Programming 11
Linker
• a linker or link editor is a computer system
program that takes one or more object files
(generated by a compiler or an assembler) and
combines them into a single executable file,
library file, or another "object" file.
2/8/2021 Introduction to C Programming 12
Loader
• In computer systems a loader is the part of an operating system that is
responsible for loading programs and libraries. It is one of the essential
stages in the process of starting a program, as it places programs
(executable code) into memory and prepares them for execution.
• Once loading is complete, the operating system starts the program by
passing control to the loaded program code.
• The following are the responsibilities of a loader:
– Validate the program for memory requirements, permissions, etc.
– Copy necessary files, such as the program image or required libraries,
from the disk into the memory
– Copy required command-line arguments into the stack
– Link the starting point of the program and link any other required
library
– Initialize the registers
– Jump to the program starting point in memory
2/8/2021 Introduction to C Programming 13
Interpreter
• In computer science, an interpreter is a computer
program that directly executes instructions written in
a programming or scripting language, without
requiring them previously to have been compiled into
a machine language program.
• Example : BASIC, Java, Python, Perl, MATLAB, Ruby, Lisp
• An interpreter generally uses one of the following
strategies for program execution:
– Parse the source code and perform its behavior directly;
– Translate source code into some efficient intermediate
representation and immediately execute this;
– Explicitly execute stored precompiled code made by
a compiler which is part of the interpreter system.
2/8/2021 Introduction to C Programming 14
Key Difference B/w Compiler and Interpreter
• Compiler transforms code written in a high-level programming
language into the machine code, at once, before program runs,
whereas an Interpreter coverts each high-level program statement,
one by one, into the machine code, during program run.
• Compiled code runs faster while interpreted code runs slower.
• Compiler displays all errors after compilation, on the other hand,
the Interpreter displays errors of each line one by one.
• Compiler is based on translation linking-loading model, whereas
Interpreter is based on Interpretation Method.
• Compiler takes an entire program whereas the Interpreter takes a
single line of code.
2/8/2021 Introduction to C Programming 15
Features of C Programming Language
• Procedural Language
• Fast and Efficient
• Modularity
• Statically Type
• General Purpose Language
• Rich set of built in Operators
• Libraries with rich Functions
• Middle Level Language
• Portability
• Easy to Extend
2/8/2021 Introduction to C Programming 16
Applications of C Programming
• C was initially used for system development work, particularly the
programs that make-up the operating system.
• C was adopted as a system development language because it
produces code that runs nearly as fast as the code written in
assembly language.
• Some examples of the use of C are -
– Operating Systems
– Language Compilers
– Assemblers
– Text Editors
– Print Spoolers
– Network Drivers
– Modern Programs
– Databases
– Language Interpreters
– Utilities
2/8/2021 Introduction to C Programming 17
Thank you
2/8/2021 Introduction to C Programming 18
Data Variables
By
Mr.S.Selvaraj
Asst. Professor (SRG) / CSE
Kongu Engineering College
Contents
1. Life Cycle of a C Program
2. Features of C
3. Data Variables
– Declaring, Assigning and Printing Variables
4. Data Type Classification
– Integer, Float, Character and Constants
5. Operators and expressions
6. Control Structures
– Decision making and Looping statements
7. Input and output functions
2/8/2021 20
Data Variables
Program Data
• A program must know the address in memory of
every piece of data that it handles.
• When a program encounters the variable x, it can
evaluate this variable only if it knows the
memory location of x.
• As a programmer, you need not know the
address of this location or the register where it is
moved to because the compiler provides this
information in the executable.
• Keep in mind that you are learning to use C and
not assembly language.
2/8/2021 Data Variables 21
Variables
• Program data occur in the form of variables and constants.
• A variable has a name that is assigned a value.
• This value is stored in memory and can change while the
program is running.
• For example, area, your_number and counter.
• The name used to access a variable is also known as an
identifier.
• Example:
– int counter;
– The compiler identifies the type as int, i.e. integer, and allocates
at least 2 bytes of memory for the variable named counter.
2/8/2021 22
Data Variables
Constants
• Constants represent data that don’t change.
• For example,
– In the expression (fahrenheit - 32) / 9.0, both 32
and 9.0 are constants.
– In printf(“Printing ASCII List”); The first argument
used with printf is often a string constant, say,
“Printing ASCII list”.
2/8/2021 Data Variables 23
Naming the variables
• The rules for framing variable names apply to all identifiers, which
include arrays and functions.
• A variable name can begin with a letter or the underscore (_)
character, but the remaining part of the name can comprise only
the following characters:
– Letters (both lower- and uppercase)
– Digits
– The underscore (_) character. Note that this is different from the
hyphen (-) which is available on the same key as the _ on your PC or
laptop.
• A variable name thus cannot begin with a digit.
• The names rate1 and _rate1 are valid but not 1rate.
• Variable names are also case-sensitive; rate1 and RATE1 are two
separate variables.
• Here are some examples of valid identifier names:
2/8/2021 Data Variables 24
Naming the variables
• Under C89 (the first C standard from ANSI), the first 31
characters of an identifier are significant. The
remaining characters are ignored by the compiler.
• Use meaningful lowercase names for variables.
Names like x and abc are valid, but they don’t
intuitively reveal what they represent—unlike variables
like sampling_speed and conversion_rate
• The following keywords used in C cannot be used as
variable names:
2/8/2021 Data Variables 25
Declaring Variables
• A variable must be declared before use.
• In most cases, the declaration is made at the beginning of
the program (mostly after main, but sometimes before
main for global variables).
• The following statement declares a variable named
bits_per_sec:
• the compiler allocates at least two bytes in memory for
bits_per_sec.
• It also notes the starting address of that memory location
so it knows where to look up when encountering
expressions that use the variable.
2/8/2021 Data Variables 26
Declaring Variables
• Using the comma as delimiter, multiple
declarations can be made in a single
statement provided the type is the same:
2/8/2021 Data Variables 27
Assigning Variables
• The previous declarations did not assign initial
values to the variables.
• To initialize a variable, use the = operator.
• One way is to separate the declaration from
the assignment:
2/8/2021 Data Variables 28
Assigning Variables
2/8/2021 Data Variables 29
2/8/2021 Data Variables 30
2/8/2021 Data Variables 31
Thank you
2/8/2021 Data Variables 32
Data Types Classification
By
Mr.S.Selvaraj
Asst. Professor (SRG) / CSE
Kongu Engineering College
Contents
1. Life Cycle of a C Program
2. Features of C
3. Data Variables
– Declaring, Assigning and Printing Variables
4. Data Type Classification
– Integer, Float, Character and Constants
5. Operators and expressions
6. Control Structures
– Decision making and Looping statements
7. Input and output functions
2/8/2021 34
Data Types Classification
Data Type Classification
• Data types are broadly categorized as follows:
– Fundamental (like int, float, etc.)
– Derived (like arrays and pointers)
– User-defined (structures, the typedef and enumerated
types)
• C language doesn’t have a separate type for strings.
2/8/2021 Data Types Classification 35
Fundamental Data Type
2/8/2021 Data Types Classification 36
• The fundamental types can be further divided
into the following three subtypes:
– Integer (the keywords short, int, long and long
long)
– Floating point (the keywords float, double and
long double)
– Character (the keyword char)
sizeof Operator
• The sizeof operator evaluates the size of all data types—the
fundamental types, pointers, arrays and constants.
• This is how you can find the size of the int data type on your
computer:
– printf(“Size of int: %dn”, sizeof(int));
• This should print 2/4 on your PC.
• Note that sizeof is not a function even though it looks like one.
• It is an operator (like = and +) which works on an operand, which
here is enclosed within parentheses in function-like manner.
• There are no fixed sizes for the fundamental data types, but only
ANSI-specified minimum sizes.
• Unlike other operators that evaluate their operands during
runtime, sizeof is a compile-time operator. The result of its
operation is known to the compiler at the time of compilation,
which implies that the value is built into the executable.
2/8/2021 Data Types Classification 37
2/8/2021 Data Types Classification 38
Integer Types
• An integer is a contiguous collection of digits without a
decimal point but it may contain the - prefix. For
instance, 65536 and -7 are integers.
• The - in -7 is an operator; it multiplies 7 by -1.
• C uses the int keyword to declare an integer variable.
• Using the short and long qualifiers in addition.
• C offers a total of four types of integers, whose
abbreviated and expanded keywords are shown in the
following list:
– int
– short or short int (short is a qualifier to int)
– long or long int (long is a qualifier to int)
– long long or long long int (long long is a qualifier to int)
2/8/2021 Data Types Classification 39
Integer Types
• A minimum size for the types:
– short — 2 bytes (16 bits)
– int — 2 bytes (16 bits) Modern int is 4 bytes
– long — 4 bytes (32 bits)
– long long — 8 bytes (64 bits)
• A relationship between the types that can be
represented in this form:
– char <= short <= int <= long <= long long
2/8/2021 40
Data Types Classification
Signed and Unsigned Integers
• By default, the four int types are signed, which means that they can
handle both positive and negative integers.
• This default behavior can be overridden by using the unsigned qualifier
before the keyword.
• For instance, the statement
unsigned int count;
• allows count to store only positive integers.
• The basic format specifier for the signed integer data type is %d.
• A modifier is needed for short (h), long (l) and long long (ll).
• For unsigned types, replace %d with %u with the same modifiers as
considered necessary
2/8/2021 Data Types Classification 41
Power of 10
2/8/2021 Data Types Classification 42
2/8/2021 Data Types Classification 43
2/8/2021 Data Types Classification 44
Specific Integer Types
• The short Type
– Abbreviated from short int, the minimum and typical size for
this type is 2 bytes.
– For the range it offers (-32,768 to 32,767), short is suitable for
positive integral entities like age, marks and family size.
– If you need an integer greater than 32,767 but less than 65,535,
use unsigned short.
• The int Type
– This is the standard integer type that reflects the word size of
your machine.
– Like short, its minimum size is 2 bytes, but since most
computers today are 32-bit machines, int is also 32 bits (4
bytes).
– A signed int can handle numbers up to 2 billion (on both +ve and
-ve sides), while the unsigned type can hold a number up to 4
billion.
– The popular and often misused %d format specifier actually
applies to int.
2/8/2021 Data Types Classification 45
Specific Integer Types
• The long Type
– The long type (abbreviated from long int) is meant to hold
numbers larger than int.
– However, that has not always been the case on 32-bit systems.
– In most cases, int and long are the same size—4 bytes, but on
some systems you could see a long of 8 bytes.
– Also, most 64-bit programming models use 8-byte long
integers. An 8-byte long integer can handle values in the
quintillion range.
• The long long Type
– This type was added by C99 to the language to accommodate
64-bit integers.
– On most systems that support this type, long long is 8 bytes.
– Since long in most 64-bit models is already set to 8 bytes, it’s a
little too early to say what the eventual size of long long would
be.
2/8/2021 Data Types Classification 46
Octal and Hexadecimal Integers
• Apart from decimal integers (base-10), C also supports octal (base-
8) and hexadecimal (base-16) numbers.
• C identifies them by a special prefix.
• Octal:
– When a 0 (zero) prefixes a number comprising the digits 0 to 7, C
interprets the number as octal. Thus, 072 is an octal integer having the
value (58)10
– (7 × 81 + 2 × 80 = 58).
– The printf/scanf duo uses %o to handle octal integers.
• Hexadecimal:
– When a number comprising the digits 0 to 9 and A to F is preceded by
0x or 0X, C interprets the number as hexadecimal. Thus, C
understands 0x72 as a base-16 number having the value (114)10
– (7 × 161 + 2 × 160).
– Use the %x or %X format specifier to handle hex integers.
• Systems programmers need to be familiar with these numbering
systems because many programs output numbers in these forms.
2/8/2021 Data Types Classification 47
2/8/2021 Data Types Classification 48
Floating Point Types
• A floating point number is a number with a decimal point, which
divides it into integral and fractional components.
• The Fortran and Pascal languages as well as the scientific
community understand it as a real number.
• A floating point number is suitable for representing prices, averages
and ratios. It is also used for storing very large and small numbers
like the number of stars in the universe or the percentage of argon
in the atmosphere.
• There are two ways of representing floating point numbers.
• The first way is the one we commonly use—a number with a
decimal point. Also, as the last two items of the following examples
show, you may omit digits before or after the decimal point:
44.1 -0.3048 .00075 7. 7. is different from 7
2/8/2021 Data Types Classification 49
Floating Point Types
• The second way is to use the exponential or scientific notation.
• This notation uses two components— mantissa and exponent—
separated by the letter E or e.
• It is expressed in this general form:
mantissa E exponent Can use e instead of E
• The mantissa, which is an integer or real number, is multiplied by 10 with
the exponent as its power.
• For instance, 44.1 is equivalent to 4.41X101, so it is expressed as 4.41E1
using exponential notation. Here, 4.41 is the mantissa and 1 is the
exponent.
• The exponent signifies the number of places the decimal point needs to
shift to the right to convert a number to the conventional form.
• The point floats (hence, the term floating point number) and the
exponent controls this float.
• If you increase the value of the exponent, the point has to move to the left
to keep the number unchanged. So, 44.1 can be expressed as 4.41E1,
0.441E2 and 0.0441E3, as well as 441E-1.
2/8/2021 Data Types Classification 50
Floating Point Types
• Consider some more examples:
• A floating point number has a precision, which signifies the
number of significant digits used in its representation.
• For instance, the value of PI is 3.142 when expressed with
4-digit precision, and 3.142857 when 7-digit precision is
used.
2/8/2021 Data Types Classification 51
Floating Point Types
2/8/2021 Data Types Classification 52
Floating Point Types
• While integers are classified by their size, floating point
numbers are classified by their precision.
• C supports three types of floating point numbers whose
keywords are noted below:
– float (single precision)
– double (double precision)
– long double (quad precision)
• Unlike with integers, ANSI specifies a single minimum range
for all of them.
• This range for a positive number is 10-38 to 10+38, but it
must also satisfy the following condition:
• range of float <= range of double <= range of long double
2/8/2021 Data Types Classification 53
Floating Point Types
• The float Type
– ANSI requires a float to represent at least 6 significant digits within its
minimum range of 10-38 to 10+38.
– This means that it must be able to handle at least the first 6 digits in a
number like 77.789654.
• The double Type
– For this type, ANSI specifies a greater precision—at least 10 digits.
– The double type usually allows a very high range of values—10-308 to
10+308.
• The long double Type
– ANSI provides this type with the same precision as double.
– For systems that support this type, long double uses 8 to 16 bytes.
• Floating point computing is slower than integer computing.
• The double and long double types may take up a lot of memory on
your system, so don’t use them unless you need a range and
precision greater than what is offered by float.
2/8/2021 Data Types Classification 54
Floating Point Types
2/8/2021 Data Types Classification 55
2/8/2021 Data Types Classification 56
Character Type (char)
• C supports the char data type which is just wide
enough to hold the values of the computer’s character
set.
• It use the 8-bit ASCII character set, so char by
definition is one byte wide.
• Even though char is essentially an integer type, we are
discussing it separately for two reasons:
– The numeric value stored in a char variable can easily be
displayed in its equivalent character form and vice versa.
– Strings owe their origin to char. A string is simply an array
of type char.
2/8/2021 Data Types Classification 57
Char Data Type
• The first point implies that the value 65 stored as a char can
be printed as A by printf using %c.
• Conversely, the character A input from the keyboard can be
saved in a char variable as 65 by scanf using %c.
• Data of type char can also be represented in two other
ways:
– By a character enclosed within single quotes (e.g. ‘A’).
– By a special escape sequence like ‘c’, but only a handful of non-
printable characters can be represented by an escape sequence.
• Like the other integer types, char occurs in signed and
unsigned forms.
• The signed form can hold values between -128 to 127,
while the range for the unsigned type is 0 to 255.
2/8/2021 Data Types Classification 58
char as Integer and Character
• If char is unsigned, then every character of the 8-bit
ASCII set can be assigned to a char variable.
• The following examples demonstrate that any integer
type can be used to display a character with %c.
• The last statement should sound a beep as the BEEP
character ([Control-g]) has the ASCII value 7.
2/8/2021 Data Types Classification 59
char as Integer and Character
• Beginners often make the mistake of using
double quotes (“A” instead of ‘A’).
• Double-quoted characters (like “A” or
“Internet of things”) represent a string, which
is not a fundamental data type.
• C understands a string as an array (a derived
data type) of type char, but more of that later.
• In C, ‘A’ is different from “A”. The former is a
character and the latter is a string.
2/8/2021 Data Types Classification 60
Computation with char
• Since any single-quoted character actually represents
an integer, it can be used in arithmetic operations.
• The following assignments are all valid, but the third
one has a message to convey:
• Should we use ‘A’ or 65, its ASCII value? The question
is significant because on EBCDIC systems (designed by
IBM), ‘A’ evaluates to 193 and not 65.
2/8/2021 Data Types Classification 61
ASCII Table
2/8/2021 Data Types Classification 62
EBCDIC Table
2/8/2021 Data Types Classification 63
2/8/2021 Data Types Classification 64
char as Escape Sequence
• C supports the escape sequence as a synonym for a
non-printable character.
• An escape sequence is a two-character combination
comprising a  (backslash) and a lowercase letter.
• The  forces the character following it to be treated
specially.
• we observe that t (the tab) expands to eight spaces
on your terminal.
• The newline (n) is universally used in printf to
advance the cursor to the next line.
• The f initiates a page break.
2/8/2021 Data Types Classification 65
List of Escape Sequence in C
2/8/2021 Data Types Classification 66
2/8/2021 Data Types Classification 67
Data Type of Constants
• Constants represent data that don’t change in the program.
• C supports a wide range of constants—both unnamed and named—
which may be grouped into the following categories:
– Unnamed constants belonging to the fundamental data types. The
constants 12, -34.5 and ‘A’ belong to this category.
– Named or symbolic constants that are defined with #define at the
beginning of the program.
– Variables that behave like constants when the const qualifier is added
to the variable declaration.
– String constants like “Nougat is here” belong to the derived data type.
• C specifies a default type for a constant, but this default is often
changed by the compiler or the programmer. This can happen for
the following reasons:
– The size of the constant is too large to be accommodated in the
default type.
– For instance, the number 5000000000 is too large for an int, the
default type for integer constants.
2/8/2021 Data Types Classification 68
Integer Constants
• C specifies int (signed) as the default type for
an integer constant.
• The compiler treats 655 as an int even though
the number easily fits in a short.
• If a constant doesn’t fit in its default type, the
compiler tries the next higher type using the
following sequence:
2/8/2021 Data Types Classification 69
Integer Constants
• C offers special symbols that can be suffixed to these
constants:
• For instance, the compiler, which otherwise sees 3 as an
int, treats 3L as a long.
• There are no constants of type short.
• Next time you see the constants 540U or 450L, remember
to treat them as unsigned int and signed long, respectively
2/8/2021 Data Types Classification 70
Floating Point Constants
• Floating Point Constants C treats a real
constant as a double which takes up 8 bytes
on most systems.
• Constants like 3.142 and 1789.456 have the
type double even though a float (4 bytes) is
wide enough for them.
2/8/2021 Data Types Classification 71
Character Constant
• Character Constants Any character or escape
sequence enclosed in single quotes represents a
character constant.
• The characters ‘A’, ‘t’ and ‘7’ are character
constants having the ASCII values 65, 11 and 7,
respectively.
• Strangely enough, C treats character constants as
type int rather than char.
• This means the constant ‘A’ is stored in a space of
4 bytes (size of int).
2/8/2021 Data Types Classification 72
Summary of Constants
• The default type for an integer constant is int.
• For a real number, the default is double.
• A character constant is stored as an int.
• C doesn’t support a constant of type short.
2/8/2021 Data Types Classification 73
Variables as Constants: The const
Qualifier
• A constant that is used multiple times in a
program is often stored as a variable.
• If the value is changed later, then the code
needs to be modified at a single location, thus
making maintenance easier.
• The constant itself should be stored as a
variable using the const qualifier:
2/8/2021 Data Types Classification 74
2/8/2021 Data Types Classification 75
2/8/2021 Data Types Classification 76
Arrays and Strings
• we may need to store the monthly rainfall for
an entire year. Rather than create 12 variables,
we use an array to store the 12 values.
• An array is a collection of data items
belonging to a single type.
• The following statement declares an array
having the name month. It is capable of
holding 12 values, each of type int:
2/8/2021 Data Types Classification 77
Arrays
• Assuming a 4-byte int, the compiler uses this declaration or
definition to allocate a contiguous chunk of 48 bytes of
memory.
• Each element of the array is accessed by the notation
month[n], where n is an integer representing the index.
• The value of n here lies between 0 and 11.
• The first element is accessed as month[0] and the last
element is month[11].
• You can perform the initialization at the time of
declaration by assigning a set of comma-delimited values
enclosed by curly braces
2/8/2021 Data Types Classification 78
2/8/2021 Data Types Classification 79
Thank you
2/8/2021 Data Types Classification 80
Operators and Expressions
By
Mr.S.Selvaraj
Asst. Professor (SRG) / CSE
Kongu Engineering College
Contents
1. Life Cycle of a C Program
2. Features of C
3. Data Variables
– Declaring, Assigning and Printing Variables
4. Data Type Classification
– Integer, Float, Character and Constants
5. Operators and expressions
6. Control Structures
– Decision making and Looping statements
7. Input and output functions
2/8/2021 82
Operators and Expressions
Expressions
• Variables and constants represent data in their most elemental form.
• These data objects become useful when combined with one another to
form expressions.
• The components of an expression are linked to one another by symbols
called operators.
• For instance, a + b / 7 is an expression where + and / are operators.
• The expression has a value which here is evaluated arithmetically
2/8/2021 Operators and Expressions 83
Operators
• Operators form the connecting link between variables and
constants in expressions.
• An operator acts on one or more operands.
• For instance, in the expression x - 5, the - symbol is an
operator, which acts on the operands x and 5.
• C supports a rich collection of operators—richer than any
language known previously.
• These operators can be grouped into the following types:
2/8/2021 Operators and Expressions 84
Operators
• An operator may be unary, binary or ternary.
• A unary operator has one operand.
– For instance, the - symbol in the negative constant -5 is a unary
operator which multiplies its operand by -1.
– The unary - is different from the binary - which performs
subtraction.
– The ++ in count++ is a unary operator which increments its
operand by one.
• Most operators are of the binary type which needs two
operands.
– The assignment operator = in x = 5 is a binary operator.
– Arithmetic operators like * and / and relational operators like >
and < are also binary operators.
• C has one ternary operator which uses the ? and : symbols.
2/8/2021 Operators and Expressions 85
Operators
• When an expression contains multiple operators, the
order of their evaluation becomes important.
• For instance, when evaluating the expression x + y * z,
does multiplication occur before addition?
• For this purpose, C specifies two attributes for each
operator:
– The precedence (priority) ensures that a high-priority
operator is acted upon before a low-priority one. In the
expression x + y * z, the * has a higher precedence than +,
so multiplication will be done first.
– The associativity determines the direction of evaluation
(left-to-right or right-to-left). In the expression x * y / z, it
is associativity and not precedence that determines that
multiplication will be done first.
2/8/2021 Operators and Expressions 86
2/8/2021 Operators and Expressions 87
2/8/2021 Operators and Expressions 88
Arithmetic Operators
2/8/2021 Operators and Expressions 89
/ and% Operators
• Integer division (/) operator leads to truncation of the
decimal portion. i.e., only Quotient Portion is taken.
• The Modulus Operator (%) evaluates the remainder of
a division between two integers. The expression 10 % 7
(10 modulo 7) evaluates to 3.
2/8/2021 Operators and Expressions 90
2/8/2021 Operators and Expressions 91
Automatic or Implicit Type Conversion
• When numbers of different data types are used in an expression, the
compiler converts a lower type to a higher type using the concept of
implicit promotion.
• C finally converts the type of the expression itself to the highest type it
finds there.
• Consider this simple expression that involves an assignment:
float pi = 22 / 7.0;
• Here, the variables and constants have three different data types.
• Recall that 7.0 has the type double and 22 is of type int.
• C treats a real constant as a double which takes up 8 bytes on most
systems. Constants like 3.142 and 1789.456 have the type double even
though a float (4 bytes) is wide enough for them.
– It looks at the operands of the / operator and finds 7.0 to have a higher type
than 22. It converts 22 to double as well, so the resultant expression also has
the type double. This means that sizeof(22 / 7.0) = sizeof(double).
– It then looks at the operand on the left of the =. This is a variable of type
float, which has a lower type than double. But since C can’t change the type
of a variable that has been declared with a specific type, it demotes the type
of the entire expression on the right to fl oat.
2/8/2021 Operators and Expressions 92
2/8/2021 Operators and Expressions 93
Explicit Type Conversion—the Type Cast
• The technique of using the F, L and LL suffixes to change
the data type of constants. This technique doesn’t apply to
variables.
• The ultimate conversion tool for explicit conversion or
coercion is the type cast or cast.
• A cast is a unary operator having two components: the
name of the data type (int, fl oat, etc.) enclosed in
parentheses, followed by the data item that needs
conversion.
• The data item can be any variable, constant or expression
of any type.
• For instance, (float) represents a cast, and (float)x
evaluates x as a float even though x may actually be of
type int.
2/8/2021 Operators and Expressions 94
Exmples
2/8/2021 Operators and Expressions 95
Order of Evaluation
• You probably remember the “BODMAS”
acronym from your school days, which
specified that division is performed before
addition (D before A in BODMAS).
• C too has a set of rules for all the 40 operators
of the language.
• These rules, which we’ll now discuss, are
based on two operator attributes:
precedence and associativity.
2/8/2021 Operators and Expressions 96
Operator Precedence
• Every operator has a precedence which signifies the
priority of its operation.
• An operator belonging to a higher level has a greater
precedence or priority than a lower-level operator.
2/8/2021 Operators and Expressions 97
Example
2/8/2021 Operators and Expressions 98
Operator Associativity
• Every operator has an associativity which
determines the direction of evaluation when
an operand is shared by two operators having
the same precedence.
• This attribute can take on two values— right-
to-left (R-L) or left-to-right (L-R).
2/8/2021 Operators and Expressions 99
2/8/2021 Operators and Expressions 100
Assignment Operators
2/8/2021 Operators and Expressions 101
++ and -- Operator
• A programmer frequently needs to increment
or decrement a variable by one—especially
inside a loop.
• C provides shortcuts for performing these two
operations: the unary ++ and -- operators.
2/8/2021 Operators and Expressions 102
2/8/2021 Operators and Expressions 103
++ and -- operator as prefix and postfix
• If you use the ++ operator as prefix
like: ++var. The value of var is incremented by
1 then, it returns the value.
• If you use the ++ operator as postfix
like: var++. The original value of var is
returned first then, var is incremented by 1.
• The -- operator works in a similar way like
the ++ operator except it decreases the value
by 1.
2/8/2021 Operators and Expressions 104
Example 1
2/8/2021 Operators and Expressions 105
Relational operators and expressions
2/8/2021 Operators and Expressions 106
Logical Operators
2/8/2021 Operators and Expressions 107
Conditional Operators
• C supports the only ternary operator—the
conditional operator—which uses the symbols
? and :
• These two symbols are used with three
expressions to implement a rudimentary form
of decision making.
• The operator uses the following formal syntax:
2/8/2021 Operators and Expressions 108
Example
• exp1, exp2 and exp3 represent three expressions,
– where exp1 is generally a relational one.
– The composite expression evaluates to exp2 if exp1
evaluates to true, or exp3 otherwise.
– Here’s how you can use this operator to make a
simple decision.
• If total is greater than zero, then 0.95 is assigned to
rate, otherwise 0.90 is assigned. Nothing could be
simpler than that!
2/8/2021 Operators and Expressions 109
Thank you
2/8/2021 Operators and Expressions 110
Control Structures
By
Mr.S.Selvaraj
Asst. Professor (SRG) / CSE
Kongu Engineering College
Contents
1. Life Cycle of a C Program
2. Features of C
3. Data Variables
– Declaring, Assigning and Printing Variables
4. Data Type Classification
– Integer, Float, Character and Constants
5. Operators and expressions
6. Control Structures
– Decision making and Looping statements
7. Input and output functions
2/8/2021 112
Control Structures
Control Structures : Decision Making
• Control expression for making decisions.
• Use of the if-else construct for two-way decision
making.
• Nesting of if-else constructs for multi-way
decision making.
• Switch construct for testing equality.
• goto statement.
2/8/2021 Control Structures 113
Decision Making in C
• C addresses selection issues with the
following three constructs:
– The if statement supported by the optional else
keyword.
– The switch statement.
– The conditional operator.
2/8/2021 Control Structures 114
Control Expression
• Some C constructs like the if-else and while
statements use the true or false value of a
control expression to determine control flow.
• They require this expression to be enclosed by
parentheses.
• The control expression is normally a relational or
logical expression as shown by the
• following examples:
2/8/2021 Control Structures 115
Control Expression
• But a control expression can also be any
expression that returns any value including 0.
• Also, because any non-zero value is true in C.
• The following expressions are also valid even if
they are neither relational nor logical:
2/8/2021 Control Structures 116
2/8/2021 Control Structures 117
Compound Statement or Block
• When using constructs like if and while, you’ll need to
address a group of statements as a single unit.
• This unit, which is flanked on either side by a matched
pair of curly braces, is called a compound statement.
• It is also known as a control block, or, simply, block.
• It could be helpful to keep in mind that a block changes
the scope (i.e. visibility) of a variable declared inside it.
• Such a variable is not visible outside the block or in
other blocks.
2/8/2021 Control Structures 118
THE if STATEMENT
• The if statement is the most commonly used
selection construct in any programming language.
• It has basically two forms—with and without the
else keyword.
2/8/2021 Control Structures 119
THE if STATEMENT
• Execution of this statement begins by evaluating
expression.
• If this value is true, then one or more statements are
executed.
• Curly braces are not required for a single statement
but they are needed for a compound statement.
• Here’s a simple example
2/8/2021 Control Structures 120
if-else: TWO-WAY BRANCHING
2/8/2021 Control Structures 121
Example
• Consider a store that offers a weekend
discount of 10% for purchases over Rs 1000,
and 5% otherwise.
• The code that computes the amount payable
can be represented in this manner.
2/8/2021 Control Structures 122
2/8/2021 Control Structures 123
2/8/2021 Control Structures 124
MULTI-WAY BRANCHING WITH if-else-if ...
2/8/2021 Control Structures 125
Example
• Let’s now use this construct to compute the tariff
for the 4G Internet service offered by a mobile
operator.
• The tariff is Rs 255 for up to 1 GB,
• Rs 455 for up to 2 GB,
• Rs 755 for up to 4 GB and
• Rs 995 there after (simplified from live data).
• This logic is easily implemented using the if-else-if
form:
2/8/2021 Control Structures 126
2/8/2021 Control Structures 127
2/8/2021 Control Structures 128
MULTI-WAY BRANCHING WITH NESTED if (if-if-else)
2/8/2021 Control Structures 129
Example
2/8/2021 Control Structures 130
THE CONDITIONAL EXPRESSION (?:)
• The conditional expression is construct uses
two symbols (? and :) as a ternary operator.
• The operator acts on three expressions using
the following formal and functional syntaxes:
2/8/2021 Control Structures 131
2/8/2021 Control Structures 132
THE switch STATEMENT
• We use the equality test so often that C has a
special construct to handle it.
• It’s the switch statement which implements
multi-way branching with a compact and
structured construct.
• If you need to match 10 integer values for
making 10 different decisions, use switch
whose syntax is shown in next slide.
2/8/2021 Control Structures 133
2/8/2021 Control Structures 134
• switch first evaluates exp which must be an integer or character
variable or constant.
• It next tries to match exp with value1. If the match succeeds,
switch executes one or more statements represented by
statements1.
• If the match fails, switch attempts to match exp with value2 and so
on until control moves to the keyword default (if present).
• This option is thus invoked when all previous matching operations
fail.
• For this purpose, switch is assisted by three keywords—case, break
and default.
• The entire set of options and their associated action are enclosed in
curly braces.
2/8/2021 Control Structures 135
Example
2/8/2021 Control Structures 136
goto STATEMENT
• C also supports a goto statement that lets
control branch to a different point in the
program without returning to the point in the
program from where it was executed.
• It may be used only in rare situations.
2/8/2021 Control Structures 137
2/8/2021 Control Structures 138
Control Structures—Loops
• In addition to decision making, a language
must be able to repeatedly execute a set of
statements.
• Constructs that do that are known as loops,
and C offers three of them—while, do-while
and for.
2/8/2021 Control Structures 139
2/8/2021 Control Structures 140
Looping Concepts
• Even though all of the three loops offered by C broadly conform to
the above scheme, there are minor differences between them.
• First, the initialization may be done in the loop construct itself (for
loop) instead of being done outside.
• Second, the control expression may be evaluated at the end (do-
while loop) instead of at the beginning.
• Finally, a control expression can’t prevent a do-while loop from
performing at least one iteration even though it can prevent the
other loops from running at all.
• A loop iteration can either be suspended (to start a new one) or
terminated altogether without re-testing the control expression.
This is achieved with the continue and break keywords that can be
invoked anywhere in the loop body.
• A loop is generally designed to execute a finite number of times,
but many applications need a loop to run all the time. Such loops
are known as infinite loops. For example (while (1)).
2/8/2021 Control Structures 141
THE while LOOP
2/8/2021 Control Structures 142
THE while LOOP
• The while loop is an entry-controlled loop, which
means that loop entry is not guaranteed.
• If the control expression is false to begin with,
then the loop is not entered at all.
• This is also true of the for loop, but not the do-
while loop which is an exit-controlled loop.
• The control expression in a do-while loop is
tested at the end of the loop, which means that
initial loop entry is guaranteed but not its
subsequent iterations.
2/8/2021 Control Structures 143
2/8/2021 Control Structures 144
Some other examples
2/8/2021 Control Structures 145
Updating the Key Variable in the
Control Expression
2/8/2021 Control Structures 146
Practice Programs
• Determining the Factorial of a Number.
• Program to Reverse Digits of an Integer.
• Printing and Summing the Fibonacci Numbers.
2/8/2021 Control Structures 147
NESTED while LOOPS
2/8/2021 Control Structures 148
2/8/2021 Control Structures 149
Printing a Half-Pyramid with Digits
2/8/2021 Control Structures 150
2/8/2021 Control Structures 151
2/8/2021 Control Structures 152
USING while WITH break AND continue
2/8/2021 Control Structures 153
break AND continue
• When the program sees break, control breaks
out of the loop to resume execution from the
statement immediately below the end of the
loop.
• On the other hand, continue doesn’t
terminate a loop but suspends loop execution
to resume the next iteration.
2/8/2021 Control Structures 154
THE do-while LOOP
2/8/2021 Control Structures 155
THE do-while LOOP
• A do-while loop is an exit-controlled loop and not an
entry-controlled one.
• C supports a do-while loop which functionally differs
from while in only one respect: the control expression
is tested at the end of the loop.
• This means that a do-while loop is guaranteed to
perform at least one iteration.
• The loop begins with the do keyword and ends with
the ; in the last line which contains the while keyword.
• This is in contrast to the while loop which terminates at
the ; of its only or last statement.
2/8/2021 Control Structures 156
Examples
2/8/2021 Control Structures 157
Practice Program
• convert a decimal number to binary but
without reversing the bits.
2/8/2021 Control Structures 158
2/8/2021 Control Structures 159
2/8/2021 Control Structures 160
THE for LOOP
• Like while and do-while, the for loop also uses
the key variable/control expression paradigm
to determine loop entry and continuity.
• It is a compact construct that gathers three
expressions at one place.
• Any while loop can be replaced with a for
loop.
2/8/2021 Control Structures 161
THE for LOOP
2/8/2021 Control Structures 162
THE for LOOP
• The while loop works on the principle of
– initializing a key variable before the loop,
– testing it in the control expression and
– updating the key variable in the body.
• The three expressions in for do the same work but at one
place.
– The initialization is done by exp1,
– the key variable check is done by exp2, and
– updating of the key variable is done by exp3.
• These expressions, which are delimited by semicolons,
determine whether a loop will run, and if so, how many
times.
• Like while, for is an entry-controlled loop because exp1
and exp2 jointly determine whether the loop will be
entered at all.
2/8/2021 Control Structures 163
Example
2/8/2021 Control Structures 164
2/8/2021 Control Structures 165
Moving All Initialization to exp1
2/8/2021 Control Structures 166
Moving Expression Statements in Body to exp3
2/8/2021 Control Structures 167
The Infinite Loop
• Depending on the nature of the problem, any
of the three expressions can be dropped.
• As a special case, all of them can be dropped
to create an infinite loop.
2/8/2021 Control Structures 168
CONVERTING A DECIMAL NUMBER TO BINARY
2/8/2021 Control Structures 169
2/8/2021 Control Structures 170
NESTED for LOOPS
• One for loop can enclose any number of inner
for loops.
• For reasons of compactness, nested for loops
are often preferred to nested while loops.
• Nested for loops are the perfect tool to use
for printing patterns.
2/8/2021 Control Structures 171
Example
2/8/2021 Control Structures 172
2/8/2021 Control Structures 173
• The expression i <= rows controls the number of rows
• The expression j <= rows - 1 controls the number of spaces, and
• the expression k != 2 * i – 1 controls the number of asterisks.
Thank you
2/8/2021 Control Structures 174
I/O Functions
By
Mr.S.Selvaraj
Asst. Professor (SRG) / CSE
Kongu Engineering College
Contents
1. Life Cycle of a C Program
2. Features of C
3. Data Variables
– Declaring, Assigning and Printing Variables
4. Data Type Classification
– Integer, Float, Character and Constants
5. Operators and expressions
6. Control Structures
– Decision making and Looping statements
7. Input and output functions
2/8/2021 176
IO Functions
Introduction
• C supports no keywords for taking input from
the keyboard or for displaying output on the
terminal.
• Functions that carry out input/output
operations consider data as a stream of
characters irrespective of the data type they
actually represent.
2/8/2021 IO Functions 177
Introduction
• Most I/O functions have to contend with two issues—
– EOF and
– buffering of data.
• Input functions often need to check for an end-of-file
(EOF) condition.
• The term “file” is misleading because EOF actually
indicates the end of data.
• There’s no character named EOF in the ASCII character
set.
• For keyboard input,
– UNIX/Linux systems use [Ctrl-d] and
– MSDOS/Windows systems use [Ctrl-z] to indicate EOF to a
program.
2/8/2021 IO Functions 178
First Issue - EOF
• EOF is represented as a symbolic constant defined in
stdio.h.
• Since any value between 0 and 255 is a valid return value
for getchar and scanf.
• ANSI requires EOF to have a value that is outside the range
of the character set of the machine.
• Typically, it is -1 but ANSI doesn’t specify that it must be so.
2/8/2021 IO Functions 179
Second Issue – Buffering of data
• A buffer is a block of memory allocated for temporary storage of
data.
• When you input data to a program, say, using scanf, the data is first
kept in this buffer before it is transmitted to the program.
• Similarly, when a program outputs data, say, using printf, the data
is first written to a buffer before it is transferred to the output
device.
• Both operations require flushing of the buffer, the mechanism by
which the contents of the buffer are transferred to the final
destination.
2/8/2021 IO Functions 180
Types of I/O Functions
• These functions can be grouped into two
categories:
• Character-handling functions
– (like getchar, fgetc, putchar and fputc).
• Formatted I/O functions
– (printf and scanf).
• These functions also perform conversion of
data between character and other data types.
2/8/2021 IO Functions 181
CHARACTER INPUT WITH getchar
• The C standard library is a collection of archives and header files.
• An archive is a disk file that contains the precompiled object code
of several functions.
• The prototypes of these functions are maintained in a set of
header files (like stdio.h).
2/8/2021 IO Functions 182
getchar()
• The getchar function fetches the next character
from the input buffer that has previously been
filled with keyboard input.
• It is a character-oriented function, which means
it treats input (say, the string 123) as three
characters even if they represent a number.
• getchar uses no arguments (the word void in the
prototype) and returns the machine value of this
character as an int.
2/8/2021 IO Functions 183
getchar()
• There are mainly three uses of this function:
• (1). Pause a Program.
– A call to getchar pauses a program which resumes operation
after the user has pressed [Enter].
• (2). Accept a single-character response.
– In this situation, the return value of getchar is saved and later
used for decision making by an if or switch statement:
• If you key in y and press [Enter], these two characters are
saved by the input buffer.
• getchar fetches the y and returns it as an int, but it leaves
behind the newline character in the buffer.
2/8/2021 IO Functions 184
getchar()
• (3). Fetch a group of characters by running in
a loop.
– In this sequence, getchar fetches all characters
from the buffer before it encounters EOF, when
the loop terminates.
– Every fetched character is written to the terminal
using the putchar function.
2/8/2021 IO Functions 185
CHARACTER OUTPUT WITH putchar
• The putchar function complements the role of
getchar by writing one character to the terminal.
• This character is accepted as an argument of type
int.
2/8/2021 IO Functions 186
putchar()
• When dealing with single characters, getchar
and putchar are preferred to their formatted
cousins, scanf and printf.
• The other functions of this family (getc/putc
and fgetc/fputc) also provide the same
functionality as getchar and putchar.
2/8/2021 IO Functions 187
BUFFER-RELATED ISSUE
2/8/2021 IO Functions 188
THE STANDARD FILES
• C treats the keyboard, terminal and printer as
files.
– stdin, the standard input file (default: keyboard).
– stdout, the standard output file (default: terminal).
– stderr, the standard error file (default: terminal).
2/8/2021 IO Functions 189
OTHER CHARACTER-I/O FUNCTIONS
• The getchar and putchar functions were designed
to work only with stdin and stdout, respectively.
• The standard library supports another two sets of
functions that also read and write a character:
– fgetc and fputc
– getc and putc
• Unlike getchar and putchar, the preceding
functions are meant to be used with any file—
includinga disk file.
2/8/2021 IO Functions 190
The fgetc and fputc Functions
• I/O functions that have the “f ” prefix are designed to
work with files.
• Both fgetc and fputc use an argument that identifies
the file.
• When used with the arguments, stdin or stdout, these
functions replicate the behavior of their
getchar/putchar equivalents, as shown in the
following:
2/8/2021 IO Functions 191
Example
2/8/2021 IO Functions 192
The getc and putc Macros
• C also supports the getc and putc macros, which
replicate the functionality of the fgetc and fputc
functions.
• Both sets use the same type and number of
arguments and return the sam
• A C macro is an alias that behaves like a function
without incurring the cost of a function call.
• It is defined using the #define preprocessor
directivee values.
2/8/2021 IO Functions 193
The ungetc Function
• The ungetc function reverses the action of
getc by putting back the most recently read
character to the input stream.
2/8/2021 IO Functions 194
Takeaway
• The functions and macros that we have
discussed so far read and write data as
characters.
• They cannot identify or handle specific data
types in the character stream.
• The rest of this section examines the scanf
and printf functions that convert character
data into specific data types and vice versa.
2/8/2021 IO Functions 195
FORMATTED INPUT: THE scanf FUNCTION
• scanf is the main member of a family of input functions
that includes fscanf and sscanf.
• Unlike most functions, scanf uses a variable number of
arguments.
• The first argument (cstring) is a control string containing
one or more format specifiers (like %d).
• The remaining arguments (&var1, &var2, etc.) represent—
not variables—but their addresses.
• The number of variable addresses must equal the number
of format specifiers.
2/8/2021 IO Functions 196
Components of scanf
2/8/2021 IO Functions 197
Example
• if the control string is “%c %d %f” and scanf encounters
the string M 1986 37.4, it performs the following tasks:
– Saves the character M (%c) to the variable gender without
performing any conversion.
– Converts the string 1986 to the integer 1986 (%d) and
saves it in the variable year.
– Converts the four-character string 37.4 to the floating
point value 37.4 (%f) and saves it in the variable amount.
2/8/2021 IO Functions 198
Example
2/8/2021 IO Functions 199
2/8/2021 IO Functions 200
scanf: THE MATCHING RULES
• scanf splits input on whitespace (space, tab
and newline) even if the control string doesn’t
contain whitespace.
• Before doing anything else, you must commit
the following rule to memory:
– “Whitespace in the control string matches zero or
more leading whitespace characters in the
input”.
2/8/2021 IO Functions 201
Examples
• This means that both %d%d and %d %d match the strings
12 45 and 12 45.
• This rule doesn’t apply to %c.
• First, if the control string contains non-whitespace
characters, the same characters must be present in the
input.
– For instance, %d:%d:%d matches 12:30:45 and 12: 30: 45 but
not 12 :30 :45 because two values contain trailing whitespace.
• Second, if a field width is specified (as in %2d), scanf tries
to match two characters of the specified data type.
– Thus, %2d%2d%2d splits the string 311214 into the values 31,
12 and 14 and saves them in three int variables.
2/8/2021 IO Functions 202
Mismatches and Return Value
2/8/2021 IO Functions 203
FORMATTED OUTPUT: THE printf FUNCTION
2/8/2021 IO Functions 204
Components of printf
2/8/2021 IO Functions 205
2/8/2021 IO Functions 206
Thank you
2/8/2021 IO Functions 207

Weitere ähnliche Inhalte

Was ist angesagt?

Computer programming language concept
Computer programming language conceptComputer programming language concept
Computer programming language concept
Afiq Sajuri
 
Computer Fundamentals Chapter 12 cl
Computer Fundamentals Chapter 12 clComputer Fundamentals Chapter 12 cl
Computer Fundamentals Chapter 12 cl
Saumya Sahu
 
Lang generations 7557_syed_ghazanfarnaqvi_saturday
Lang generations 7557_syed_ghazanfarnaqvi_saturdayLang generations 7557_syed_ghazanfarnaqvi_saturday
Lang generations 7557_syed_ghazanfarnaqvi_saturday
Syed Naqvi
 
Machine language
Machine languageMachine language
Machine language
Ripal Dhruv
 

Was ist angesagt? (20)

FIT-Unit3 chapter2- Computer Languages
FIT-Unit3 chapter2- Computer LanguagesFIT-Unit3 chapter2- Computer Languages
FIT-Unit3 chapter2- Computer Languages
 
computer languages
computer languagescomputer languages
computer languages
 
Computer languages 11
Computer languages 11Computer languages 11
Computer languages 11
 
Introduction to computer programming
Introduction to computer programmingIntroduction to computer programming
Introduction to computer programming
 
Computer programming programming_langugages
Computer programming programming_langugagesComputer programming programming_langugages
Computer programming programming_langugages
 
Development of computer languages
Development of computer languagesDevelopment of computer languages
Development of computer languages
 
Computer programming
Computer programmingComputer programming
Computer programming
 
Computer programming language concept
Computer programming language conceptComputer programming language concept
Computer programming language concept
 
Lecture1
Lecture1Lecture1
Lecture1
 
Chapter 4 computer language
Chapter 4 computer languageChapter 4 computer language
Chapter 4 computer language
 
Computer Fundamentals Chapter 12 cl
Computer Fundamentals Chapter 12 clComputer Fundamentals Chapter 12 cl
Computer Fundamentals Chapter 12 cl
 
Lang generations 7557_syed_ghazanfarnaqvi_saturday
Lang generations 7557_syed_ghazanfarnaqvi_saturdayLang generations 7557_syed_ghazanfarnaqvi_saturday
Lang generations 7557_syed_ghazanfarnaqvi_saturday
 
Computer languages
Computer languagesComputer languages
Computer languages
 
Programming languages,compiler,interpreter,softwares
Programming languages,compiler,interpreter,softwaresProgramming languages,compiler,interpreter,softwares
Programming languages,compiler,interpreter,softwares
 
Categories of computers and computer languages ppt
Categories of computers and computer languages pptCategories of computers and computer languages ppt
Categories of computers and computer languages ppt
 
Machine language
Machine languageMachine language
Machine language
 
Basic Meaning of Computer languages
Basic Meaning of Computer languagesBasic Meaning of Computer languages
Basic Meaning of Computer languages
 
Generations Of Programming Languages
Generations Of Programming LanguagesGenerations Of Programming Languages
Generations Of Programming Languages
 
High Level Languages (Imperative, Object Orientated, Declarative)
High Level Languages (Imperative, Object Orientated, Declarative)High Level Languages (Imperative, Object Orientated, Declarative)
High Level Languages (Imperative, Object Orientated, Declarative)
 
High level languages representation
High level languages representationHigh level languages representation
High level languages representation
 

Ähnlich wie Introduction to C Programming

Ähnlich wie Introduction to C Programming (20)

C.pdf
C.pdfC.pdf
C.pdf
 
C session 1.pptx
C session 1.pptxC session 1.pptx
C session 1.pptx
 
Introduction to Compiler design
Introduction to Compiler design Introduction to Compiler design
Introduction to Compiler design
 
Embedded c c++ programming fundamentals master
Embedded c c++ programming fundamentals masterEmbedded c c++ programming fundamentals master
Embedded c c++ programming fundamentals master
 
Programming in c
Programming in cProgramming in c
Programming in c
 
Programming in C
Programming in CProgramming in C
Programming in C
 
Unit 1_Evaluation Criteria_session 3.pptx
Unit 1_Evaluation Criteria_session 3.pptxUnit 1_Evaluation Criteria_session 3.pptx
Unit 1_Evaluation Criteria_session 3.pptx
 
CS3251-_PIC
CS3251-_PICCS3251-_PIC
CS3251-_PIC
 
C programming
C programming C programming
C programming
 
C programming
C programmingC programming
C programming
 
4_5802928814682016556.pptx
4_5802928814682016556.pptx4_5802928814682016556.pptx
4_5802928814682016556.pptx
 
Cd ch1 - introduction
Cd   ch1 - introductionCd   ch1 - introduction
Cd ch1 - introduction
 
CD - CH1 - Introduction to compiler design.pptx
CD - CH1 - Introduction to compiler design.pptxCD - CH1 - Introduction to compiler design.pptx
CD - CH1 - Introduction to compiler design.pptx
 
COM1407: Introduction to C Programming
COM1407: Introduction to C Programming COM1407: Introduction to C Programming
COM1407: Introduction to C Programming
 
week 2 - INTRO TO PROGRAMMING.pptx
week 2 - INTRO TO PROGRAMMING.pptxweek 2 - INTRO TO PROGRAMMING.pptx
week 2 - INTRO TO PROGRAMMING.pptx
 
Compiler Design Basics
Compiler Design BasicsCompiler Design Basics
Compiler Design Basics
 
WEBSITE DEVELOPMENT
WEBSITE DEVELOPMENTWEBSITE DEVELOPMENT
WEBSITE DEVELOPMENT
 
Computer Programming In C.pptx
Computer Programming In C.pptxComputer Programming In C.pptx
Computer Programming In C.pptx
 
Understanding C and its Applications.pdf
Understanding C and its Applications.pdfUnderstanding C and its Applications.pdf
Understanding C and its Applications.pdf
 
.NET Core, ASP.NET Core Course, Session 3
.NET Core, ASP.NET Core Course, Session 3.NET Core, ASP.NET Core Course, Session 3
.NET Core, ASP.NET Core Course, Session 3
 

Mehr von Selvaraj Seerangan

Unit 2,3,4 _ Internet of Things A Hands-On Approach (Arshdeep Bahga, Vijay Ma...
Unit 2,3,4 _ Internet of Things A Hands-On Approach (Arshdeep Bahga, Vijay Ma...Unit 2,3,4 _ Internet of Things A Hands-On Approach (Arshdeep Bahga, Vijay Ma...
Unit 2,3,4 _ Internet of Things A Hands-On Approach (Arshdeep Bahga, Vijay Ma...
Selvaraj Seerangan
 
[PPT] _ Unit 2 _ 9.0 _ Domain Specific IoT _Home Automation.pdf
[PPT] _ Unit 2 _ 9.0 _ Domain Specific IoT _Home Automation.pdf[PPT] _ Unit 2 _ 9.0 _ Domain Specific IoT _Home Automation.pdf
[PPT] _ Unit 2 _ 9.0 _ Domain Specific IoT _Home Automation.pdf
Selvaraj Seerangan
 

Mehr von Selvaraj Seerangan (20)

Unit 2,3,4 _ Internet of Things A Hands-On Approach (Arshdeep Bahga, Vijay Ma...
Unit 2,3,4 _ Internet of Things A Hands-On Approach (Arshdeep Bahga, Vijay Ma...Unit 2,3,4 _ Internet of Things A Hands-On Approach (Arshdeep Bahga, Vijay Ma...
Unit 2,3,4 _ Internet of Things A Hands-On Approach (Arshdeep Bahga, Vijay Ma...
 
Unit 5 _ Fog Computing .pdf
Unit 5 _ Fog Computing .pdfUnit 5 _ Fog Computing .pdf
Unit 5 _ Fog Computing .pdf
 
CAT III Answer Key.pdf
CAT III Answer Key.pdfCAT III Answer Key.pdf
CAT III Answer Key.pdf
 
END SEM _ Design Thinking _ 16 Templates.pptx
END SEM _ Design Thinking _ 16 Templates.pptxEND SEM _ Design Thinking _ 16 Templates.pptx
END SEM _ Design Thinking _ 16 Templates.pptx
 
Design Thinking _ Complete Templates.pptx
Design Thinking _ Complete Templates.pptxDesign Thinking _ Complete Templates.pptx
Design Thinking _ Complete Templates.pptx
 
CAT 3 _ List of Templates.pptx
CAT 3 _ List of Templates.pptxCAT 3 _ List of Templates.pptx
CAT 3 _ List of Templates.pptx
 
[PPT] _ Unit 5 _ Evolve.pptx
[PPT] _ Unit 5 _ Evolve.pptx[PPT] _ Unit 5 _ Evolve.pptx
[PPT] _ Unit 5 _ Evolve.pptx
 
[PPT] _ Unit 4 _ Engage.pptx
[PPT] _ Unit 4 _ Engage.pptx[PPT] _ Unit 4 _ Engage.pptx
[PPT] _ Unit 4 _ Engage.pptx
 
[PPT] _ Unit 3 _ Experiment.pptx
[PPT] _ Unit 3 _ Experiment.pptx[PPT] _ Unit 3 _ Experiment.pptx
[PPT] _ Unit 3 _ Experiment.pptx
 
CAT 2 _ List of Templates.pptx
CAT 2 _ List of Templates.pptxCAT 2 _ List of Templates.pptx
CAT 2 _ List of Templates.pptx
 
Design Thinking - Empathize Phase
Design Thinking - Empathize PhaseDesign Thinking - Empathize Phase
Design Thinking - Empathize Phase
 
CAT-II Answer Key.pdf
CAT-II Answer Key.pdfCAT-II Answer Key.pdf
CAT-II Answer Key.pdf
 
PSP LAB MANUAL.pdf
PSP LAB MANUAL.pdfPSP LAB MANUAL.pdf
PSP LAB MANUAL.pdf
 
18CSL51 - Network Lab Manual.pdf
18CSL51 - Network Lab Manual.pdf18CSL51 - Network Lab Manual.pdf
18CSL51 - Network Lab Manual.pdf
 
DS LAB MANUAL.pdf
DS LAB MANUAL.pdfDS LAB MANUAL.pdf
DS LAB MANUAL.pdf
 
CAT 1 _ List of Templates.pptx
CAT 1 _ List of Templates.pptxCAT 1 _ List of Templates.pptx
CAT 1 _ List of Templates.pptx
 
[PPT] _ UNIT 1 _ COMPLETE.pptx
[PPT] _ UNIT 1 _ COMPLETE.pptx[PPT] _ UNIT 1 _ COMPLETE.pptx
[PPT] _ UNIT 1 _ COMPLETE.pptx
 
CAT-1 Answer Key.doc
CAT-1 Answer Key.docCAT-1 Answer Key.doc
CAT-1 Answer Key.doc
 
Unit 3 Complete.pptx
Unit 3 Complete.pptxUnit 3 Complete.pptx
Unit 3 Complete.pptx
 
[PPT] _ Unit 2 _ 9.0 _ Domain Specific IoT _Home Automation.pdf
[PPT] _ Unit 2 _ 9.0 _ Domain Specific IoT _Home Automation.pdf[PPT] _ Unit 2 _ 9.0 _ Domain Specific IoT _Home Automation.pdf
[PPT] _ Unit 2 _ 9.0 _ Domain Specific IoT _Home Automation.pdf
 

Kürzlich hochgeladen

The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
heathfieldcps1
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
QucHHunhnh
 

Kürzlich hochgeladen (20)

Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 

Introduction to C Programming

  • 1. Introduction to C Programming By Mr.S.Selvaraj Asst. Professor (SRG) / CSE Kongu Engineering College Thanks to and Resource from : Sumitabha Das, “Computer Fundamentals and C Programming”, 1st Edition, McGraw Hill, 2018.
  • 2. 20CST11 – Problem Solving and Programming 2/8/2021 Introduction to C Programming 2 Syllabus
  • 3. Contents 1. Life Cycle of a C Program 2. Features of C 3. Data Variables – Declaring, Assigning and Printing Variables 4. Data Type Classification – Integer, Float, Character and Constants 5. Operators and expressions 6. Control Structures – Decision making and Looping statements 7. Input and output functions 2/8/2021 3 Introduction to C Programming
  • 4. Why to Learn C Program • C programming language is a MUST for students and working professionals to become a great Software Engineer specially when they are working in Software Development Domain. • Some of the key advantages of learning C Programming: – Easy to learn – Structured language – It produces efficient programs – It can handle low-level activities – It can be compiled on a variety of computer platforms 2/8/2021 Introduction to C Programming 4
  • 5. History of Computer Languages • Fortran formerly FORTRAN, derived from ”Formula Translation” is a general- purpose, compiled imperative programming language that is especially suited to numeric computation and scientific computing. Originally developed by IBM in 1957. • ALGOL short for "Algorithmic Language“ is a family of imperative computer programming languages originally developed in 1958. • BASIC (Beginners' All-purpose Symbolic Instruction Code) is a family of general- purpose, high-level programming languages whose design philosophy emphasizes ease of use. The original version was designed by John G. Kemeny and Thomas E. Kurtz and released at Dartmouth College in 1964. • BCPL ("Basic Combined Programming Language") is a procedural, imperative, and structured programming language. BCPL was first implemented by Martin Richards of the University of Cambridge in 1967. • B was derived from BCPL, and its name may be a contraction of BCPL. B is a programming language developed at Bell Labs circa 1969. It is the work of Ken Thompson with Dennis Ritchie. • C is a successor to the programming language B. C is a general-purpose, high-level language that was originally developed by Dennis Ritchie to develop the UNIX operating system at AT & T Bell Labs (Now Lucent). C was originally first implemented on the DEC PDP-11 computer in 1972. • The language was formalized in 1988 by the American National Standard Institute (ANSI). 2/8/2021 5 Introduction to C Programming
  • 6. Computer Language Timeline YEAR LANGUAGE Developed By 1957 FORTRAN John Backus 1958 ALGOL --- 1964 BASIC John G. Kemeny Thomas E. Kurtz 1967 BCPL Martin Richards 1970 Pascal Niklaus Wirth 1968 B Ken Thompson 1972 C Dennis Ritchie 1985 C ++ Bjarne Stroustrup 1988 ANSI C --- 1991 Python Guido van Rossum 1995 Java James Gosling 2000 C # Microsoft 2/8/2021 Introduction to C Programming 6
  • 7. Introduction to C • C is a simple but powerful third-generation language. • The UNIX OS and RDBMS MySQL was totally written in C. • C has replaced BASIC and Pascal for introducing students to the programming world. • It has also influenced the development of object- oriented languages like C++, C# and Java. • C can be considered to be both a high- and low-level language. While it is sufficiently low-level to enable access to specific memory locations, it is also a high- level language with all the standard constructs and operators found in any 3GL language 2/8/2021 7 Introduction to C Programming
  • 8. Introduction to C • Its rich library of functions enables the development of modular applications. • Its support of a variety of constructs for decision making (if and switch) and repetition (while, for and do-while) also makes it suitable for structured programming. • But the language derives its power from the vast arsenal of operators that permit low-level operations like – (i) direct access to memory, and – (ii) manipulation of every bit in memory 2/8/2021 Introduction to C Programming 8
  • 9. Life Cycle of a C Program 2/8/2021 Introduction to C Programming 9
  • 10. Preprocessor and Compiler • a preprocessor is a program that processes its input data to produce output that is used as input to another program. • a compiler is a computer program that translates computer code written in one programming language (the source language) into another language (the target language). • OR • The name "compiler" is primarily used for programs that translate source code from a high-level programming language to a lower level language (e.g., assembly language, object code, or machine code) to create an executable program. 2/8/2021 Introduction to C Programming 10
  • 11. Assembler • An assembler program creates object code by translating combinations of mnemonics and syntax for operations and addressing modes into their numerical equivalents. • OR • An assembler is a program that converts assembly language into machine code. It takes the basic commands and operations from assembly code and converts them into binary code that can be recognized by a specific type of processor. • Assemblers are similar to compilers in that they produce executable code. 2/8/2021 Introduction to C Programming 11
  • 12. Linker • a linker or link editor is a computer system program that takes one or more object files (generated by a compiler or an assembler) and combines them into a single executable file, library file, or another "object" file. 2/8/2021 Introduction to C Programming 12
  • 13. Loader • In computer systems a loader is the part of an operating system that is responsible for loading programs and libraries. It is one of the essential stages in the process of starting a program, as it places programs (executable code) into memory and prepares them for execution. • Once loading is complete, the operating system starts the program by passing control to the loaded program code. • The following are the responsibilities of a loader: – Validate the program for memory requirements, permissions, etc. – Copy necessary files, such as the program image or required libraries, from the disk into the memory – Copy required command-line arguments into the stack – Link the starting point of the program and link any other required library – Initialize the registers – Jump to the program starting point in memory 2/8/2021 Introduction to C Programming 13
  • 14. Interpreter • In computer science, an interpreter is a computer program that directly executes instructions written in a programming or scripting language, without requiring them previously to have been compiled into a machine language program. • Example : BASIC, Java, Python, Perl, MATLAB, Ruby, Lisp • An interpreter generally uses one of the following strategies for program execution: – Parse the source code and perform its behavior directly; – Translate source code into some efficient intermediate representation and immediately execute this; – Explicitly execute stored precompiled code made by a compiler which is part of the interpreter system. 2/8/2021 Introduction to C Programming 14
  • 15. Key Difference B/w Compiler and Interpreter • Compiler transforms code written in a high-level programming language into the machine code, at once, before program runs, whereas an Interpreter coverts each high-level program statement, one by one, into the machine code, during program run. • Compiled code runs faster while interpreted code runs slower. • Compiler displays all errors after compilation, on the other hand, the Interpreter displays errors of each line one by one. • Compiler is based on translation linking-loading model, whereas Interpreter is based on Interpretation Method. • Compiler takes an entire program whereas the Interpreter takes a single line of code. 2/8/2021 Introduction to C Programming 15
  • 16. Features of C Programming Language • Procedural Language • Fast and Efficient • Modularity • Statically Type • General Purpose Language • Rich set of built in Operators • Libraries with rich Functions • Middle Level Language • Portability • Easy to Extend 2/8/2021 Introduction to C Programming 16
  • 17. Applications of C Programming • C was initially used for system development work, particularly the programs that make-up the operating system. • C was adopted as a system development language because it produces code that runs nearly as fast as the code written in assembly language. • Some examples of the use of C are - – Operating Systems – Language Compilers – Assemblers – Text Editors – Print Spoolers – Network Drivers – Modern Programs – Databases – Language Interpreters – Utilities 2/8/2021 Introduction to C Programming 17
  • 18. Thank you 2/8/2021 Introduction to C Programming 18
  • 19. Data Variables By Mr.S.Selvaraj Asst. Professor (SRG) / CSE Kongu Engineering College
  • 20. Contents 1. Life Cycle of a C Program 2. Features of C 3. Data Variables – Declaring, Assigning and Printing Variables 4. Data Type Classification – Integer, Float, Character and Constants 5. Operators and expressions 6. Control Structures – Decision making and Looping statements 7. Input and output functions 2/8/2021 20 Data Variables
  • 21. Program Data • A program must know the address in memory of every piece of data that it handles. • When a program encounters the variable x, it can evaluate this variable only if it knows the memory location of x. • As a programmer, you need not know the address of this location or the register where it is moved to because the compiler provides this information in the executable. • Keep in mind that you are learning to use C and not assembly language. 2/8/2021 Data Variables 21
  • 22. Variables • Program data occur in the form of variables and constants. • A variable has a name that is assigned a value. • This value is stored in memory and can change while the program is running. • For example, area, your_number and counter. • The name used to access a variable is also known as an identifier. • Example: – int counter; – The compiler identifies the type as int, i.e. integer, and allocates at least 2 bytes of memory for the variable named counter. 2/8/2021 22 Data Variables
  • 23. Constants • Constants represent data that don’t change. • For example, – In the expression (fahrenheit - 32) / 9.0, both 32 and 9.0 are constants. – In printf(“Printing ASCII List”); The first argument used with printf is often a string constant, say, “Printing ASCII list”. 2/8/2021 Data Variables 23
  • 24. Naming the variables • The rules for framing variable names apply to all identifiers, which include arrays and functions. • A variable name can begin with a letter or the underscore (_) character, but the remaining part of the name can comprise only the following characters: – Letters (both lower- and uppercase) – Digits – The underscore (_) character. Note that this is different from the hyphen (-) which is available on the same key as the _ on your PC or laptop. • A variable name thus cannot begin with a digit. • The names rate1 and _rate1 are valid but not 1rate. • Variable names are also case-sensitive; rate1 and RATE1 are two separate variables. • Here are some examples of valid identifier names: 2/8/2021 Data Variables 24
  • 25. Naming the variables • Under C89 (the first C standard from ANSI), the first 31 characters of an identifier are significant. The remaining characters are ignored by the compiler. • Use meaningful lowercase names for variables. Names like x and abc are valid, but they don’t intuitively reveal what they represent—unlike variables like sampling_speed and conversion_rate • The following keywords used in C cannot be used as variable names: 2/8/2021 Data Variables 25
  • 26. Declaring Variables • A variable must be declared before use. • In most cases, the declaration is made at the beginning of the program (mostly after main, but sometimes before main for global variables). • The following statement declares a variable named bits_per_sec: • the compiler allocates at least two bytes in memory for bits_per_sec. • It also notes the starting address of that memory location so it knows where to look up when encountering expressions that use the variable. 2/8/2021 Data Variables 26
  • 27. Declaring Variables • Using the comma as delimiter, multiple declarations can be made in a single statement provided the type is the same: 2/8/2021 Data Variables 27
  • 28. Assigning Variables • The previous declarations did not assign initial values to the variables. • To initialize a variable, use the = operator. • One way is to separate the declaration from the assignment: 2/8/2021 Data Variables 28
  • 32. Thank you 2/8/2021 Data Variables 32
  • 33. Data Types Classification By Mr.S.Selvaraj Asst. Professor (SRG) / CSE Kongu Engineering College
  • 34. Contents 1. Life Cycle of a C Program 2. Features of C 3. Data Variables – Declaring, Assigning and Printing Variables 4. Data Type Classification – Integer, Float, Character and Constants 5. Operators and expressions 6. Control Structures – Decision making and Looping statements 7. Input and output functions 2/8/2021 34 Data Types Classification
  • 35. Data Type Classification • Data types are broadly categorized as follows: – Fundamental (like int, float, etc.) – Derived (like arrays and pointers) – User-defined (structures, the typedef and enumerated types) • C language doesn’t have a separate type for strings. 2/8/2021 Data Types Classification 35
  • 36. Fundamental Data Type 2/8/2021 Data Types Classification 36 • The fundamental types can be further divided into the following three subtypes: – Integer (the keywords short, int, long and long long) – Floating point (the keywords float, double and long double) – Character (the keyword char)
  • 37. sizeof Operator • The sizeof operator evaluates the size of all data types—the fundamental types, pointers, arrays and constants. • This is how you can find the size of the int data type on your computer: – printf(“Size of int: %dn”, sizeof(int)); • This should print 2/4 on your PC. • Note that sizeof is not a function even though it looks like one. • It is an operator (like = and +) which works on an operand, which here is enclosed within parentheses in function-like manner. • There are no fixed sizes for the fundamental data types, but only ANSI-specified minimum sizes. • Unlike other operators that evaluate their operands during runtime, sizeof is a compile-time operator. The result of its operation is known to the compiler at the time of compilation, which implies that the value is built into the executable. 2/8/2021 Data Types Classification 37
  • 38. 2/8/2021 Data Types Classification 38
  • 39. Integer Types • An integer is a contiguous collection of digits without a decimal point but it may contain the - prefix. For instance, 65536 and -7 are integers. • The - in -7 is an operator; it multiplies 7 by -1. • C uses the int keyword to declare an integer variable. • Using the short and long qualifiers in addition. • C offers a total of four types of integers, whose abbreviated and expanded keywords are shown in the following list: – int – short or short int (short is a qualifier to int) – long or long int (long is a qualifier to int) – long long or long long int (long long is a qualifier to int) 2/8/2021 Data Types Classification 39
  • 40. Integer Types • A minimum size for the types: – short — 2 bytes (16 bits) – int — 2 bytes (16 bits) Modern int is 4 bytes – long — 4 bytes (32 bits) – long long — 8 bytes (64 bits) • A relationship between the types that can be represented in this form: – char <= short <= int <= long <= long long 2/8/2021 40 Data Types Classification
  • 41. Signed and Unsigned Integers • By default, the four int types are signed, which means that they can handle both positive and negative integers. • This default behavior can be overridden by using the unsigned qualifier before the keyword. • For instance, the statement unsigned int count; • allows count to store only positive integers. • The basic format specifier for the signed integer data type is %d. • A modifier is needed for short (h), long (l) and long long (ll). • For unsigned types, replace %d with %u with the same modifiers as considered necessary 2/8/2021 Data Types Classification 41
  • 42. Power of 10 2/8/2021 Data Types Classification 42
  • 43. 2/8/2021 Data Types Classification 43
  • 44. 2/8/2021 Data Types Classification 44
  • 45. Specific Integer Types • The short Type – Abbreviated from short int, the minimum and typical size for this type is 2 bytes. – For the range it offers (-32,768 to 32,767), short is suitable for positive integral entities like age, marks and family size. – If you need an integer greater than 32,767 but less than 65,535, use unsigned short. • The int Type – This is the standard integer type that reflects the word size of your machine. – Like short, its minimum size is 2 bytes, but since most computers today are 32-bit machines, int is also 32 bits (4 bytes). – A signed int can handle numbers up to 2 billion (on both +ve and -ve sides), while the unsigned type can hold a number up to 4 billion. – The popular and often misused %d format specifier actually applies to int. 2/8/2021 Data Types Classification 45
  • 46. Specific Integer Types • The long Type – The long type (abbreviated from long int) is meant to hold numbers larger than int. – However, that has not always been the case on 32-bit systems. – In most cases, int and long are the same size—4 bytes, but on some systems you could see a long of 8 bytes. – Also, most 64-bit programming models use 8-byte long integers. An 8-byte long integer can handle values in the quintillion range. • The long long Type – This type was added by C99 to the language to accommodate 64-bit integers. – On most systems that support this type, long long is 8 bytes. – Since long in most 64-bit models is already set to 8 bytes, it’s a little too early to say what the eventual size of long long would be. 2/8/2021 Data Types Classification 46
  • 47. Octal and Hexadecimal Integers • Apart from decimal integers (base-10), C also supports octal (base- 8) and hexadecimal (base-16) numbers. • C identifies them by a special prefix. • Octal: – When a 0 (zero) prefixes a number comprising the digits 0 to 7, C interprets the number as octal. Thus, 072 is an octal integer having the value (58)10 – (7 × 81 + 2 × 80 = 58). – The printf/scanf duo uses %o to handle octal integers. • Hexadecimal: – When a number comprising the digits 0 to 9 and A to F is preceded by 0x or 0X, C interprets the number as hexadecimal. Thus, C understands 0x72 as a base-16 number having the value (114)10 – (7 × 161 + 2 × 160). – Use the %x or %X format specifier to handle hex integers. • Systems programmers need to be familiar with these numbering systems because many programs output numbers in these forms. 2/8/2021 Data Types Classification 47
  • 48. 2/8/2021 Data Types Classification 48
  • 49. Floating Point Types • A floating point number is a number with a decimal point, which divides it into integral and fractional components. • The Fortran and Pascal languages as well as the scientific community understand it as a real number. • A floating point number is suitable for representing prices, averages and ratios. It is also used for storing very large and small numbers like the number of stars in the universe or the percentage of argon in the atmosphere. • There are two ways of representing floating point numbers. • The first way is the one we commonly use—a number with a decimal point. Also, as the last two items of the following examples show, you may omit digits before or after the decimal point: 44.1 -0.3048 .00075 7. 7. is different from 7 2/8/2021 Data Types Classification 49
  • 50. Floating Point Types • The second way is to use the exponential or scientific notation. • This notation uses two components— mantissa and exponent— separated by the letter E or e. • It is expressed in this general form: mantissa E exponent Can use e instead of E • The mantissa, which is an integer or real number, is multiplied by 10 with the exponent as its power. • For instance, 44.1 is equivalent to 4.41X101, so it is expressed as 4.41E1 using exponential notation. Here, 4.41 is the mantissa and 1 is the exponent. • The exponent signifies the number of places the decimal point needs to shift to the right to convert a number to the conventional form. • The point floats (hence, the term floating point number) and the exponent controls this float. • If you increase the value of the exponent, the point has to move to the left to keep the number unchanged. So, 44.1 can be expressed as 4.41E1, 0.441E2 and 0.0441E3, as well as 441E-1. 2/8/2021 Data Types Classification 50
  • 51. Floating Point Types • Consider some more examples: • A floating point number has a precision, which signifies the number of significant digits used in its representation. • For instance, the value of PI is 3.142 when expressed with 4-digit precision, and 3.142857 when 7-digit precision is used. 2/8/2021 Data Types Classification 51
  • 52. Floating Point Types 2/8/2021 Data Types Classification 52
  • 53. Floating Point Types • While integers are classified by their size, floating point numbers are classified by their precision. • C supports three types of floating point numbers whose keywords are noted below: – float (single precision) – double (double precision) – long double (quad precision) • Unlike with integers, ANSI specifies a single minimum range for all of them. • This range for a positive number is 10-38 to 10+38, but it must also satisfy the following condition: • range of float <= range of double <= range of long double 2/8/2021 Data Types Classification 53
  • 54. Floating Point Types • The float Type – ANSI requires a float to represent at least 6 significant digits within its minimum range of 10-38 to 10+38. – This means that it must be able to handle at least the first 6 digits in a number like 77.789654. • The double Type – For this type, ANSI specifies a greater precision—at least 10 digits. – The double type usually allows a very high range of values—10-308 to 10+308. • The long double Type – ANSI provides this type with the same precision as double. – For systems that support this type, long double uses 8 to 16 bytes. • Floating point computing is slower than integer computing. • The double and long double types may take up a lot of memory on your system, so don’t use them unless you need a range and precision greater than what is offered by float. 2/8/2021 Data Types Classification 54
  • 55. Floating Point Types 2/8/2021 Data Types Classification 55
  • 56. 2/8/2021 Data Types Classification 56
  • 57. Character Type (char) • C supports the char data type which is just wide enough to hold the values of the computer’s character set. • It use the 8-bit ASCII character set, so char by definition is one byte wide. • Even though char is essentially an integer type, we are discussing it separately for two reasons: – The numeric value stored in a char variable can easily be displayed in its equivalent character form and vice versa. – Strings owe their origin to char. A string is simply an array of type char. 2/8/2021 Data Types Classification 57
  • 58. Char Data Type • The first point implies that the value 65 stored as a char can be printed as A by printf using %c. • Conversely, the character A input from the keyboard can be saved in a char variable as 65 by scanf using %c. • Data of type char can also be represented in two other ways: – By a character enclosed within single quotes (e.g. ‘A’). – By a special escape sequence like ‘c’, but only a handful of non- printable characters can be represented by an escape sequence. • Like the other integer types, char occurs in signed and unsigned forms. • The signed form can hold values between -128 to 127, while the range for the unsigned type is 0 to 255. 2/8/2021 Data Types Classification 58
  • 59. char as Integer and Character • If char is unsigned, then every character of the 8-bit ASCII set can be assigned to a char variable. • The following examples demonstrate that any integer type can be used to display a character with %c. • The last statement should sound a beep as the BEEP character ([Control-g]) has the ASCII value 7. 2/8/2021 Data Types Classification 59
  • 60. char as Integer and Character • Beginners often make the mistake of using double quotes (“A” instead of ‘A’). • Double-quoted characters (like “A” or “Internet of things”) represent a string, which is not a fundamental data type. • C understands a string as an array (a derived data type) of type char, but more of that later. • In C, ‘A’ is different from “A”. The former is a character and the latter is a string. 2/8/2021 Data Types Classification 60
  • 61. Computation with char • Since any single-quoted character actually represents an integer, it can be used in arithmetic operations. • The following assignments are all valid, but the third one has a message to convey: • Should we use ‘A’ or 65, its ASCII value? The question is significant because on EBCDIC systems (designed by IBM), ‘A’ evaluates to 193 and not 65. 2/8/2021 Data Types Classification 61
  • 62. ASCII Table 2/8/2021 Data Types Classification 62
  • 63. EBCDIC Table 2/8/2021 Data Types Classification 63
  • 64. 2/8/2021 Data Types Classification 64
  • 65. char as Escape Sequence • C supports the escape sequence as a synonym for a non-printable character. • An escape sequence is a two-character combination comprising a (backslash) and a lowercase letter. • The forces the character following it to be treated specially. • we observe that t (the tab) expands to eight spaces on your terminal. • The newline (n) is universally used in printf to advance the cursor to the next line. • The f initiates a page break. 2/8/2021 Data Types Classification 65
  • 66. List of Escape Sequence in C 2/8/2021 Data Types Classification 66
  • 67. 2/8/2021 Data Types Classification 67
  • 68. Data Type of Constants • Constants represent data that don’t change in the program. • C supports a wide range of constants—both unnamed and named— which may be grouped into the following categories: – Unnamed constants belonging to the fundamental data types. The constants 12, -34.5 and ‘A’ belong to this category. – Named or symbolic constants that are defined with #define at the beginning of the program. – Variables that behave like constants when the const qualifier is added to the variable declaration. – String constants like “Nougat is here” belong to the derived data type. • C specifies a default type for a constant, but this default is often changed by the compiler or the programmer. This can happen for the following reasons: – The size of the constant is too large to be accommodated in the default type. – For instance, the number 5000000000 is too large for an int, the default type for integer constants. 2/8/2021 Data Types Classification 68
  • 69. Integer Constants • C specifies int (signed) as the default type for an integer constant. • The compiler treats 655 as an int even though the number easily fits in a short. • If a constant doesn’t fit in its default type, the compiler tries the next higher type using the following sequence: 2/8/2021 Data Types Classification 69
  • 70. Integer Constants • C offers special symbols that can be suffixed to these constants: • For instance, the compiler, which otherwise sees 3 as an int, treats 3L as a long. • There are no constants of type short. • Next time you see the constants 540U or 450L, remember to treat them as unsigned int and signed long, respectively 2/8/2021 Data Types Classification 70
  • 71. Floating Point Constants • Floating Point Constants C treats a real constant as a double which takes up 8 bytes on most systems. • Constants like 3.142 and 1789.456 have the type double even though a float (4 bytes) is wide enough for them. 2/8/2021 Data Types Classification 71
  • 72. Character Constant • Character Constants Any character or escape sequence enclosed in single quotes represents a character constant. • The characters ‘A’, ‘t’ and ‘7’ are character constants having the ASCII values 65, 11 and 7, respectively. • Strangely enough, C treats character constants as type int rather than char. • This means the constant ‘A’ is stored in a space of 4 bytes (size of int). 2/8/2021 Data Types Classification 72
  • 73. Summary of Constants • The default type for an integer constant is int. • For a real number, the default is double. • A character constant is stored as an int. • C doesn’t support a constant of type short. 2/8/2021 Data Types Classification 73
  • 74. Variables as Constants: The const Qualifier • A constant that is used multiple times in a program is often stored as a variable. • If the value is changed later, then the code needs to be modified at a single location, thus making maintenance easier. • The constant itself should be stored as a variable using the const qualifier: 2/8/2021 Data Types Classification 74
  • 75. 2/8/2021 Data Types Classification 75
  • 76. 2/8/2021 Data Types Classification 76
  • 77. Arrays and Strings • we may need to store the monthly rainfall for an entire year. Rather than create 12 variables, we use an array to store the 12 values. • An array is a collection of data items belonging to a single type. • The following statement declares an array having the name month. It is capable of holding 12 values, each of type int: 2/8/2021 Data Types Classification 77
  • 78. Arrays • Assuming a 4-byte int, the compiler uses this declaration or definition to allocate a contiguous chunk of 48 bytes of memory. • Each element of the array is accessed by the notation month[n], where n is an integer representing the index. • The value of n here lies between 0 and 11. • The first element is accessed as month[0] and the last element is month[11]. • You can perform the initialization at the time of declaration by assigning a set of comma-delimited values enclosed by curly braces 2/8/2021 Data Types Classification 78
  • 79. 2/8/2021 Data Types Classification 79
  • 80. Thank you 2/8/2021 Data Types Classification 80
  • 81. Operators and Expressions By Mr.S.Selvaraj Asst. Professor (SRG) / CSE Kongu Engineering College
  • 82. Contents 1. Life Cycle of a C Program 2. Features of C 3. Data Variables – Declaring, Assigning and Printing Variables 4. Data Type Classification – Integer, Float, Character and Constants 5. Operators and expressions 6. Control Structures – Decision making and Looping statements 7. Input and output functions 2/8/2021 82 Operators and Expressions
  • 83. Expressions • Variables and constants represent data in their most elemental form. • These data objects become useful when combined with one another to form expressions. • The components of an expression are linked to one another by symbols called operators. • For instance, a + b / 7 is an expression where + and / are operators. • The expression has a value which here is evaluated arithmetically 2/8/2021 Operators and Expressions 83
  • 84. Operators • Operators form the connecting link between variables and constants in expressions. • An operator acts on one or more operands. • For instance, in the expression x - 5, the - symbol is an operator, which acts on the operands x and 5. • C supports a rich collection of operators—richer than any language known previously. • These operators can be grouped into the following types: 2/8/2021 Operators and Expressions 84
  • 85. Operators • An operator may be unary, binary or ternary. • A unary operator has one operand. – For instance, the - symbol in the negative constant -5 is a unary operator which multiplies its operand by -1. – The unary - is different from the binary - which performs subtraction. – The ++ in count++ is a unary operator which increments its operand by one. • Most operators are of the binary type which needs two operands. – The assignment operator = in x = 5 is a binary operator. – Arithmetic operators like * and / and relational operators like > and < are also binary operators. • C has one ternary operator which uses the ? and : symbols. 2/8/2021 Operators and Expressions 85
  • 86. Operators • When an expression contains multiple operators, the order of their evaluation becomes important. • For instance, when evaluating the expression x + y * z, does multiplication occur before addition? • For this purpose, C specifies two attributes for each operator: – The precedence (priority) ensures that a high-priority operator is acted upon before a low-priority one. In the expression x + y * z, the * has a higher precedence than +, so multiplication will be done first. – The associativity determines the direction of evaluation (left-to-right or right-to-left). In the expression x * y / z, it is associativity and not precedence that determines that multiplication will be done first. 2/8/2021 Operators and Expressions 86
  • 87. 2/8/2021 Operators and Expressions 87
  • 88. 2/8/2021 Operators and Expressions 88
  • 90. / and% Operators • Integer division (/) operator leads to truncation of the decimal portion. i.e., only Quotient Portion is taken. • The Modulus Operator (%) evaluates the remainder of a division between two integers. The expression 10 % 7 (10 modulo 7) evaluates to 3. 2/8/2021 Operators and Expressions 90
  • 91. 2/8/2021 Operators and Expressions 91
  • 92. Automatic or Implicit Type Conversion • When numbers of different data types are used in an expression, the compiler converts a lower type to a higher type using the concept of implicit promotion. • C finally converts the type of the expression itself to the highest type it finds there. • Consider this simple expression that involves an assignment: float pi = 22 / 7.0; • Here, the variables and constants have three different data types. • Recall that 7.0 has the type double and 22 is of type int. • C treats a real constant as a double which takes up 8 bytes on most systems. Constants like 3.142 and 1789.456 have the type double even though a float (4 bytes) is wide enough for them. – It looks at the operands of the / operator and finds 7.0 to have a higher type than 22. It converts 22 to double as well, so the resultant expression also has the type double. This means that sizeof(22 / 7.0) = sizeof(double). – It then looks at the operand on the left of the =. This is a variable of type float, which has a lower type than double. But since C can’t change the type of a variable that has been declared with a specific type, it demotes the type of the entire expression on the right to fl oat. 2/8/2021 Operators and Expressions 92
  • 93. 2/8/2021 Operators and Expressions 93
  • 94. Explicit Type Conversion—the Type Cast • The technique of using the F, L and LL suffixes to change the data type of constants. This technique doesn’t apply to variables. • The ultimate conversion tool for explicit conversion or coercion is the type cast or cast. • A cast is a unary operator having two components: the name of the data type (int, fl oat, etc.) enclosed in parentheses, followed by the data item that needs conversion. • The data item can be any variable, constant or expression of any type. • For instance, (float) represents a cast, and (float)x evaluates x as a float even though x may actually be of type int. 2/8/2021 Operators and Expressions 94
  • 96. Order of Evaluation • You probably remember the “BODMAS” acronym from your school days, which specified that division is performed before addition (D before A in BODMAS). • C too has a set of rules for all the 40 operators of the language. • These rules, which we’ll now discuss, are based on two operator attributes: precedence and associativity. 2/8/2021 Operators and Expressions 96
  • 97. Operator Precedence • Every operator has a precedence which signifies the priority of its operation. • An operator belonging to a higher level has a greater precedence or priority than a lower-level operator. 2/8/2021 Operators and Expressions 97
  • 99. Operator Associativity • Every operator has an associativity which determines the direction of evaluation when an operand is shared by two operators having the same precedence. • This attribute can take on two values— right- to-left (R-L) or left-to-right (L-R). 2/8/2021 Operators and Expressions 99
  • 100. 2/8/2021 Operators and Expressions 100
  • 102. ++ and -- Operator • A programmer frequently needs to increment or decrement a variable by one—especially inside a loop. • C provides shortcuts for performing these two operations: the unary ++ and -- operators. 2/8/2021 Operators and Expressions 102
  • 103. 2/8/2021 Operators and Expressions 103
  • 104. ++ and -- operator as prefix and postfix • If you use the ++ operator as prefix like: ++var. The value of var is incremented by 1 then, it returns the value. • If you use the ++ operator as postfix like: var++. The original value of var is returned first then, var is incremented by 1. • The -- operator works in a similar way like the ++ operator except it decreases the value by 1. 2/8/2021 Operators and Expressions 104
  • 105. Example 1 2/8/2021 Operators and Expressions 105
  • 106. Relational operators and expressions 2/8/2021 Operators and Expressions 106
  • 107. Logical Operators 2/8/2021 Operators and Expressions 107
  • 108. Conditional Operators • C supports the only ternary operator—the conditional operator—which uses the symbols ? and : • These two symbols are used with three expressions to implement a rudimentary form of decision making. • The operator uses the following formal syntax: 2/8/2021 Operators and Expressions 108
  • 109. Example • exp1, exp2 and exp3 represent three expressions, – where exp1 is generally a relational one. – The composite expression evaluates to exp2 if exp1 evaluates to true, or exp3 otherwise. – Here’s how you can use this operator to make a simple decision. • If total is greater than zero, then 0.95 is assigned to rate, otherwise 0.90 is assigned. Nothing could be simpler than that! 2/8/2021 Operators and Expressions 109
  • 110. Thank you 2/8/2021 Operators and Expressions 110
  • 111. Control Structures By Mr.S.Selvaraj Asst. Professor (SRG) / CSE Kongu Engineering College
  • 112. Contents 1. Life Cycle of a C Program 2. Features of C 3. Data Variables – Declaring, Assigning and Printing Variables 4. Data Type Classification – Integer, Float, Character and Constants 5. Operators and expressions 6. Control Structures – Decision making and Looping statements 7. Input and output functions 2/8/2021 112 Control Structures
  • 113. Control Structures : Decision Making • Control expression for making decisions. • Use of the if-else construct for two-way decision making. • Nesting of if-else constructs for multi-way decision making. • Switch construct for testing equality. • goto statement. 2/8/2021 Control Structures 113
  • 114. Decision Making in C • C addresses selection issues with the following three constructs: – The if statement supported by the optional else keyword. – The switch statement. – The conditional operator. 2/8/2021 Control Structures 114
  • 115. Control Expression • Some C constructs like the if-else and while statements use the true or false value of a control expression to determine control flow. • They require this expression to be enclosed by parentheses. • The control expression is normally a relational or logical expression as shown by the • following examples: 2/8/2021 Control Structures 115
  • 116. Control Expression • But a control expression can also be any expression that returns any value including 0. • Also, because any non-zero value is true in C. • The following expressions are also valid even if they are neither relational nor logical: 2/8/2021 Control Structures 116
  • 118. Compound Statement or Block • When using constructs like if and while, you’ll need to address a group of statements as a single unit. • This unit, which is flanked on either side by a matched pair of curly braces, is called a compound statement. • It is also known as a control block, or, simply, block. • It could be helpful to keep in mind that a block changes the scope (i.e. visibility) of a variable declared inside it. • Such a variable is not visible outside the block or in other blocks. 2/8/2021 Control Structures 118
  • 119. THE if STATEMENT • The if statement is the most commonly used selection construct in any programming language. • It has basically two forms—with and without the else keyword. 2/8/2021 Control Structures 119
  • 120. THE if STATEMENT • Execution of this statement begins by evaluating expression. • If this value is true, then one or more statements are executed. • Curly braces are not required for a single statement but they are needed for a compound statement. • Here’s a simple example 2/8/2021 Control Structures 120
  • 121. if-else: TWO-WAY BRANCHING 2/8/2021 Control Structures 121
  • 122. Example • Consider a store that offers a weekend discount of 10% for purchases over Rs 1000, and 5% otherwise. • The code that computes the amount payable can be represented in this manner. 2/8/2021 Control Structures 122
  • 125. MULTI-WAY BRANCHING WITH if-else-if ... 2/8/2021 Control Structures 125
  • 126. Example • Let’s now use this construct to compute the tariff for the 4G Internet service offered by a mobile operator. • The tariff is Rs 255 for up to 1 GB, • Rs 455 for up to 2 GB, • Rs 755 for up to 4 GB and • Rs 995 there after (simplified from live data). • This logic is easily implemented using the if-else-if form: 2/8/2021 Control Structures 126
  • 129. MULTI-WAY BRANCHING WITH NESTED if (if-if-else) 2/8/2021 Control Structures 129
  • 131. THE CONDITIONAL EXPRESSION (?:) • The conditional expression is construct uses two symbols (? and :) as a ternary operator. • The operator acts on three expressions using the following formal and functional syntaxes: 2/8/2021 Control Structures 131
  • 133. THE switch STATEMENT • We use the equality test so often that C has a special construct to handle it. • It’s the switch statement which implements multi-way branching with a compact and structured construct. • If you need to match 10 integer values for making 10 different decisions, use switch whose syntax is shown in next slide. 2/8/2021 Control Structures 133
  • 135. • switch first evaluates exp which must be an integer or character variable or constant. • It next tries to match exp with value1. If the match succeeds, switch executes one or more statements represented by statements1. • If the match fails, switch attempts to match exp with value2 and so on until control moves to the keyword default (if present). • This option is thus invoked when all previous matching operations fail. • For this purpose, switch is assisted by three keywords—case, break and default. • The entire set of options and their associated action are enclosed in curly braces. 2/8/2021 Control Structures 135
  • 137. goto STATEMENT • C also supports a goto statement that lets control branch to a different point in the program without returning to the point in the program from where it was executed. • It may be used only in rare situations. 2/8/2021 Control Structures 137
  • 139. Control Structures—Loops • In addition to decision making, a language must be able to repeatedly execute a set of statements. • Constructs that do that are known as loops, and C offers three of them—while, do-while and for. 2/8/2021 Control Structures 139
  • 141. Looping Concepts • Even though all of the three loops offered by C broadly conform to the above scheme, there are minor differences between them. • First, the initialization may be done in the loop construct itself (for loop) instead of being done outside. • Second, the control expression may be evaluated at the end (do- while loop) instead of at the beginning. • Finally, a control expression can’t prevent a do-while loop from performing at least one iteration even though it can prevent the other loops from running at all. • A loop iteration can either be suspended (to start a new one) or terminated altogether without re-testing the control expression. This is achieved with the continue and break keywords that can be invoked anywhere in the loop body. • A loop is generally designed to execute a finite number of times, but many applications need a loop to run all the time. Such loops are known as infinite loops. For example (while (1)). 2/8/2021 Control Structures 141
  • 142. THE while LOOP 2/8/2021 Control Structures 142
  • 143. THE while LOOP • The while loop is an entry-controlled loop, which means that loop entry is not guaranteed. • If the control expression is false to begin with, then the loop is not entered at all. • This is also true of the for loop, but not the do- while loop which is an exit-controlled loop. • The control expression in a do-while loop is tested at the end of the loop, which means that initial loop entry is guaranteed but not its subsequent iterations. 2/8/2021 Control Structures 143
  • 145. Some other examples 2/8/2021 Control Structures 145
  • 146. Updating the Key Variable in the Control Expression 2/8/2021 Control Structures 146
  • 147. Practice Programs • Determining the Factorial of a Number. • Program to Reverse Digits of an Integer. • Printing and Summing the Fibonacci Numbers. 2/8/2021 Control Structures 147
  • 148. NESTED while LOOPS 2/8/2021 Control Structures 148
  • 150. Printing a Half-Pyramid with Digits 2/8/2021 Control Structures 150
  • 153. USING while WITH break AND continue 2/8/2021 Control Structures 153
  • 154. break AND continue • When the program sees break, control breaks out of the loop to resume execution from the statement immediately below the end of the loop. • On the other hand, continue doesn’t terminate a loop but suspends loop execution to resume the next iteration. 2/8/2021 Control Structures 154
  • 155. THE do-while LOOP 2/8/2021 Control Structures 155
  • 156. THE do-while LOOP • A do-while loop is an exit-controlled loop and not an entry-controlled one. • C supports a do-while loop which functionally differs from while in only one respect: the control expression is tested at the end of the loop. • This means that a do-while loop is guaranteed to perform at least one iteration. • The loop begins with the do keyword and ends with the ; in the last line which contains the while keyword. • This is in contrast to the while loop which terminates at the ; of its only or last statement. 2/8/2021 Control Structures 156
  • 158. Practice Program • convert a decimal number to binary but without reversing the bits. 2/8/2021 Control Structures 158
  • 161. THE for LOOP • Like while and do-while, the for loop also uses the key variable/control expression paradigm to determine loop entry and continuity. • It is a compact construct that gathers three expressions at one place. • Any while loop can be replaced with a for loop. 2/8/2021 Control Structures 161
  • 162. THE for LOOP 2/8/2021 Control Structures 162
  • 163. THE for LOOP • The while loop works on the principle of – initializing a key variable before the loop, – testing it in the control expression and – updating the key variable in the body. • The three expressions in for do the same work but at one place. – The initialization is done by exp1, – the key variable check is done by exp2, and – updating of the key variable is done by exp3. • These expressions, which are delimited by semicolons, determine whether a loop will run, and if so, how many times. • Like while, for is an entry-controlled loop because exp1 and exp2 jointly determine whether the loop will be entered at all. 2/8/2021 Control Structures 163
  • 166. Moving All Initialization to exp1 2/8/2021 Control Structures 166
  • 167. Moving Expression Statements in Body to exp3 2/8/2021 Control Structures 167
  • 168. The Infinite Loop • Depending on the nature of the problem, any of the three expressions can be dropped. • As a special case, all of them can be dropped to create an infinite loop. 2/8/2021 Control Structures 168
  • 169. CONVERTING A DECIMAL NUMBER TO BINARY 2/8/2021 Control Structures 169
  • 171. NESTED for LOOPS • One for loop can enclose any number of inner for loops. • For reasons of compactness, nested for loops are often preferred to nested while loops. • Nested for loops are the perfect tool to use for printing patterns. 2/8/2021 Control Structures 171
  • 173. 2/8/2021 Control Structures 173 • The expression i <= rows controls the number of rows • The expression j <= rows - 1 controls the number of spaces, and • the expression k != 2 * i – 1 controls the number of asterisks.
  • 174. Thank you 2/8/2021 Control Structures 174
  • 175. I/O Functions By Mr.S.Selvaraj Asst. Professor (SRG) / CSE Kongu Engineering College
  • 176. Contents 1. Life Cycle of a C Program 2. Features of C 3. Data Variables – Declaring, Assigning and Printing Variables 4. Data Type Classification – Integer, Float, Character and Constants 5. Operators and expressions 6. Control Structures – Decision making and Looping statements 7. Input and output functions 2/8/2021 176 IO Functions
  • 177. Introduction • C supports no keywords for taking input from the keyboard or for displaying output on the terminal. • Functions that carry out input/output operations consider data as a stream of characters irrespective of the data type they actually represent. 2/8/2021 IO Functions 177
  • 178. Introduction • Most I/O functions have to contend with two issues— – EOF and – buffering of data. • Input functions often need to check for an end-of-file (EOF) condition. • The term “file” is misleading because EOF actually indicates the end of data. • There’s no character named EOF in the ASCII character set. • For keyboard input, – UNIX/Linux systems use [Ctrl-d] and – MSDOS/Windows systems use [Ctrl-z] to indicate EOF to a program. 2/8/2021 IO Functions 178
  • 179. First Issue - EOF • EOF is represented as a symbolic constant defined in stdio.h. • Since any value between 0 and 255 is a valid return value for getchar and scanf. • ANSI requires EOF to have a value that is outside the range of the character set of the machine. • Typically, it is -1 but ANSI doesn’t specify that it must be so. 2/8/2021 IO Functions 179
  • 180. Second Issue – Buffering of data • A buffer is a block of memory allocated for temporary storage of data. • When you input data to a program, say, using scanf, the data is first kept in this buffer before it is transmitted to the program. • Similarly, when a program outputs data, say, using printf, the data is first written to a buffer before it is transferred to the output device. • Both operations require flushing of the buffer, the mechanism by which the contents of the buffer are transferred to the final destination. 2/8/2021 IO Functions 180
  • 181. Types of I/O Functions • These functions can be grouped into two categories: • Character-handling functions – (like getchar, fgetc, putchar and fputc). • Formatted I/O functions – (printf and scanf). • These functions also perform conversion of data between character and other data types. 2/8/2021 IO Functions 181
  • 182. CHARACTER INPUT WITH getchar • The C standard library is a collection of archives and header files. • An archive is a disk file that contains the precompiled object code of several functions. • The prototypes of these functions are maintained in a set of header files (like stdio.h). 2/8/2021 IO Functions 182
  • 183. getchar() • The getchar function fetches the next character from the input buffer that has previously been filled with keyboard input. • It is a character-oriented function, which means it treats input (say, the string 123) as three characters even if they represent a number. • getchar uses no arguments (the word void in the prototype) and returns the machine value of this character as an int. 2/8/2021 IO Functions 183
  • 184. getchar() • There are mainly three uses of this function: • (1). Pause a Program. – A call to getchar pauses a program which resumes operation after the user has pressed [Enter]. • (2). Accept a single-character response. – In this situation, the return value of getchar is saved and later used for decision making by an if or switch statement: • If you key in y and press [Enter], these two characters are saved by the input buffer. • getchar fetches the y and returns it as an int, but it leaves behind the newline character in the buffer. 2/8/2021 IO Functions 184
  • 185. getchar() • (3). Fetch a group of characters by running in a loop. – In this sequence, getchar fetches all characters from the buffer before it encounters EOF, when the loop terminates. – Every fetched character is written to the terminal using the putchar function. 2/8/2021 IO Functions 185
  • 186. CHARACTER OUTPUT WITH putchar • The putchar function complements the role of getchar by writing one character to the terminal. • This character is accepted as an argument of type int. 2/8/2021 IO Functions 186
  • 187. putchar() • When dealing with single characters, getchar and putchar are preferred to their formatted cousins, scanf and printf. • The other functions of this family (getc/putc and fgetc/fputc) also provide the same functionality as getchar and putchar. 2/8/2021 IO Functions 187
  • 189. THE STANDARD FILES • C treats the keyboard, terminal and printer as files. – stdin, the standard input file (default: keyboard). – stdout, the standard output file (default: terminal). – stderr, the standard error file (default: terminal). 2/8/2021 IO Functions 189
  • 190. OTHER CHARACTER-I/O FUNCTIONS • The getchar and putchar functions were designed to work only with stdin and stdout, respectively. • The standard library supports another two sets of functions that also read and write a character: – fgetc and fputc – getc and putc • Unlike getchar and putchar, the preceding functions are meant to be used with any file— includinga disk file. 2/8/2021 IO Functions 190
  • 191. The fgetc and fputc Functions • I/O functions that have the “f ” prefix are designed to work with files. • Both fgetc and fputc use an argument that identifies the file. • When used with the arguments, stdin or stdout, these functions replicate the behavior of their getchar/putchar equivalents, as shown in the following: 2/8/2021 IO Functions 191
  • 193. The getc and putc Macros • C also supports the getc and putc macros, which replicate the functionality of the fgetc and fputc functions. • Both sets use the same type and number of arguments and return the sam • A C macro is an alias that behaves like a function without incurring the cost of a function call. • It is defined using the #define preprocessor directivee values. 2/8/2021 IO Functions 193
  • 194. The ungetc Function • The ungetc function reverses the action of getc by putting back the most recently read character to the input stream. 2/8/2021 IO Functions 194
  • 195. Takeaway • The functions and macros that we have discussed so far read and write data as characters. • They cannot identify or handle specific data types in the character stream. • The rest of this section examines the scanf and printf functions that convert character data into specific data types and vice versa. 2/8/2021 IO Functions 195
  • 196. FORMATTED INPUT: THE scanf FUNCTION • scanf is the main member of a family of input functions that includes fscanf and sscanf. • Unlike most functions, scanf uses a variable number of arguments. • The first argument (cstring) is a control string containing one or more format specifiers (like %d). • The remaining arguments (&var1, &var2, etc.) represent— not variables—but their addresses. • The number of variable addresses must equal the number of format specifiers. 2/8/2021 IO Functions 196
  • 197. Components of scanf 2/8/2021 IO Functions 197
  • 198. Example • if the control string is “%c %d %f” and scanf encounters the string M 1986 37.4, it performs the following tasks: – Saves the character M (%c) to the variable gender without performing any conversion. – Converts the string 1986 to the integer 1986 (%d) and saves it in the variable year. – Converts the four-character string 37.4 to the floating point value 37.4 (%f) and saves it in the variable amount. 2/8/2021 IO Functions 198
  • 201. scanf: THE MATCHING RULES • scanf splits input on whitespace (space, tab and newline) even if the control string doesn’t contain whitespace. • Before doing anything else, you must commit the following rule to memory: – “Whitespace in the control string matches zero or more leading whitespace characters in the input”. 2/8/2021 IO Functions 201
  • 202. Examples • This means that both %d%d and %d %d match the strings 12 45 and 12 45. • This rule doesn’t apply to %c. • First, if the control string contains non-whitespace characters, the same characters must be present in the input. – For instance, %d:%d:%d matches 12:30:45 and 12: 30: 45 but not 12 :30 :45 because two values contain trailing whitespace. • Second, if a field width is specified (as in %2d), scanf tries to match two characters of the specified data type. – Thus, %2d%2d%2d splits the string 311214 into the values 31, 12 and 14 and saves them in three int variables. 2/8/2021 IO Functions 202
  • 203. Mismatches and Return Value 2/8/2021 IO Functions 203
  • 204. FORMATTED OUTPUT: THE printf FUNCTION 2/8/2021 IO Functions 204
  • 205. Components of printf 2/8/2021 IO Functions 205
  • 207. Thank you 2/8/2021 IO Functions 207