0% found this document useful (0 votes)
2 views28 pages

C Programming Unit 2 - V1

Uploaded by

Sikha Bansal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views28 pages

C Programming Unit 2 - V1

Uploaded by

Sikha Bansal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

C Programming Manipal University Jaipur (MUJ)

BACHELOR OF COMPUTER APPLICATIONS


SEMESTER 1

C PROGRAMMING

Unit 2 : Basics of C Programming 1


C Programming Manipal University Jaipur (MUJ)

Unit 2
Basics of C Programming
Table of Contents

SL Fig No / Table SAQ /


Topic Page No
No / Graph Activity
1 Introduction - -
4-5
1.1 Objectives - -
2 Data types in C 1, 2, 3 1, 2, 3, 4
2.1 Floating-point Numbers - -
2.2 Program to calculate the average of N -
-
numbers
2.3 Program to compute the roots of a -
-
quadratic equation
6 - 16
2.4 Converting Integers to Floating-point -
-
and vice-versa
2.5 Mixed-mode Expressions - -
2.6 The type cast Operator - -
2.7 The type char - -
2.8 Keywords - -
3 Concept of an Integer and Variable 4, 5, 6
3.1 Rules for naming Variables and - 17 - 21
-
assigning values to variables
4 Constants 5, 6 7
4.1 Integer constants - -
4.2 Real constants - -
22 - 25
4.3 Character constants - -
4.4 String constants - -
4.5 Backslash character constants - -
5 Summary - - 26

Unit 2 : Basics of C Programming 2


C Programming Manipal University Jaipur (MUJ)

6 Terminal Questions - - 27
7 Answers to Self Assessment Questions - - 27
8 Answers to Terminal Questions - - 28
9 Exercises - - 28

Unit 2 : Basics of C Programming 3


C Programming Manipal University Jaipur (MUJ)

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.

Unit 2 : Basics of C Programming 4


C Programming Manipal University Jaipur (MUJ)

In conclusion, this comprehensive introduction to data types and related concepts in C


programming lays the foundation for constructing robust and efficient programs. Mastering
these topics is essential for programmers to harness the full potential of the C language in
diverse applications.

1.1. Objectives:

At studying this unit, you should be able to:

❖ Understand the role of data types in C programming.


❖ Demonstrate proficiency in declaring and using variables.
❖ Apply the type cast operator
❖ Differentiate between integer, real, character, string, and backslash character constants.

Unit 2 : Basics of C Programming 5


C Programming Manipal University Jaipur (MUJ)

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.

2.1. Floating-point Numbers

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

Float 32 3.4E-38 to 3.4E+38

Double 64 1.7E-308 to 1.7E+308

long double 80 3.4E-4932 to 1.1E+4932

Program 2.1.1: The following program illustrates typical declarations, assignments


and values stored in various types of variables.

Unit 2 : Basics of C Programming 6


C Programming Manipal University Jaipur (MUJ)

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

Unit 2 : Basics of C Programming 7


C Programming Manipal University Jaipur (MUJ)

2.2. Program to calculate the average of N numbers

Program 2.1.2: Program to calculate the average of N numbers


#define N 10 /* SYMBOLIC CONSTANT */
main()
{
Int count; /* DECLARATION OF
float sum, average, number; VARIABLES */
sum = 0; / * INITIALIZATION OF
count = 0; VARIABLES*/
while (count<N)
{
scanf(“%f”, &number);
sum = sum + number;
count = count + 1;
}
average = sum / N;
printf(“N = % d Sum = %f “, N, sum);
printf(“Average = %f”, average);

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

Unit 2 : Basics of C Programming 8


C Programming Manipal University Jaipur (MUJ)

2.3. Program to compute the roots of a quadratic equation

Program 2.1.3: Program to compute the roots of a quadratic equation

#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

input the values of a,b and c

24 -16 Root1 = 2.00 Root2 = -4.00

input the values of a,b and c

12 3

roots are imaginary

Unit 2 : Basics of C Programming 9


C Programming Manipal University Jaipur (MUJ)

2.4. Converting Integers to Floating-point and vice-versa

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.

All short type are automatically converted to int ; then

• 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;

Unit 2 : Basics of C Programming 10


C Programming Manipal University Jaipur (MUJ)

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:

• float to int causes truncation of the fractional part.


• double to float causes rounding of digits.
• long int to int causes dropping of the excess higher order bits

2.5. Mixed-mode Expressions

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 ________.

Unit 2 : Basics of C Programming 11


C Programming Manipal University Jaipur (MUJ)

2.6. The type cast Operator

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.

Ratio = doctor_number / engineer _number

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:

Ratio = (float) doctor_number / engineer _number

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:

Unit 2 : Basics of C Programming 12


C Programming Manipal University Jaipur (MUJ)

Table 2.1.2: Use of Casts

Example Action

X=(int) 8.5 8.5 is converted to integer by truncation.

A=(int) 21.3 / (int) 4.5 Evaluated as 21/4 and the result would be 5.

B=(double) sum/n Division is done in floating point mode.

Y= (int) (a+b) The result of a+b is converted to integer.

Z= (int) a+b a is converted to integer and then added to b.

P=cos(( double)x) Converts x to double before using it.

Program: The following program shows the use of casts

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

Unit 2 : Basics of C Programming 13


C Programming Manipal University Jaipur (MUJ)

of variables in an expression, never assume the rules of automatic conversion. It is always a


good practice to explicitly force the conversion. It is more safer and more portable. For
example, when y and p are double and m is int, the following two statements are equivalent.

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

6. Casting can be used to round-off a given value. (True/False)


7. The value of A in the expression A=(int)11.35/(int)14.5 is ___________.
8. If the value of X is 35.2, then the value of A in the expression: A = (int)(X+0.5); is
______________.

2.7. The type char

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.

Unit 2 : Basics of C Programming 14


C Programming Manipal University Jaipur (MUJ)

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

9. What is the format character to display the value of a char variable?


10. The output of the following C statement: printf(“%c”, 70); is ___________.

Unit 2 : Basics of C Programming 15


C Programming Manipal University Jaipur (MUJ)

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.

Table 2.1.3: ANSI C Keywords


auto Double int struct

break Else long switch

case Enum register typedef

char extern return union

const float short unsigned

continue for signed void

default goto sizeof volatile

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

11. All keywords must be written in ____________.


12. default is not a valid keyword in C. (True/False)

Unit 2 : Basics of C Programming 16


C Programming Manipal University Jaipur (MUJ)

3. CONCEPT OF AN INTEGER AND VARIABLE

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.

Table 2.2.1: Basic types, qualifiers and their size


Type Size (bits) Range

int or signed int 16 -32,768 to 32,767

unsigned int 16 0 to 65535

short int or signed short


int 8 -128 to 127

unsigned short int 8 0 to 255

long int or signed long int 32 -2,147,483,648 to 2,147,483,647

unsigned long int 32 0 to 4,294,967,295

Unit 2 : Basics of C Programming 17


C Programming Manipal University Jaipur (MUJ)

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;

The above statement declares an integer variable i.

long int i1, i2;

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

Unit 2 : Basics of C Programming 18


C Programming Manipal University Jaipur (MUJ)

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;

int i1 = 10, i2 = 20;

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)

Unit 2 : Basics of C Programming 19


C Programming Manipal University Jaipur (MUJ)

3.1. Rules for naming Variables and assigning values to variables

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;

sets a to whatever b's value is. The expression

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

Unit 2 : Basics of C Programming 20


C Programming Manipal University Jaipur (MUJ)

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;

Which is equivalent to?

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

19. In C, variable names are case sensitive. (True/False)


20. A variable name in C consists of letters, numbers and _________.

Unit 2 : Basics of C Programming 21


C Programming Manipal University Jaipur (MUJ)

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

4.1. Integer constants

An integer constant refers to a sequence of digits. There are three types of integers, namely
decimal, octal and hexadecimal.

Decimal integers consist of a set of digits, 0 through 9, preceded by an optional – or +.

Examples: 12, -546, 0, 354647, +56

An octal integer constant consists of any combination of digits from the set 0 through 7, with
a leading 0.

Examples: 045, 0, 0567

A sequence of digits preceded by 0x or 0X is considered as hexadecimal integer. They may


also include alphabets A through F or a through f. The letters A through F represent numbers
10 through 15.

Examples: 0X6, 0x5B, 0Xbcd, 0X

Unit 2 : Basics of C Programming 22


C Programming Manipal University Jaipur (MUJ)

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.

Examples: 54637U or 54637u (unsigned integer)

65757564345UL or 65757564345ul (unsigned long integer)

7685784L or 7685784l (long integer)

Program: Program to represent integer constants on a 16-bit computer


/* Integer numbers on 16-bit machine */
main()
{
printf(“Integer values\n\n”);
printf(“%d %d %d\n”, 32767,32767+1,32767+10); printf(“\n”);
printf(“Long integer values\n\n”);
printf(“%ld %ld %ld\n”, 32767L, 32767L+1L, 32767L+10L);
}

Type and execute the above program and observe the output

4.2. Real constants

The numbers containing fractional parts like 67.45 are called real (or floating point)
constants.

Examples: 0.0045, -8.5, +345.678

A real number may also be expressed in exponential (scientific) notation.

The general form is:

mantissa e exponent

Unit 2 : Basics of C Programming 23


C Programming Manipal University Jaipur (MUJ)

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.

Examples: 04e4, 12e-2, -1.3E-2

7500000000 may be written as 7.5E9 or 75E8.

Floating point constants are normally represented as double-precision quantities. However,


the suffixes f or F may be used to force single precision and l or L to extend double-precision
further.

4.3. Character constants

A single character constant (or simple character constant) contains a single character
enclosed within a pair of single quote marks.

Examples: ‘6’, ‘X’, ‘;’

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);

would print the letter a.

4.4. String constants

A string constant is a sequence of characters enclosed within double quotes. The characters
may be letters, numbers, special characters and blank space.

Examples: “Hello!”, “1947”, “5+3”

4.5. Backslash character constants

Unit 2 : Basics of C Programming 24


C Programming Manipal University Jaipur (MUJ)

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.

Table 2.3’.1: Backslash character constants

Constant Meaning

‘\b’ back space

‘\f’ form feed

‘\n’ new line

‘\r’ carriage return

‘\t’ horizontal tab

‘\v’ vertical tab

‘\’’ single quote

‘\” ‘ double quote

‘\\’ 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.

Unit 2 : Basics of C Programming 25


C Programming Manipal University Jaipur (MUJ)

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.

Unit 2 : Basics of C Programming 26


C Programming Manipal University Jaipur (MUJ)

6. TERMINAL QUESTIONS

1. Distinguish between signed and unsigned integers.


2. What are the components of declaration statement?
3. State the rules for naming a variable in C.
4. Clarify the different constants present in the C programming language.?

7. ANSWERS TO SELF ASSESSMENT 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

Unit 2 : Basics of C Programming 27


C Programming Manipal University Jaipur (MUJ)

8. ANSWERS TO TERMINAL QUESTIONS

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;

The above statement declares an integer variable i.

long int i1, i2;

3. In the C programming language, a variable is a named storage location that holds a


value. It is a fundamental concept used for storing and manipulating data within a
program. (For variable refer section 2.2)
4. Constants in C are values that remain unchanged during program execution. (For
variable refer section 2.3)

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.

Unit 2 : Basics of C Programming 28

You might also like