C Programming Unit 2 - V1
C Programming Unit 2 - V1
C PROGRAMMING
Unit 2
Basics of C Programming
Table of Contents
6 Terminal Questions - - 27
7 Answers to Self Assessment Questions - - 27
8 Answers to Terminal Questions - - 28
9 Exercises - - 28
1. INTRODUCTION
Data Types play a fundamental role in C programming, providing a way to classify and work
with different types of data. This knowledge is crucial for understanding the behaviour of
variables and constants in C programs. The objectives of delving into data types are to ensure
precise representation of data and facilitate efficient program execution.
Floating-point Numbers are a specific data type in C that allows representation of real
numbers, including decimal fractions. Understanding their characteristics and usage is vital
for dealing with mathematical computations and real-world applications where precision is
essential.
The type cast Operator is a powerful tool for explicitly converting one data type into another.
This capability is particularly useful when working with mixed data types in expressions,
allowing programmers to control how data is interpreted and processed.
The type char represents character data in C. It is a fundamental data type for handling single
characters, making it indispensable for tasks involving text processing and manipulation.
Keywords in C are reserved words that have predefined meanings. These words are crucial
for constructing statements and expressions in a C program. Mastery of keywords ensures
proper communication with the compiler, facilitating accurate program execution.
Variables, introduced in section 2.2, serve as containers for storing and manipulating data
during program execution. Proper declaration and usage of variables are essential for
writing effective and readable C programs.
Simple C programs involve applying the concepts discussed earlier, including variables and
data types, to solve specific problems. These programs serve as practical examples to
reinforce understanding and application of C programming principles.
Constants in C are values that remain unchanged during program execution. Integer
Constants, Real Constants, Character Constants, String Constants, and Backslash Character
Constants are various types that cater to different data representations and scenarios.
1.1. Objectives:
2. DATA TYPES IN C
Data types in C programming are foundational elements that define the nature of variables
and guide data manipulation. The primary objective is to understand their impact on data
representation in computer memory, optimizing storage and execution efficiency. Core data
types, including int, float, double, and char, require exploration to make informed choices in
variable selection based on precision and range needs. Going beyond built-in types, learning
to create user-defined types using structures and enumerations enhances code organization.
Finally, delving into type modifiers (e.g., short, long) and qualifiers (e.g., const, volatile)
refines data type characteristics, enabling programmers to tailor variables for specific tasks
and ensuring the creation of efficient, readable, and resilient C programs.
Floating point (or real) numbers are stored in 32 bit (on all 16 bit and 32 bit machines), with
6 digits of precision. Floating point numbers are defined in C by the keyword float. When the
accuracy provided by a float number is not sufficient, the type double can be used to define
the number. A double data type number uses 64 bits giving a precision of 14 digits. These are
known as double precision numbers. To extend the precision further, we may use long
double which uses 80 bits. The table 3.1 shows all the allowed combinations of floating point
numbers and qualifiers and their size and range on a 16-bit machine.
Table 2.1.1: Floating point numbers and qualifiers and their size and range on a 16-
bit machine.
Type Size (bits) Range
main()
{
/* …….DECLARATIONS……………………..*/
float x, p;
double y, q;
unsigned k;
/* ……………….DECLARATIONS AND ASSIGNMENTS………..*/
int m=54321;
long int n=1234567890;
/*…………..ASSIGNMENTS……………………*/
x = 1.234567890000;
y = 9.87654321;
k = 54321;
p=q=1.0;
/*…………….PRINTING………………….*/
printf(“m=%d\n”,m);
printf(“n=%ld\n”,n);
printf(“x=%.12lf\n”,x);
printf(“x=%f\n”,x);
printf(“y=%.12lf\n”,y);
printf(“y=%lf\n”,y);
printf(“k=%u p= %f q=%.12lf\n”,k,p,q);
}
Output
m= -11215
n= 1234567890
x = 1.234567880630
x = 1.234568
y = 9.876543210000
y = 9.876543
k = 54321 p = 1.000000 q= 1.000000000000
Output
1
2.3
4.67
1.42
7
3.67
4.08
2.2
4.25
8.21
N= 10 Sum= 38.799999 Average= 3.880000
#include <math.h>
main()
{
float a,b,c,discriminant, root1, root2;
printf(“input the values of a,b and c\n”);
scanf (“%f %f %f”, &a, &b, &c);
discriminant = b * b – 4 * a *c;
if (discriminant<0)
printf(“roots are imaginary\n”);
else
{
root1 = (-b + sqrt(discriminant)) / (2 * a);
root2 = (-b - sqrt(discriminant)) / (2 * a);
printf (“Root1 = %5.2f \n Root2 = %5.2f \n”, root1, root2); }
}
Output
12 3
C permits mixing of constants and variables of different types in an expression, but during
evaluation it adheres to very strict rules of type conversion. We know that the computer
considers one operator at a time, involving two operands.
If the operands are of different types, the ‘lower’ type is automatically converted to the
‘higher’ type before the operation proceeds. The result is of higher type.
Given below is the sequence of rules that are applied while evaluating expressions.
• If one of the operands is long double, the other will be converted to long double and
the result will be long double;
• else, if one of the operands is double, the other will be converted to double and the
result will be double;
• else, if one of the operands is float, the other will be converted to float and the result
will be float;
• else, if one of the operands is unsigned long int, the other will be converted to unsigned
long int and the result will be unsigned long int;
• else if one of the operands is long int and the other is unsigned int, then:
• if unsigned int can be converted to long int, the unsigned int operand will be converted
as such and the result will be long int;
else, both operands will be converted to unsigned long int and the result will be
unsigned long int;
• else, if one of the operands is long int , the other will be converted to long int and the
result will be long int;
• else, if one of the operands is unsigned int , the other will be converted to unsigned int
and the result will be unsigned int;
The final result of an expression is converted to type of the variable on the left of the
assignment sign before assigning the value to it. However, the following changes are
introduced during the final assignment:
When one of the operands is real and the other is integer, the expression is called a mixed-
mode arithmetic expression. If either operand is of the real type, then only the real operation
is performed and the result is always real number. Thus
25 / 10.0 = 2.5
Whereas 25 / 10 =2
SELF-ASSESSMENT QUESTIONS - 1
1. When the accuracy provided by a float number is not sufficient, the type long
float can be used to define the number. (True/False)
2. A double data type uses __________ bits.
3. If the operands are of different data types, the ‘lower’ type is automatically
converted to the ‘higher’ type before the operation proceeds. (True/False)
4. During the final assignment ________ to int causes dropping of the excess higher
order bits.
5. The value of the expression 22.0/10 is ________.
C performs type conversions automatically. However, there are instances when we want to
force a type conversion in a way that is different from the automatic conversion. Consider,
for example, the calculation of ratio of doctors to engineers in a town.
Since doctor _number and engineer_number are declared as integers in the program, the
decimal part of the result of the division would be lost and Ratio would represent a wrong
figure. This problem can be solved by converting locally one of the variables to the floating
point as shown below:
The operator (float) converts the doctor_number to floating point for the purpose of
evaluation of the expression. Then using the rule of automatic conversion, the division is
performed in floating point mode, thus retaining the fractional part of the result. Note that
in no way does the operator (float) affect the value of the variable doctor_number. And also,
the type of doctor_number remains as int in the other parts of the program.
The process of such local conversion is known as casting a value. The general form of cast is:
(type-name) expression
where type-name is one of the standard C data types. The expression may be a constant,
variable or an expression. The Table 3.2 shows some examples of casts and their actions:
Example Action
A=(int) 21.3 / (int) 4.5 Evaluated as 21/4 and the result would be 5.
main()
{
/* Program to find average of two integers */
float avg;
int n=2,n1,n2;
printf(“enter any 2 numbers\n”);
scanf(“%d %d”,&n1,&n2);
avg=(n1+n2)/(float)n;
printf(“ their average is\n”,avg);
}
Casting can be used to round-off a given value. Consider the following statement:
X= (int) (y+0.5);
If y is 37.7, y+0.5 is 38.2 and on casting, the result becomes 38, the value that is assigned to
X. Of course, the expression, being cast is not changed. When combining two different types
y = p + m;
y = p + (double)m;
However, the second statement is preferable. It will work the same way on all machines and
is more readable.
SELF-ASSESSMENT QUESTIONS - 2
A single character can be defined as a character(char) type data. Characters are usually
stored in 8 bits (one byte) of internal storage. The qualifier signed or unsigned may be
explicitly applied to char. While unsigned chars have values between 0 and 255, signed
chars have values from -128 to 127.
A character constant is formed by enclosing the character within a pair of single quote marks.
So ‘b’, ‘.’ and ‘5’ are all valid examples of character constants. Note that a character constant,
which is a single character enclosed in single quotes is different from a character string,
which is any number of characters enclosed in double quotes.
The format characters %c can be used in a printf statement to display the value of a char
variable at the terminal.
Program: The following program illustrates how to use char data type.
#include<stdio.h>
main()
{
char c=’A’;
int a=65;
printf(“%c\n”, c);
printf(“%d\n”, c);
printf(“%c\n”,a);
}
Output
65
Note that with the format characters %d, the ASCII number of the character is displayed.
With the format character %c, the character corresponding to the given ASCII number is
displayed.
SELF-ASSESSMENT QUESTIONS - 3
2.8. Keywords
Keywords are the reserved words of a programming language. All the keywords have fixed
meanings and these meanings cannot be changed.
Keywords serve as basic building blocks for program statements. The list of all keywords in
ANSI C are listed in the Table 3.3.
do if static while
All keywords must be written in lowercase. Some compilers may use additional keywords
that must be identified from the C manual.
SELF-ASSESSMENT QUESTIONS - 4
Integers are whole numbers with a range of values supported by a particular machine.
Generally, integers occupy one word of storage, and since the word sizes of machines vary
(typically, 16 or 32 bits) the size of an integer that can be stored depends on the computer.
If we use 16 bit word length, the size of the integer value is limited to the range -32768 to
+32767 (that is, -215 to +2 15 -1 ). A signed integer uses one bit for sign and 15 bits for the
magnitude of the number. Similarly, a 32 bit word length can store an integer ranging from -
2,147,483,648 to 2,147,483,647.
In order to provide some control over the range of numbers and storage space, C has three
classes of integer storage, namely short int, int , and long int, in both signed and unsigned
forms. For example, short int represents fairly small integer values and requires half the
amount of storage as a regular int number uses. A signed integer uses one bit for sign and
15 bits for the magnitude of the number, therefore, for a 16 bit machine, the range of
unsigned integer numbers will be from 0 to 65,535.
We declare long and unsigned integers to increase the range of values. The use of qualifier
signed on integers is optional because the default declaration assumes a signed number. The
Table 1.2 shows all the allowed combinations of basic types and qualifiers and their size and
range on a 16-bit machine.
Informally, a variable (also called an object) is a place where you can store a value so that
you can refer to it unambiguously. A variable needs a name. You can think of the variables in
your program as a set of boxes, each with a label giving its name; you might imagine that
storing a value “in'' a variable consists of writing the value on a slip of paper and placing it in
the box.
Now let us see how integers and variables are declared. A declaration tells the compiler the
name and type of a variable you'll be using in your program.
In its simplest form, a declaration consists of the type, the name of the variable, and a
terminating semicolon:
int i;
We can also declare several variables of the same type in one declaration, separating them
with commas as shown above.
The placement of declarations is significant. You can't place them just anywhere (i.e. they
cannot be interspersed with the other statements in your program). They must either be
placed at the beginning of a function, or at the beginning of a brace-enclosed block of
statements, or outside of any function. Furthermore, the placement of a declaration, as well
as its storage class, controls several things about its visibility and lifetime, as we'll see later.
You may wonder why variables must be declared before use. There are two reasons:
• It makes things somewhat easier on the compiler; it knows right away what kind of
storage to allocate and what code to emit to store and manipulate each variable; it
doesn't have to try to intuit the programmer's intentions.
• It forces a bit of useful discipline on the programmer: you cannot introduce variables
wherever you wish; you must think about them enough to pick appropriate types for
them. (The compiler's error messages to you, telling you that you apparently forgot to
declare a variable, are as often helpful as they are a nuisance: they're helpful when they
tell you that you misspelled a variable, or forgot to think about exactly how you were
going to use it.)
Most of the time, it is recommended to write one declaration per line. For the most part, the
compiler doesn't care what order declarations are in. You can order the declarations
alphabetically, or in the order that they're used, or to put related declarations next to each
other. Collecting all variables of the same type together on one line essentially orders
declarations by type, which isn't a very useful order (it's only slightly more useful than
random order).
A declaration for a variable can also contain an initial value. This initializer consists of an
equal sign and an expression, which is usually a single constant:
int i = 1;
SELF-ASSESSMENT QUESTIONS - 5
13. The size of the Integers in C language is same in all the machines. (True/False)
14. A ________ is a place where we can store values.
15. Size of int is _________ bits.
16. Which of the following tells the compiler the name and type of a variable you'll
be using in your program? ( declaration)
(a) declaration
(b) variables
(c) integers
(d) assignments
17. The __________ consists of an equal sign and an expression, which is usually a
single constant. (initializer)
18. A single declaration statement can contain variables of different types.
(True/False)
Within limits, you can give your variables and functions any names you want. These names
(the formal term is “identifiers'') consist of letters, numbers, and underscores. For our
purposes, names must begin with a letter. Theoretically, names can be as long as you want,
but extremely long ones get tedious to type after a while, and the compiler is not required to
keep track of extremely long ones perfectly. (What this means is that if you were to name a
variable, say, supercalafragalisticespialidocious, the compiler might get lazy and pretend that
you'd named it super-calafragalisticespialidocio, such that if you later misspelled it super-
calafragalisticespialidociouz, the compiler wouldn't catch your mistake. Nor would the
compiler necessarily be able to tell the difference if for some perverse reason you
deliberately declared a second variable named supercalafragalisticespialidociouz.)
The capitalization of names in C is significant: the variable names variable, Variable, and
VARIABLE (as well as silly combinations like variAble) are all distinct.
A final restriction on names is that you may not use keywords (the words such as int and for
which are part of the syntax of the language) as the names of variables or functions (or as
identifiers of any kind).
Now let us see how you can assign values to variables. The assignment operator = assigns a
value to a variable. For example,
x = 1;
sets x to 1, and
a = b;
i = i + 1;
is, as we've mentioned elsewhere, the standard programming idiom for increasing a
variable's value by 1: this expression takes i's old value, adds 1
to it, and stores it back into i. (C provides several “shortcut'' operators for modifying
variables in this and similar ways, which we'll meet later. We've called the = sign the
“assignment operator'' and referred to “assignment expressions'' because, in fact, = is an
operator just like + or -. C does not have “assignment statements''; instead, an assignment
like a = b is an expression and can be used wherever any expression can appear. Since it's an
expression, the assignment a = b has a value, namely, the same value that's assigned to a. This
value can then be used in a larger expression; for example, we might write
c = a = b;
c = (a = b);
and assigns b’s value to both a and c. (The assignment operator, therefore, groups from right
to left.) Later we'll see other circumstances in which it can be useful to use the value of an
assignment expression. It's usually a matter of style whether you initialize a variable with an
initializer in its declaration or with an assignment expression near where you first use it.
That is, there's no particular difference between
int a = 10;
and
int a;
/* later... */
a = 10;
SELF-ASSESSMENT QUESTIONS - 6
4. CONSTANTS
Constants in C refer to fixed values that do not change during the execution of a program. C
supports several types of constants as illustrated in Fig. 1.1.
Fig. 2.3.1
An integer constant refers to a sequence of digits. There are three types of integers, namely
decimal, octal and hexadecimal.
An octal integer constant consists of any combination of digits from the set 0 through 7, with
a leading 0.
The largest integer value that can be stored is machine-dependent. It is 32767 on 16-bit
machines and 2,147,483,647 on 32-bit machines. It is also possible to store larger integer
constants on these machines by appending qualifiers such as U, L and UL to the constants.
Type and execute the above program and observe the output
The numbers containing fractional parts like 67.45 are called real (or floating point)
constants.
mantissa e exponent
The mantissa is either a real number expressed in decimal notation or an integer. The
exponent is an integer number with an optional plus or minus sign. The letter e separating
the mantissa and the exponent can be written in either lowercase or uppercase.
A single character constant (or simple character constant) contains a single character
enclosed within a pair of single quote marks.
Character constants have integer values known as ASCII values. For example, the statement
printf(“%d”, ‘a’);
would print the number 97, the ASCII value of the letter a. Similarly, the statement
printf(“%c”, 97);
A string constant is a sequence of characters enclosed within double quotes. The characters
may be letters, numbers, special characters and blank space.
C supports some special backslash character constants that are used in output functions. A
list of such backslash character constants is given in Table 1.1. Note that each one of them
represents one character, although they consist of two characters. These character
combinations are called escape sequences.
Constant Meaning
‘\\’ backslash
‘\0’ null
SELF-ASSESSMENT QUESTIONS - 7
21. An octal integer constant consists of any combination of digits from the set _________
through _________.
22. A sequence of digits preceded by 0x or 0X is considered as _____________ integer.
23. A string constant is a sequence of __________ enclosed within double quotes.
5. SUMMARY
In the realm of C programming, this overview unfolds with an introduction, highlighting the
significance of various components. Section 2.1 delves into data types, elucidating their role
in shaping how variables store and process information. It covers fundamental elements like
floating-point numbers, the type cast operator, 'char' type, and keywords, establishing the
groundwork for precise programming.
The subsequent sections, 2.2 and 2.3, navigate through variables and simple C programs,
respectively. Understanding variables is essential for effective data manipulation, while the
creation of simple programs reinforces practical application.
The exploration extends to constants, encompassing integer, real, character, string, and
backslash character constants. This comprehensive approach, emphasizing objectives and
practicality, ensures a well-rounded comprehension of the foundational elements necessary
for proficient C programming.
6. TERMINAL QUESTIONS
1. False
2. 64
3. True
4. long in
5. 2.2
6. True
7. 0
8. 35
9. %c
10. False
11. Lower Case
12. False
13. False
14. Variable
15. 16
16. (a) declaration
17. Initializer
18. False
19. True
20. Underscore
21. (0,7)
22. Hexadecimal
23. characters
1. A signed integer uses one bit for sign and 15 bits for the magnitude of the number.
(Refer Section 2.2 for more details)
2. A declaration tells the compiler the name and type of a variable you'll be using in your
program. In its simplest form, a declaration consists of the type, the name of the
variable, and a terminating semicolon:
int i;
9. EXERCISE
1. Write a program that takes two integers as input and swaps their values using a
temporary variable.
2. Write a program that calculates the area of a rectangle using constants for length and
width.
3. Convert the temperature in Fahrenheit to Celsius by taking user input.