Unit 3

Download as pdf or txt
Download as pdf or txt
You are on page 1of 41

C Programming – Unit 3 BCA-TU ict.instructor90@gmail.

com

Introduction

The C programming language is a powerful general-purpose, procedural language that supports


structured programming and provides low-level access to the system memory. Dennis Ritchie
invented C language in 1972 at AT&T (then called Bell Laboratory), where it was implemented
in the UNIX system on DEC PDP II. It was also the successor of the B programming language
invented by Ken Thompson. C was designed to overcome the problems encountered by BASIC,
B, and BPCL programming languages. By 1980, C became the most popular language for
mainframes, microcomputers, and minicomputers.
It can be used to develop software like operating systems, databases, compilers, and so on. C
programming is an excellent language to learn to program for beginners.

History of C Programming
The advent of C programming begin in the late 1960s and share roots deep in the development of
UNIX operating system. UNIX is a popular network operating system that pumps heart of the
modern internet.
In late 1960s Ken Thompson and Dennis Ritchie developed, a language called B. Earlier version
of UNIX uses B programming language. It inherits many of its features from BCPL (Basic
Combined Programming Language).
Later in the early 1970s need for a portable operating system and programming language
originated. Rather developing programs and operating system for a particular machine. The need
of a portable operating system came in existence. This was the period when development of C
programming language started.
During 1969 to 1972, Dennis Ritchie at Bell Laboratories developed C. In 1972, the first release
of C programming got officially public. C inherited many features from ALGOL, BCPL and B. It
is such a powerful language that UNIX operating system is almost completely written in C.

C standards
The massive popularity of C programming headed development of its versions. However, every
version was similar to the original but often incompatible. To assure the standard of C in every
version, American National Standards Institute (ANSI) initiated work on C standards.
In 1989, ANSI sets base for all implementations of C compilers and published the first standard of
C. The first C standard is popularly known as C89. The current C standard is commonly referred
as C11.
C Programming – Unit 3 BCA-TU [email protected]

Fig: Timeline History of C language

Features of C

C is a popular programming language among programmers. It is one of the widely used


programming language in the world.
Simple and Robust
For beginner’s C is the easiest language to learn. Its simplicity lies in the lesser number of
programming constructs that can power up any complex system. However, some concepts of C
programming can become nightmare for beginners. C supports a rich set of built-in library
functions and a variety of operators.
C Programming – Unit 3 BCA-TU [email protected]

Portability
C is a machine independent language. C programs can run on a range of machines that has a C
compiler. Today almost every machine has a minimum C compiler installed on it. Hence, when
you write programs in C you should not worry, whether your program will run on a particular
machine or not. However, C does not supports platform independency as Java.
Modularity
C programs are modular in nature. We can divide C programs to several modules that will combine
in a single module to build the final program.
Extensibility
C language provides a rich set of built-in library function. We can also build our own library
functions and can use them in future. Because of modularization of programs, you can extend your
C programs anytime.
Speed
The compilation and execution of C programs are faster than modern programming languages.
Wide acceptability
C programming is widely known among programmers around the world. Because of its vast
popularity, it is suitable for most of the system projects.
Why should I learn C programming?
Whether you are beginning your programming life or you have learnt programming. Learning C
has its own importance, below are the few advantages of C, over other programming languages.
 C is a simple language, compared any other modern programming languages. It contains a
lesser number of programming constructs that makes it easy to learn. However, some
concepts of C programming can be a nightmare for beginners.
 Learning C will make you understand how a computer program functions internally.
 Despite being a high-level programming language its ability to provide rich support for
low-level programming separates it from modern programming languages.
 The Backbone of Operating system development is C. Most of the popular OS either fully
or partially written in C.
 C is the main programming language used in Apple iOS apps and OS development as
Objective C. Objective C is the Object Oriented version of C programming.
 C language is widely used for the development of Compilers, Assemblers, Language
Interpreters, Device drivers, Databases, Embedded systems, Server, Game frameworks etc.
 Most of the modern programming languages either directly or indirectly inherited from C.
Therefore, C will definitely help to learn C inherited languages.

Execution of C Program
C Programming – Unit 3 BCA-TU [email protected]

Overall Process
 Type the program in C editor and save with .c extension.
 Compile or build the program.
 If there are errors, correct the errors and recompile the program.
 If there are no errors, then execute/run the program.
 Which will open User Screen and check the result.

C Program Basics
C is a structured programming language. Every c program and its statements must be in a particular
structure. Every c program has the following general structure.
C Programming – Unit 3 BCA-TU [email protected]

Line 1: Comments - They are ignored by the compiler


This section is used to provide a small description of the program. The comment lines are simply
ignored by the compiler that means they are not executed. In C, there are two types of comments.

 Single Line Comments: Single line comment begins with // symbol. We can write any
number of single line comments.
 Multiple Lines Comments: Multiple lines comment begins with /* symbol and ends with */.
We can write any number of multiple lines comments in a program.
In a C program, the comment lines are optional. Based on the requirement, we write comments.
All the comment lines in a C program just provide the guidelines to understand the program and
its code.
Line 2: Preprocessing Commands
Preprocessing commands are used to include header files and to define constants. We use
the #include statement to include the header file into our program. We use a #define statement to
define a constant. The preprocessing statements are used according to the requirements. If we don't
need any header file, then no need to write #include statement? If we don't need any constant, then
no need to write a #define statement?
Line 3: Global Declaration
The global declaration is used to define the global variables, which are common for all the
functions after its declaration. We also use the global declaration to declare functions. This global
declaration is used based on the requirement.
Line 4: int main() or void main()
Every C program must write this statement. This statement (main) specifies the starting point of
the C program execution. Here, main is a user-defined method which tells the compiler that this is
the starting point of the program execution. Here, int is a data type of a value that is going to return
to the Operating System after completing the main method execution. If we don't want to return
any value, we can use it as void.
Line 5: Open Brace ({ )
The open brace indicates the beginning of the block which belongs to the main method. In C
program, every block begins with a '{' symbol.
Line 6: Local Declaration
In this section, we declare the variables and functions that are local to the function or block in
which they are declared. The variables which are declared in this section are valid only within the
function or block in which they are declared.
Line 7: Executable statements
C Programming – Unit 3 BCA-TU [email protected]

In this section, we write the statements which perform tasks like reading data, displaying the result,
calculations, etc., all the statements in this section are written according to the requirements.
Line 9: Closing Brace ( })
The close brace indicates the end of the block which belongs to the main method. In C program
every block ends with a '}' symbol.
Line 10, 11, 12, User-defined function ()
This is the place where we implement the user-defined functions. The user-defined function
implementation can also be performed before the main method. In this case, the user-defined
function need not be declared. Directly it can be implemented, but it must be before the main
method. In a program, we can define as many user-defined functions as we want. Every user-
defined function needs a function call to execute its statements.
General rules for any C program
 Every executable statement must end with a semicolon symbol (;).
 Every C program must contain exactly one main method (Starting point of the program
execution).
 All the system-defined words (keywords) must be used in lowercase letters.
 Keywords cannot be used as user-defined names (identifiers).
 For every open brace ({), there must be respective closing brace (}).
 Every variable must be declared before it is used.
First C Program

#include <stdio.h>

void main()

/* Our first simple C basic program */

printf("Hello World! ");

C PROGRAMMING BASICS TO WRITE A C PROGRAM:

Below are few commands and syntax used in C programming to write a simple C program. Let’s
see all the sections of a simple C program line by line.
C Programming – Unit 3 BCA-TU [email protected]

C Basic commands Explanation

This is a preprocessor command that includes


standard input output header file(stdio.h) from the
#include <stdio.h> C library before compiling a C program

This is the main function from where execution of


void main() any C program begins.

{ This indicates the beginning of the main function.

Whatever is given inside the command “/* */” in


any C program, won’t be considered for
/*_some comments_*/ compilation and execution.

printf(“Hello_World! “); printf command prints the output onto the screen.

} This indicates the end of the main function.

C Character Set
As every language contains a set of characters used to construct words, statements, etc. C language
also has a set of characters which include alphabets, digits, and special symbols. C language
supports a total of 256 characters.

Every C program contains statements. These statements are constructed using words and these
words are constructed using characters from C character set. C language character set contains the
following set of characters...
 Alphabets
 Digits
 Special Symbols
Alphabets
C language supports all the alphabets from the English language. Lower and upper case letters
together support 52 alphabets.
 lower case letters - a to z
 UPPER CASE LETTERS - A to Z
Digits
C language supports 10 digits which are used to construct numerical values in C language.
C Programming – Unit 3 BCA-TU [email protected]

Digits - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
Special Symbols
C language supports a rich set of special symbols that include symbols to perform mathematical
operations, to check conditions, white spaces, backspaces, and other special symbols.
Special Symbols - ~ @ # $ % ^ & * ( ) _ - + = { } [ ] ; : ' " / ? . >, < \ | tab newline space NULL
bell backspace vertical tab etc.
Every character in C language has its equivalent ASCII (American Standard Code for Information
Interchange) value.

Valid C Characters: Special Characters are listed below –

Symbol Meaning
C Programming – Unit 3 BCA-TU [email protected]

~ Tilde

! Exclamation mark

# Number sign

$ Dollar sign

% Percent sign

^ Caret

& Ampersand

* Asterisk

( Left parenthesis

) Right parenthesis

_ Underscore

+ Plus sign

| Vertical bar
C Programming – Unit 3 BCA-TU [email protected]

\ Backslash

` Apostrophe

– Minus sign

= Equal to sign

{ Left brace

} Right brace

[ Left bracket

] Right bracket

: Colon

” Quotation mark

; Semicolon

< Opening angle bracket

> Closing angle bracket

? Question mark
C Programming – Unit 3 BCA-TU [email protected]

, Comma

. Period

/ Slash

C program to print all the characters of C character Set

#include<stdio.h>

#include<conio.h>

int main() {

int i;

clrscr();

printf("ASCII ==> Character\n");

for(i = -128; i <= 127; i++)

printf("%d ==> %c\n", i, i);

getch();

return 0;

Preprocessor Directives

The C preprocessor is a macro processor that is used automatically by the C compiler to transform
your program before actual compilation (Preprocessor directives are executed before
compilation.). It is called a macro processor because it allows you to define macros, which are
brief abbreviations for longer constructs. A macro is a segment of code which is replaced by the
value of macro. Macro is defined by #define directive.
C Programming – Unit 3 BCA-TU [email protected]

 Preprocessing directives are lines in your program that start with #.


 The # is followed by an identifier that is the directive name.
 For example, #define is the directive that defines a macro.
 Whitespace is also allowed before and after the #.
The # and the directive name cannot come from a macro expansion. For example, if foo is defined
as a macro expanding to define, that does not make #foo a valid preprocessing directive.
All preprocessor directives starts with hash # symbol.
List of preprocessor directives:
 #include
 #define
 #undef
 #ifdef
 #ifndef
 #if
 #else
 #elif
 #endif
 #error
 #pragma

#include

The #include preprocessor directive is used to paste code of given file into current file. It is used
include system-defined and user-defined header files. If included file is not found, compiler
renders error.
It has three variants:
 #include <file>
This variant is used for system header files. It searches for a file named file in a list of
directories specified by you, then in a standard list of system directories.
 #include "file"
This variant is used for header files of your own program. It searches for a file named file
first in the current directory, then in the same directories used for system header files. The
current directory is the directory of the current input file.
 #include anything else
This variant is called a computed #include. Any #include directive whose argument does
not fit the above two forms is a computed include.
C Programming – Unit 3 BCA-TU [email protected]

Macro's (#define)
Let's start with macro, as we discuss, a macro is a segment of code which is replaced by the value
of macro. Macro is defined by #define directive.
Syntax
#define token value

There are two types of macros:


 Object-like Macros
 Function-like Macros
Object-like Macros
The object-like macro is an identifier that is replaced by value. It is widely used to represent
numeric constants. For example:
#define PI 3.1415
Here, PI is the macro name which will be replaced by the value 3.14. Let's see an example
of Object-like Macros:
#include <stdio.h>

#define PI 3.1415

main()

printf("%f",PI);

Output:
3.14000
Function-like Macros
The function-like macro looks like function call. For example:
#define MIN(a,b) ((a)<(b)?(a):(b))
Here, MIN is the macro name. Let's see an example of Function-like Macros:
#include <stdio.h>

#define MIN(a,b) ((a)<(b)?(a):(b))

void main() {
C Programming – Unit 3 BCA-TU [email protected]

printf("Minimum between 10 and 20 is: %d\n", MIN(10,20));

Output:
Minimum between 10 and 20 is: 10

#undef
To undefine a macro means to cancel its definition. This is done with the #undef directive.
Syntax:
#undef token
define and undefine example
#include <stdio.h>

#define PI 3.1415

#undef PI

main() {

printf("%f",PI);

Output:
Compile Time Error: 'PI' undeclared

#ifdef

The #ifdef preprocessor directive checks if macro is defined by #define. If yes, it executes the
code.
Syntax:
#ifdef MACRO
//code
#endif

#ifndef
C Programming – Unit 3 BCA-TU [email protected]

The #ifndef preprocessor directive checks if macro is not defined by #define. If yes, it executes
the code.
Syntax:
#ifndef MACRO
//code
#endif

#if

The #if preprocessor directive evaluates the expression or condition. If condition is true, it
executes the code.
Syntax:
#if expression
//code
#endif

#else
The #else preprocessor directive evaluates the expression or condition if condition of #if is false.
It can be used with #if, #elif, #ifdef and #ifndef directives.
Syntax:
#if expression
//if code
#else
//else code
#endif

Syntax with #elif


#if expression
//if code
#elif expression
C Programming – Unit 3 BCA-TU [email protected]

//elif code
#else
//else code
#endif

Example
#include <stdio.h>

#include <conio.h>

#define NUMBER 1

void main() {

#if NUMBER==0

printf("Value of Number is: %d",NUMBER);

#else

print("Value of Number is non-zero");

#endif

getch();

Output
Value of Number is non-zero

#error

The #error preprocessor directive indicates error. The compiler gives fatal error if #error directive
is found and skips further compilation process.
C #error example
#include<stdio.h>

#ifndef __MATH_H

#error First include then compile

#else

void main(){

float a;
C Programming – Unit 3 BCA-TU [email protected]

a=sqrt(7);

printf("%f",a);

#endif

#pragma

The #pragma preprocessor directive is used to provide additional information to the compiler.
The #pragma directive is used by the compiler to offer machine or operating-system feature.
Different compilers can provide different usage of #pragma directive.
Syntax:
#pragma token
Example
#include<stdio.h>

#include<conio.h>

void func() ;

#pragma startup func

#pragma exit func

void main(){

printf("\nI am in main");

getch();

void func(){

printf("\nI am in func");

getch();

}
C Programming – Unit 3 BCA-TU [email protected]

Output
I am in func
I am in main
I am in func

C printf and scan:

 printf() and scanf() functions are inbuilt library functions in C programming language
which are available in C library by default. These functions are declared and related macros
are defined in “stdio.h” which is a header file in C language.
 We have to include “stdio.h” file as shown in below C program to make use of these printf()
and scanf() library functions in C language.

 In C programming language, printf() function is used to print the (“character, string, float,
integer, octal and hexadecimal values”) onto the output screen.
 We use printf() function with %d format specifier to display the value of an integer
variable.
 Similarly %c is used to display character, %f for float variable, %s for string
variable, %lf for double and %x for hexadecimal variable.
 To generate a newline, we use “\n” in C printf() statement.

#include <stdio.h>

void main()

char ch = 'A';

char str[20] = "C Programming";

float flt = 10.234;

int no = 150;

double dbl = 20.123456;

printf("Character is %c \n", ch);

printf("String is %s \n" , str);


C Programming – Unit 3 BCA-TU [email protected]

printf("Float value is %f \n", flt);

printf("Integer value is %d\n" , no);

printf("Double value is %lf \n", dbl);

printf("Octal value is %o \n", no);

printf("Hexadecimal value is %x \n", no);

Output

Character is A
String is C Programming
Float value is 10.234000
Integer value is 150
Double value is 20.123456
Octal value is 226
Hexadecimal value is 96

scanf() function in C language

In C programming language, scanf() function is used to read character, string, numeric data from
keyboard
Consider below example program where user enters a character. This value is assigned to the
variable “ch” and then displayed.
Then, user enters a string and this value is assigned to the variable “str” and then displayed.

#include <stdio.h>
void main()
{
char ch;
char str[100];
printf("Enter any character \n");
scanf("%c", &ch);
C Programming – Unit 3 BCA-TU [email protected]

printf("Entered character is %c \n", ch);


printf("Enter any string ( upto 100 character ) \n");
scanf("%s", &str);
printf("Entered string is %s \n", str);
}

Output

Enter any character


a
Entered character is a
Enter any string (up to 100 character)
hai
Entered string is hai

Point to remember:
 printf() is used to display the output and scanf() is used to read the inputs.
 printf() and scanf() functions are declared in “stdio.h” header file in C library.
 All syntax in C language including printf() and scanf() functions are case sensitive.

Header files

Simple programs can be put in a single file, but when your program grows larger, it’s impossible
to keep it all in just one file. So, you can move parts of a program to a separate file, then you
create a header file.
A header file looks like a normal C file, except it ends with .h instead of .c, and instead of the
implementations of your functions and the other parts of a program, it holds the declarations.
Header file defines certain values, symbols and operations which is included in the file to obtain
access to its contents. The header file have the suffix ‘.h’. It contains only the prototype of the
function in the corresponding source file. For e.g., stdio.h contains the prototype for ‘printf’
while the corresponding source file contains its definition. It saves time for writing and
debugging the code.

#include <stdio.h>

To use it.
#include is a preprocessor directive.
C Programming – Unit 3 BCA-TU [email protected]

The preprocessor goes and looks up the stdio.h file in the standard library, because you used
brackets around it. To include your own header files, you’ll use quotes, like this:
#include "myfile.h"
Let’s make an example.
This program calculates the years since a given year:
C Programming – Unit 3 BCA-TU [email protected]

#include <stdio.h>
int calculateAge(int year) {
const int CURRENT_YEAR = 2020;
return CURRENT_YEAR - year;
}
int main(void) {
printf("%u", calculateAge(1990));
}

Suppose I want to move the calculateAge function to a separate file.


 Create a calculate_age.c file:

int calculateAge(int year) {


const int CURRENT_YEAR = 2020;
return CURRENT_YEAR - year;
}

And calculate_age.h file where I put the function prototype, which is same as the function in
the .c file, except the body:
int calculateAge(int year);

Now in the main .c file we can go and remove the calculateAge() function definition, and we can
import calculate_age.h, which will make the calculateAge() function available:

#include <stdio.h>

#include "calculate_age.h"

int main(void) {

printf("%u", calculateAge(1990));

}
C Programming – Unit 3 BCA-TU [email protected]

C Tokens

Every C program is a collection of instructions and every instruction is a collection of some


individual units. Every smallest individual unit of a c program is called token. Every instruction
in a c program is a collection of tokens. Tokens are used to construct c programs and they are
said to the basic building blocks of a c program.

In a c program tokens may contain the following...


 Keywords
 Identifiers
 Operators
 Special Symbols
 Constants
 Strings
 Data values
In a C program, a collection of all the keywords, identifiers, operators, special symbols,
constants, strings, and data values are called tokens.

C Keywords

As every language has words to construct statements, C programming also has words with a
specific meaning which are used to construct c program instructions. In the C programming
language, keywords are special words with predefined meaning. Keywords are also known as
reserved words in C programming language.

In the C programming language, there are 32 keywords. All the 32 keywords have their meaning
which is already known to the compiler.
Keywords are the reserved words with predefined meaning which already known to the
compiler. Whenever C compiler come across a keyword, automatically it understands its
meaning.

Properties of Keywords
 All the keywords in C programming language are defined as lowercase letters so they
must be used only in lowercase letters
 Every keyword has a specific meaning, users can not change that meaning.
 Keywords cannot be used as user-defined names like variable, functions, arrays, pointers,
etc...
C Programming – Unit 3 BCA-TU [email protected]

 Every keyword in C programming language represents something or specifies some kind


of action to be performed by the compiler.
 32 Keywords in C Programming Language
C Programming – Unit 3 BCA-TU [email protected]

C Identifiers

In C programming language, programmers can specify their name to a variable, array, pointer,
function, etc... An identifier is a collection of characters which acts as the name of variable,
function, array, pointer, structure, etc... In other words, an identifier can be defined as the user-
defined name to identify an entity uniquely in the c programming language that name may be of
the variable name, function name, array name, pointer name, structure name or a label.
The identifier is a user-defined name of an entity to identify it uniquely during the program
execution
Example
int age;
char name[30];

Here, age and name are identifiers.

Rules for Creating Identifiers


 An identifier can contain letters (UPPERCASE and
lowercase), numerics & underscore symbol only.
 An identifier should not start with a numerical value. It can start with a letter or an
underscore.
 We should not use any special symbols in between the identifier even whitespace.
However, the only underscore symbol is allowed.
 Keywords should not be used as identifiers.
 There is no limit for the length of an identifier. However, the compiler considers the first
31 characters only.
 An identifier must be unique in its scope.
Rules for Creating Identifiers for better programming
The following are the commonly used rules for creating identifiers for better programming...
 The identifier must be meaningful to describe the entity.
 Since starting with an underscore may create conflict with system names, so we avoid
starting an identifier with an underscore.
 We start every identifier with a lowercase letter. If an identifier contains more than one
word then the first word starts with a lowercase letter and second word onwards first
letter is used as an UPPERCASE letter. We can also use an underscore to separate
multiple words in an identifier.
C Programming – Unit 3 BCA-TU [email protected]

C data types
Data used in c program is classified into different types based on its properties. In the C
programming language, a data type can be defined as a set of values with similar characteristics.
All the values in a data type have the same properties.
Data types in the c programming language are used to specify what kind of value can be stored in
a variable. The memory size and type of the value of a variable are determined by the variable
data type. In a c program, each variable or constant or array must have a data type and this data
type specifies how much memory is to be allocated and what type of values are to be stored in
that variable or constant or array.
The formal definition of a data type is as follows...

The Data type is a set of value with predefined characteristics. Data types are used to declare
variable, constants, arrays, pointers, and functions.

C programming consists of following data types

 Primary data types (Basic data types OR Predefined data types)


 Derived data types (Secondary data types OR User-defined data types)
 Enumeration data types
 Void data type

Primary data types


The primary data types in the C programming language are the basic data types. All the primary
data types are already defined in the system. Primary data types are also called as Built-In data
types.
The following are the primary data types in c programming language...
 Integer data type
 Floating Point data type
C Programming – Unit 3 BCA-TU [email protected]

 Double data type


 Character data type

Integer Data type


The integer data type is a set of whole numbers. Every integer value does not have the decimal
value. We use the keyword "int" to represent integer data type in c. We use the keyword int to
declare the variables and to specify the return type of a function. The integer data type is used with
different type modifiers like short, long, signed and unsigned. The following table provides
complete details about the integer data type.
C Programming – Unit 3 BCA-TU [email protected]

Floating Point data types


Floating-point data types are a set of numbers with the decimal value. Every floating-point value
must contain the decimal value. The floating-point data type has two variants...
 float
 double
We use the keyword "float" to represent floating-point data type and "double" to represent
double data type in c. Both float and double are similar but they differ in the number of decimal
places. The float value contains 6 decimal places whereas double value contains 15 or 19
decimal places. The following table provides complete details about floating-point data types.

Character data type


The character data type is a set of characters enclosed in single quotations. The following table
provides complete details about the character data type.

Summary of Primary data Types


C Programming – Unit 3 BCA-TU [email protected]

void data type


The void data type means nothing or no value. Generally, the void is used to specify a function
which does not return any value. We also use the void data type to specify empty parameters of a
function.
Enumerated data type
An enumerated data type is a user-defined data type that consists of integer constants and each
integer constant is given a name. The keyword "enum" is used to define the enumerated data
type.
Derived data types
Derived data types are user-defined data types. The derived data types are also called as user-
defined data types or secondary data types. In the c programming language, the derived data types
are created using the following concepts...
 Arrays
 Structures
 Unions
 Enumeration
#include <stdio.h>
int main()
{
printf("sizeof(char) = %d\n\n", sizeof(char));
printf("sizeof(short) = %d\n", sizeof(short));
printf("sizeof(int) = %d\n", sizeof(int));
C Programming – Unit 3 BCA-TU [email protected]

printf("sizeof(long) = %d\n", sizeof(long));


printf("sizeof(long long) = %d\n\n", sizeof(long long));
printf("sizeof(float) = %d\n", sizeof(float));
printf("sizeof(double) = %d\n", sizeof(double));
printf("sizeof(long double) = %d\n", sizeof(long double));
return 0;
}

C Variables
Variables in a c programming language are the named memory locations where the user can store
different values of the same datatype during the program execution. That means a variable is a
name given to a memory location in which we can store different values of the same data type. In
other words, a variable can be defined as a storage container to hold values of the same datatype
during the program execution.
The formal definition of a data type is as follows...

Variable is a name given to a memory location where we can store different values of the same
datatype during the program execution.

Every variable in c programming language must be declared in the declaration section before it is
used. Every variable must have a datatype that determines the range and type of values be stored
and the size of the memory to be allocated.

A variable name may contain letters, digits and underscore symbol.


The following are the rules to specify a variable name...
 Variable name should not start with a digit.
 Keywords should not be used as variable names.
 A variable name should not contain any special symbols except underscore (_).
 A variable name can be of any length but compiler considers only the first 31 characters of
the variable name.
Declaration of Variable
Declaration of a variable tells the compiler to allocate the required amount of memory with the
specified variable name and allows only specified datatype values into that memory location. In C
C Programming – Unit 3 BCA-TU [email protected]

programming language, the declaration can be performed either before the function as global
variables or inside any block or function. But it must be at the beginning of block or function.
Declaration Syntax:

datatype variableName;

Example

int number;

The above declaration tells to the compiler that allocates 2 bytes of memory with the
name number and allows only integer values into that memory location.

C Constants
In C programming language, a constant is similar to the variable but the constant hold only one
value during the program execution. That means, once a value is assigned to the constant, that
value can't be changed during the program execution. Once the value is assigned to the constant,
it is fixed throughout the program. A constant can be defined as follows...
A constant is a named memory location which holds only one value throughout the program
execution.

In C programming language, a constant can be of any data type like integer, floating-point,
character, string and double, etc.,
Integer constants

An integer constant can be a decimal integer or octal integer or hexadecimal integer. A decimal
integer value is specified as direct integer value whereas octal integer value is prefixed with 'o' and
hexadecimal value is prefixed with 'OX'.

An integer constant can also be unsigned type of integer constant or long type of integer constant.
Unsigned integer constant value is suffixed with 'u' and long integer constant value is suffixed with
'l' whereas unsigned long integer constant value is suffixed with 'ul'.
Example
125 -----> Decimal Integer Constant
O76 -----> Octal Integer Constant
OX3A -----> Hexadecimal Integer Constant
50u -----> Unsigned Integer Constant
30l -----> Long Integer Constant
100ul -----> Unsigned Long Integer Constant
C Programming – Unit 3 BCA-TU [email protected]

Floating Point constants


A floating-point constant must contain both integer and decimal parts. Sometimes it may also
contain the exponent part. When a floating-point constant is represented in exponent form, the
value must be suffixed with 'e' or 'E'.
Example
The floating-point value 3.14 is represented as 3E-14 in exponent form.
Character Constants
A character constant is a symbol enclosed in single quotation. A character constant has a maximum
length of one character.
Example
'A'
'2'
'+'
In the C programming language, there are some predefined character constants called escape
sequences. Every escape sequence has its own special functionality and every escape sequence is
prefixed with '\' symbol. These escape sequences are used in output function called 'printf()'.

String Constants
A string constant is a collection of characters, digits, special symbols and escape sequences that
are enclosed in double quotations.

We define string constant in a single line as follows... "This is test"

We can define string constant using multiple lines as follows...


" This\
is\
test "

We can also define string constant by separating it with white space as follows...
"This" "is" "test"

All the above three defines the same string constant.


Creating constants in C

In a c programming language, constants can be created using two concepts...


 Using the 'const' keyword
 Using '#define' preprocessor
C Programming – Unit 3 BCA-TU [email protected]


Using the 'const' keyword
We create a constant of any datatype using 'const' keyword. To create a constant, we prefix the
variable declaration with 'const' keyword.
The general syntax for creating constant using 'const' keyword is as follows...

const datatype constantName ;


OR
const datatype constantName = value ;

Example
const int x = 10 ;
Here, 'x' is a integer constant with fixed value 10.
Example Program

#include<stdio.h>
#include<conio.h>
void main(){

int i = 9 ;
const int x = 10 ;

i = 15 ;
x = 100 ; // creates an error
printf("i = %d\nx = %d", i, x ) ;
}

The above program gives an error because we are trying to change the constant variable value (x
= 100).
Using '#define' preprocessor

We can also create constants using '#define' preprocessor directive. When we create constant using
this preprocessor directive it must be defined at the beginning of the program (because all the
preprocessor directives must be written before the global declaration).
We use the following syntax to create constant using '#define' preprocessor directive...
C Programming – Unit 3 BCA-TU [email protected]

#define CONSTANTNAME value

Example

#define PI 3.14

Here, PI is a constant with value 3.14


Example Program

#include<stdio.h>
#include<conio.h>
#defien PI 3.14
void main(){
int r, area ;
printf("Please enter the radius of circle : ") ;
scanf("%d", &r) ;
area = PI * (r * r) ;
printf("Area of the circle = %d", area) ;
}

C Output Functions
C programming language provides built-in functions to perform output operation. The output
operations are used to display data on user screen (output screen) or printer or any file. The c
programming language provides the following built-in output functions...
 printf()
 putchar()
 puts()
 fprintf()
C Programming – Unit 3 BCA-TU [email protected]

printf() function
The printf() function is used to print string or data values or a combination of string and data values
on the output screen (User screen). The printf() function is built-in function defined in a header
file called "stdio.h". When we want to use printf() function in our program we need to include the
respective header file (stdio.h) using the #include statement. The printf() function has the
following syntax...
Syntax:

printf("message to be display!!!");

Example Program

#include<stdio.h>
#include<conio.h>
void main(){
printf("Hello! Welcome to btechsmartclass!!!");
}

Output:

In the above example program, we used the printf() function to print a string on to the output
screen.

The printf() function is also used to display data values. When we want to display data values we
use format string of the data value to be displayed.
Syntax:
printf("format string",variableName);
Example Program
#include<stdio.h>
#include<conio.h>
void main(){
int i = 10;
float x = 5.5;
C Programming – Unit 3 BCA-TU [email protected]

printf("%d %f",i, x);

}
In the above example program, we used the printf() function to print data values of variables i and
x on to the output screen. Here i is a an integer variable so we have used format string %d and x is
a float variable so we have used format string %f.

The printf() function can also be used to display string along with data values.
Syntax:
printf("String format string",variableName);
Example Program
#include<stdio.h>
#include<conio.h>

void main(){
int i = 10;
float x = 5.5;
printf("Integer value = %d, float value = %f",i, x);

}
In the above program, we are displaying string along with data values.

Every function in the C programming language must have a return value. The printf() function
also have an integer as a return value. The printf() function returns an integer value equivalent to
the total number of characters it has printed.
Example Program
#include<stdio.h>
#include<conio.h>

void main(){
int i;
C Programming – Unit 3 BCA-TU [email protected]

i = printf("btechsmartclass");
printf(" is %d number of characters.",i);

}
Output:

In the above program, first printf() function printing "btechsmartclass" which is of 15 characters.
So it returns integer value 15 to the variable "i". The value of "i" is printed in the second printf()
function.
Formatted printf() function
Generally, when we write multiple printf() statements the result is displayed in a single line
because the printf() function displays the output in a single line. Consider the following example
program...
Example Program
#include<stdio.h>
#include<conio.h>

void main(){
printf("Welcome to ");
printf("btechsmartclass ");
printf("the perfect website for learning");

}
Output:

In the above program, there are 3 printf() statements written in different lines but the output is
displayed in single line only.

To display the output in different lines or as we wish, we use some special characters called escape
sequences. Escape sequences are special characters with special functionality used in printf()
function to format the output according to the user requirement. In the C programming language,
we have the following escape sequences...
C Programming – Unit 3 BCA-TU [email protected]

Escape sequence Meaning

\n Moves the cursor to New Line

\t Inserts Horizontal Tab (5 characters space)

\v Inserts Vertical Tab (5 lines space)

\a Beep sound

\b Backspace (removes the previous character from its current position)

\\ Inserts Backward slash symbol

\? Inserts Question mark symbol

\' Inserts Single quotation mark symbol

\" Inserts Double quotation mark symbol

Consider the following example program...


Example Program
#include<stdio.h>
#include<conio.h>

void main(){
printf("Welcome to\n");
printf("btechsmartclass\n");
printf("the perfect website for learning");

}
Output:
C Programming – Unit 3 BCA-TU [email protected]

putchar() function
The putchar() function is used to display a single character on the output screen. The putchar()
functions prints the character which is passed as a parameter to it and returns the same character
as a return value. This function is used to print only a single character. To print multiple characters
we need to write multiple times or use a looping statement. Consider the following example
program...
Example Program
#include<stdio.h>
#include<conio.h>

void main(){
char ch = 'A';
putchar(ch);

}
Output:

puts() function
The puts() function is used to display a string on the output screen. The puts() functions prints a
string or sequence of characters till the newline. Consider the following example program...
Example Program
#include<stdio.h>
#include<conio.h>

void main(){
char name[30];
printf("\nEnter your favourite website: ");
gets(name);
puts(name);
}
C Programming – Unit 3 BCA-TU [email protected]

Output:

fprintf() function
The fprintf() function is used with the concept of files. The fprintf() function is used to print a line
into the file. When you want to use fprintf() function the file must be opened in writing mode.
C Escape Sequence
An escape sequence is a sequence of characters used in formatting the output and are not displayed
while printing text on to the screen, each having its own specific function.

All the escape sequences in C are represented by 2 or more characters, one compulsorily
being backslash (\) and the other any character present in the C character set.
Here is a table which illustrates the use of escape sequences in C:
\n (New line) – We use it to shift the cursor control to the new line
\t (Horizontal tab) – We use it to shift the cursor to a couple of spaces to the right in the same line.
\a (Audible bell) – A beep is generated indicating the execution of the program to alert the user.
\r (Carriage Return) – We use it to position the cursor to the beginning of the current line.
\\ (Backslash) – We use it to display the backslash character.
\’ (Apostrophe or single quotation mark) – We use it to display the single-quotation mark.
\” (Double quotation mark)- We use it to display the double-quotation mark.
\0 (Null character) – We use it to represent the termination of the string.
\? (Question mark) – We use it to display the question mark. (?)
\nnn (Octal number)- We use it to represent an octal number.
\xhh (Hexadecimal number) – We use it to represent a hexadecimal number.
\v (Vertical tab)
\b (Backspace)
\e (Escape character)
\f (Form Feed page break)

#include<stdio.h>
C Programming – Unit 3 BCA-TU [email protected]

int main()
{
/* To illustrate the use of \n escape sequence */
printf("Welcome\v");
printf("to\n");
printf("DataFlair\v");
printf("tutorials!\n");
/* To illustrate the use of \n escape sequence */
printf("Welcome\tto\tDataFlair\ttutorials!");
/* To illustrate the use of \v escape sequence */
printf("Welcome\vto\vDataFlair\vtutorials!");
return 0;
}

You might also like