You are on page 1of 58

Introduction to Language & Expressions

What is C?

C is a compiler based programming language supports both high level and low level statements to
interact directly with the hardware.

Development of C Language

The C programming language evolved from a succession of programming languages developed at Bell
Laboratories in early 1970s. It was not until the late 1970s that this programming language began to
gain widespread popularity and support. This was because until that time C compilers were not readily
available for commercial use outside of Bell Laboratories.

The C language was the outcome of Dennis Ritchies work on a project in Bell Laboratories, to invent a
suitable high level language for writing an Operating System which manages the input and output
devices of a computer, allocates its storage and schedules the running of other programs.

UNIX operating system is written in the C language. Hence the Unix Operating system has C as its
standard programming language. In fact over 90% of the operating system itself is written in the C
language. So originally C language was designed and implemented on the Unix Operating System.

C as a general purpose Language


C is a high level, procedural/structured, and general purpose programming language and resembles
few other high level languages such as Fortran, Pascal, and PL/1. However, we cannot call the C
language as a Purely High Level Language.

C stands somewhere between the high-level languages meant for carrying on special activities and the
low level languages such as assembly language of a machine because of some features like System
Independence, Limited Data Type, High Flexibility, it is considered as a powerful language C has
also become popular because of its portability across systems.

History of C
Year Language Developed by Remarks
1960 ALGOL International Committee Too general, Too abstract
1963 CPL Cambridge University Hard to learn, Difficult to implement
Could deal with only specific
1967 BCPL Martin Richards
problems
Could deal with only specific
1970 B Ken Thompson AT & T Bell Labs
problems

Gayatri Vidya Parishad Degree College


Lost generality of BCPL and B
1972 C Dennis Ritchie AT & T Bell Labs
restored
Early 80s C++ Bjarne Stroustrup AT & T Introduces OOPs to C.

Features of C
- Simple, versatile, general purpose language
- Programs are fast and efficient
- Has got rich set of operators
- more general and has no restrictions
- can easily manipulates with bits, bytes and addresses
- Varieties of data types are available
- separate compilation of functions is possible and such functions can be called by any C program
- block-structured language
- Can be applied in System programming areas like operating systems, compilers & Interpreters,
Assemblers etc.,

II. Programming Basics


Components of a program

1. Constants
2. Variables
3. Operators
4. Statements
So, before writing serious programming we must be clear with all the above components of programs.
According to above example every program is a set of statements, and statement is an instruction to
the computer, which is a collection of constants, variables, operators and statements.

Constants
A constant is a fixed value, which never altered during the execution of a program.
Constants can be divided into two major categories:
1. Primary Constants
2. Secondary Constants

Data Types
The kind of data that the used variables can hold in a programming language is known as the data
type.
Basic data types are as follows:
1. Numeric Data Type
2. Non-Numeric Data Type
3. Integer Data Type

Gayatri Vidya Parishad Degree College


4. Real Data Type
5. Logical Data Type
6. Enumerated Data Type
1. Numeric Data Type: Totally deals with the numbers. These numbers can be of integer (int) data
type or real (float) data type.

2. Non-Numeric Data Type : Totally deals with characters. Any character or group of characters
enclosed within quotes will be considered as non-numeric or character data type.

3. Integer Data Type : Deals with integers or whole numbers. All arithmetic operations can be
achieved through this data type and the results are again integers.

4. Real Data Type : deals with real numbers or the numeric data, which includes fractions. All
arithmetic operations can be achieved through this data type and the results can be real data type.

5. Logical or Boolean Data Type : can hold only either of the two values TRUE or FALSE at a time. In
computer, a 1 (one) is stored for TRUE and a 0 (zero) is stored for FALSE.

6. Enumerated Data Type : Includes the unstructured data grouped together to lead to a new type.
This data type is not standard and us usually defined by user.
Ex.
Week_days = { sun, mon, tue, wed, thu, fri, sat };
Directions = {North, East, West, South };

C - Basic Syntax
Basic Structure of C Programs
C programs are essentially constructed in the following manner, as a number of well defined
sections.
/* HEADER SECTION */
/* Contains name, author, revision number*/

/* INCLUDE SECTION */
/* contains #include statements */

/* CONSTANTS AND TYPES SECTION */


/* contains types and #defines */

/* GLOBAL VARIABLES SECTION */


/* any global variables declared here */

/* FUNCTIONS SECTION */
/* user defined functions */

Gayatri Vidya Parishad Degree College


/* main() SECTION */

int main()
{

}
Adhering to a well defined structured layout will make your programs
easy to read
easy to modify
consistent in format
self documenting

Structure of a C program

<return type> main( arg-list )


{
<declaration part>

<Statement block>

<Return Values >


}
HEADER FILES
Header files contain definitions of functions and variables which can be incorporated into any C
program by using the pre-processor #include statement. Standard header files are provided with each
compiler, and cover a range of areas, string handling, mathematical, data conversion, printing and
reading of variables.
To use any of the standard functions, the appropriate header file should be included. This is done at
the beginning of the C source file. For example, to use the function printf() in a program, the line

#include <stdio.h>

should be at the beginning of the source file, because the definition for printf() is found in the
file stdio.h All header files have the extension .h and generally reside in the /include subdirectory.

#include <stdio.h>
#include "mydecls.h"

Gayatri Vidya Parishad Degree College


The use of angle brackets <> informs the compiler to search the compilers include directory for the
specified file. The use of the double quotes "" around the filename inform the compiler to search in
the current directory for the specified file.

I/O Statements
Print
This statement displays the given literal / prompt / identifiers on the screen with the given format.
Syntax:
printf(<"prompt/literal/format id/esc char. ">, id1,id2, .....);
E.g.:
printf("Hello");
printf("Student number : %d", sno);
printf("Student name : %s", name);
printf("3Subjects Marks : %d, %d, %d", m1, m2, m3);

1. Program to print a message:


/* 02_print.c */
#include <stdio.h>
int main( )
{
printf("Hello");
return 0;
}
Escape Characters
Common Escape Sequences

Escape Sequence Character


\a Bell(beep)
\b Backspace
\f Form feed
\n New line
\r Return
\t Tab
\\ Backslash
\ Single quotation mark
\ Double quotation marks
\xdd Hexadecimal representation

2. Program to print a message in a new line

Gayatri Vidya Parishad Degree College


- Compare with the last program.

/* 03_esc.c */
#include <stdio.h>
int main()
{
printf("\nHello");
return 0;
}
3. Program to display address of a person
- Multiple statements in main
/* 04_multi.c */
#include <stdio.h>
int main()
{
printf("\nName of the Person");
printf("\nStreet, Apartment//House No. ");
printf("\nzip, City");
printf("\nCountry");
return 0;
}
Scanf
Using this statement we can accept and values to variables during the execution of the program.
Syntax:
scanf(<format id/esc char">, id1,id2, .....);
Eg.
scanf("%d", &sno);
scanf("%s", name);
scanf("%d%d%d", &m1, &m2, &m3);

6. Program to find the sum of two value using scanf


- When you run the program it shows you the cursor and waits for your input, enter a numeric value
and press "Return", do this twice and you will get the output.

/* 07_scanf.c */
#include <stdio.h>
int main()
{
int a , b, c; scanf("%d", &a);
scanf("%d", &b);
c = a + b;

Gayatri Vidya Parishad Degree College


printf("\nSum is %d", c);
return 0;
}
7. Program to find the sum of two values with message display
- Messages are optional but introduces user-friendly interaction
- Compare with the last program

/* 08_sum.c */
#include <stdio.h>
int main()
{
int a , b, c; printf("Enter A value "); scanf("%d", &a);
printf("Enter B value "); scanf("%d", &b);
c = a + b;
printf("\nSum is %d", c);
return 0;
}
8. Program to find the result of ( a+ b )2
- Similar to sum of two values program but the formulae is different
/* 09_formula.c */
#include <stdio.h>
int main()
{
int a, b, c;
printf("Enter A value "); scanf("%d", &a);
printf("Enter B value "); scanf("%d", &b);
c = a * a + b * b + 2 * a * b;

printf("Result is %d", c);


return 0;
}

9. Program to find the annual salary of an employee


- input : eno, name, sal
- Process : Asal = sal * 12
- Output : Eno, name, sal, asal
- This program introduces the different types of variable

/* 10_emp.c */
#include <stdio.h>
int main()
{
int eno;

Gayatri Vidya Parishad Degree College


char name[10]; /* name with 10 characters width */
float sal, asal; /* sal & asal as real values */
printf("Enter Employee number "); scanf("%d", &eno);
printf("Enter Employee name "); scanf("%s", name);
printf("Enter Employee salary "); scanf("%f", &sal);

asal = sal * 12;


printf("\nEmployee number %d", eno);
printf("\nEmployee name %s", name);
printf("\nEmployee salary %f", sal);
printf("\nAnnual Salary %f", asal);
return 0;
}
10. Write a program to find the total and average marks of a student
- Input : Sno, name, sub1, sub2, sub3
- process : total = sub1 + sub2 + sub3; avg = total / 3
- output : sno, name, total, avg
- Similar to the above program just accept, process, and print the values

/* 11_stud.c */
#include <stdio.h>
int main()
{
int sno, sub1, sub2, sub3, total;
char name[10];
float avg;

clrscr(); /* clear the screen before its output */


printf("Enter Student number "); scanf("%d", &sno);
printf("Enter Student name "); scanf("%s", name);
printf("Enter Subject1 marks "); scanf("%d", &sub1);
printf("Enter Subject2 marks "); scanf("%d", &sub2);
printf("Enter Subject3 marks "); scanf("%d", &sub3);

total = sub1 + sub2 + sub3;


avtg = total / 3;

printf("\nStudent number %d", sno);


printf("\nStudent name %s", name);
printf("\nTotal marks %d", total);
printf("\nAverage marks %f" , avg);
return 0;
}

Gayatri Vidya Parishad Degree College


More IO Statements
Gets:
To accept a string from the key board. It accepts string value up to the carriage return.
Syntax:
gets( <id.> );
E.g.:
gets(name);
gets(street);
puts
It displays the given string value on the screen.
Syntax:
puts( <id.> / <prompt>);
E.g.:
puts(name);
puts(street);

getch - Read char without echo


getche - read char with echo
getchar - read char and accept carriage return
putch
It can print a character on the screen.
Syntax:
putch(<char>).
E.g.:
putch(a);
putch(65);

getch
It accepts a character from console.
Syntax:
char = getch().
E.g.:
ch = getch();
option = getch();

You have seen the basic structure of a C program, so it will be easy to understand other basic building
blocks of the C programming language.

Gayatri Vidya Parishad Degree College


Tokens in C

A C program consists of various tokens and a token is either a keyword, an identifier, a constant, a
string literal, or a symbol. For example, the following C statement consists of five tokens

print("Hello, World! \n");

The individual tokens are

print
(
"Hello, World! \n"
)
;

Semicolons

In a C program, the semicolon is a statement terminator. That is, each individual statement must be
ended with a semicolon. It indicates the end of one logical entity.

Given below are two different statements

print("Hello, World! \n");


return 0;

Comments

Comments are like helping text in your C program and they are ignored by the compiler. They start
with /* and terminate with the characters */ as shown below

/* my first program in C */
You cannot have comments within comments and they do not occur within a string or character
literals.

Identifiers

A C identifier is a name used to identify a variable, function, or any other user-defined item. An
identifier starts with a letter A to Z, a to z, or an underscore '_' followed by zero or more letters,
underscores, and digits (0 to 9).

Gayatri Vidya Parishad Degree College


C does not allow punctuation characters such as @, $, and % within identifiers. C is a case-
sensitive programming language. Thus, Manpower and manpower are two different identifiers in C.
Here are some examples of acceptable identifiers

mohd zara abc move_name a_123


myname50 _temp j a23b9 retVal

Keywords

The following list shows the reserved words in C. These reserved words may not be used as constants
or variables or any other identifier names.
auto else long switch
break enum register typedef
case extern return union
char float short unsigned
const for signed void
continue goto sizeof volatile
default if static while
do int struct _Packed
double

Whitespace in C

A line containing only whitespace, possibly with a comment, is known as a blank line, and a C compiler
totally ignores it.

Whitespace is the term used in C to describe blanks, tabs, newline characters and comments.
Whitespace separates one part of a statement from another and enables the compiler to identify
where one element in a statement, such as int, ends and the next element begins. Therefore, in the
following statement

int age;

there must be at least one whitespace character (usually a space) between int and age for the
compiler to be able to distinguish them. On the other hand, in the following statement

fruit = apples + oranges; // get the total fruit

no whitespace characters are necessary between fruit and =, or between = and apples, although you
are free to include some if you wish to increase readability.

Gayatri Vidya Parishad Degree College


C - Data Types
DATA TYPES AND CONSTANTS
The four basic data types are
INTEGER
These are whole numbers, both positive and negative. Unsigned integers (positive values only)
are supported. In addition, there are short and long integers.
The keyword used to define integers is,
int

An example of an integer value is 32. An example of declaring an integer variable called sum is,

int sum;
sum = 20;

FLOATING POINT
These are numbers which contain fractional parts, both positive and negative. The keyword
used to define float variables is,
float

An example of a float value is 34.12. An example of declaring a float variable called money is,
float money;
money = 0.12;

DOUBLE
These are exponetional numbers, both positive and negative. The keyword used to define
double variables is,

double

An example of a double value is 3.0E2. An example of declaring a double variable called big is,
double big;
big = 312E+7;

CHARACTER
These are single characters. The keyword used to define character variables is,
char

Gayatri Vidya Parishad Degree College


An example of a character value is the letter A. An example of declaring a character variable
called letter is,
char letter;
letter = 'A';
Note the assignment of the character A to the variable letter is done by enclosing the value
in single quotes. Remember the golden rule: Single character - Use single quotes.

Sample program illustrating each data type

#include < stdio.h >

main()
{
int sum;
float money;
char letter;
double pi;

sum = 10; /* assign integer value */


money = 2.21; /* assign float value */
letter = 'A'; /* assign character value */
pi = 2.01E6; /* assign a double value */

printf("value of sum = %d\n", sum );


printf("value of money = %f\n", money );
printf("value of letter = %c\n", letter );
printf("value of pi = %e\n", pi );
}

Sample program output


value of sum = 10
value of money = 2.210000
value of letter = A
value of pi = 2.010000e+06

Data types in c refer to an extensive system used for declaring variables or functions of
different types. The type of a variable determines how much space it occupies in storage and how the
bit pattern stored is interpreted.

The types in C can be classified as follows


S.N.O Types & Description

Gayatri Vidya Parishad Degree College


Basic Types
1 They are arithmetic types and are further classified into: (a) integer types and (b)
floating-point types.
Enumerated types

2 They are again arithmetic types and they are used to define variables that can only
assign certain discrete integer values throughout the program.

The type void


3 The type specifier void indicates that no value is available.

Derived types
4 They include (a) Pointer types, (b) Array types, (c) Structure types, (d) Union types and
(e) Function types.
The array types and structure types are referred collectively as the aggregate types. The type of a
function specifies the type of the function's return value. We will see the basic types in the following
section, where as other types will be covered in the upcoming chapters.

Integer Types

The following table provides the details of standard integer types with their storage sizes and value
ranges
Type Storage size Value range
char 1 byte -128 to 127 or 0 to 255
unsigned char 1 byte 0 to 255
signed char 1 byte -128 to 127
-32,768 to 32,767 or -2,147,483,648 to
Int 2 or 4 bytes
2,147,483,647
unsigned int 2 or 4 bytes 0 to 65,535 or 0 to 4,294,967,295
short 2 bytes -32,768 to 32,767
unsigned short 2 bytes 0 to 65,535
long 4 bytes -2,147,483,648 to 2,147,483,647
unsigned long 4 bytes 0 to 4,294,967,295
To get the exact size of a type or a variable on a particular platorm, you can use the sizeof operator.
The expressions sizeof(type) yields the storage size of the object or type in bytes. Given below is an
example to get the size of int type on any machine

#include <stdio.h>
#include <limits.h>

Gayatri Vidya Parishad Degree College


int main() {
print("Storage size for int : %d \n", sizeof(int));
return 0;
}

When you compile and execute the above program, it produces the following result on Linux

Storage size for int : 4

Floating-Point Types

The following table provide the details of standard floating-point types with storage sizes and value
ranges and their precision
Type Storage size Value range Precision
float 4 byte 1. 2E-38 to 3.4E+38 6 decimal places
double 8 byte 2. 3E-308 to 1.7E+308 15 decimal places
long double 10 byte 3. 4E-4932 to 1.1E+4932 19 decimal places

The header file float.h defines macros that allow you to use these values and other details about the
binary representation of real numbers in your programs. The following example prints the storage
space taken by a float type and its range values

#include <stdio.h>
#include <float.h>
int main() {
print("Storage size for float : %d \n", sizeof(float));
print("Minimum float positive value: %E\n", FLT_MIN );
print("Maximum float positive value: %E\n", FLT_MAX );
print("Precision value: %d\n", FLT_DIG );
return 0;
}

When you compile and execute the above program, it produces the following result on Linux

Storage size for float : 4


Minimum float positive value: 1.175494E-38

Gayatri Vidya Parishad Degree College


Maximum float positive value: 3.402823E+38
Precision value: 6

The void Type

The void type specifies that no value is available. It is used in three kinds of situations
S.N.0 Types & Description
Function returns as void
There are various functions in C which do not return any value or you can say they return
1 void. A function with no return value has the return type as void. For example, void exit
(int status);

Function arguments as void


There are various functions in C which do not accept any parameter. A function with no
2
parameter can accept a void. For example, int rand(void);

Pointers to void
A pointer of type void * represents the address of an object, but not its type. For example,
3 a memory allocation function void *malloc( size_t size ); returns a pointer to void which
can be casted to any data type.

C - Variables
A variable is nothing but a name given to a storage area that our programs can manipulate. Each
variable in C has a specific type, which determines the size and layout of the variable's memory; the
range of values that can be stored within that memory; and the set of operations that can be applied
to the variable.

The name of a variable can be composed of letters, digits, and the underscore character. It must begin
with either a letter or an underscore. Upper and lowercase letters are distinct because C is case-
sensitive. Based on the basic types explained in the previous chapter, there will be the following basic
variable types

Type Description
char Typically a single octet(one byte). This is an integer type.
int The most natural size of integer for the machine.
float A single-precision floating point value.
double A double-precision floating point value.
void Represents the absence of type.

Gayatri Vidya Parishad Degree College


C programming language also allows to define various other types of variables, which we will cover in
subsequent chapters like Enumeration, Pointer, Array, Structure, Union, etc. For this chapter, let us
study only basic variable types.

Variable Definition in C

A variable definition tells the compiler where and how much storage to create for the variable. A
variable definition specifies a data type and contains a list of one or more variables of that type as
follows

type variable_list;
Here, type must be a valid C data type including char, w_char, int, float, double, bool, or any user-
defined object; and variable_list may consist of one or more identifier names separated by commas.
Some valid declarations are shown here

int i, j, k;
char c, ch;
float f, salary;
double d;
The line int i, j, k; declares and defines the variables i, j, and k; which instruct the compiler to create
variables named i, j and k of type int.

Variables can be initialized (assigned an initial value) in their declaration. The initializer consists of an
equal sign followed by a constant expression as follows

type variable_name = value;


Some examples are

extern int d = 3, f = 5; // declaration of d and f.


int d = 3, f = 5; // definition and initializing d and f.
byte z = 22; // definition and initializes z.
char x = 'x'; // the variable x has the value 'x'.
For definition without an initializer: variables with static storage duration are implicitly initialized with
NULL (all bytes have the value 0); the initial value of all other variables are undefined.

Variable Declaration in C

A variable declaration provides assurance to the compiler that there exists a variable with the given
type and name so that the compiler can proceed for further compilation without requiring the
complete detail about the variable. A variable definition has its meaning at the time of compilation
only, the compiler needs actual variable definition at the time of linking the program.

Gayatri Vidya Parishad Degree College


A variable declaration is useful when you are using multiple files and you define your variable in one of
the files which will be available at the time of linking of the program. You will use the
keyword extern to declare a variable at any place. Though you can declare a variable multiple times in
your C program, it can be defined only once in a file, a function, or a block of code.

Example

Try the following example, where variables have been declared at the top, but they have been defined
and initialized inside the main function

#include <stdio.h>
// Variable declaration:
extern int a, b;
extern int c;
extern float f;
int main () {
/* variable definition: */
int a, b;
int c;
float f;
/* actual initialization */
a = 10;
b = 20;
c = a + b;
print("value of c : %d \n", c);
f = 70.0/3.0;
printf("value of f : %f \n", f);
return 0;

When the above code is compiled and executed, it produces the following result

value of c : 30
value of f : 23.333334

Gayatri Vidya Parishad Degree College


The same concept applies on function declaration where you provide a function name at the time of
its declaration and its actual definition can be given anywhere else. For example

// function declaration
int func();
int main() {
// function call
int i = func();
}
// function definition
int func() {
return 0;
}

L values and R values in C

There are two kinds of expressions in C


lvalue Expressions that refer to a memory location are called "lvalue" expressions. An lvalue
may appear as either the left-hand or right-hand side of an assignment.
rvalue The term rvalue refers to a data value that is stored at some address in memory. An
rvalue is an expression that cannot have a value assigned to it which means an rvalue may
appear on the right-hand side but not on the left-hand side of an assignment.
Variables are lvalues and so they may appear on the left-hand side of an assignment. Numeric literals
are rvalues and so they may not be assigned and cannot appear on the left-hand side. Take a look at
the following valid and invalid statements

int g = 20; // valid statement


10 = 20; // invalid statement; would generate compile-time error
C variable is a named location in a memory where a program can manipulate the data. This location is
used to hold the value of the variable.
The value of the C variable may get change in the program.
C variable might be belonging to any of the data type like int, float, char etc.
RULES FOR NAMING C VARIABLE:
1.Variable name must begin with letter or underscore.
2.Variables are case sensitive

Gayatri Vidya Parishad Degree College


3.They can be constructed with digits, letters.
4.No special symbols are allowed other than underscore.
5.sum, height, _value are some examples for variable name
DECLARING & INITIALIZING C VARIABLE:
Variables should be declared in the C program before to use.
Memory space is not allocated for a variable while declaration. It happens only on variable definition.
Variable initialization means assigning a value to the variable.
Type Syntax
data_type variable_name;
Variable declaration
Example: int x, y, z; char flat, ch;
data_type variable_name = value;
Variable initialization Example: int x = 50, y = 30; char flag = x, ch=l;

INITIALIZING DATA VARIABLES AT DECLARATION TIME


Unlike PASCAL, in C variables may be initialized with a value when they are declared. Consider the
following declaration, which declares an integer variable count which is initialized to 10.

int count = 10;

SIMPLE ASSIGNMENT OF VALUES TO VARIABLES


The = operator is used to assign values to data variables. Consider the following statement, which
assigns the value 32 an integer variable count, and the letter A to the character variable letter

count = 32;
letter = 'A';

THE VALUE OF VARIABLES AT DECLARATION TIME


Lets examine what the default value a variable is assigned when its declared. To do this, lets consider
the following program, which declares two variables, count which is an integer, and letter which is a
character.
Neither variable is pre-initialized. The value of each variable is printed out using a printf() statement.

#include <stdio.h>

main()
{
int count;
char letter;

Gayatri Vidya Parishad Degree College


printf("Count = %d\n", count);
printf("Letter = %c\n", letter);
}

Sample program output


Count = 26494
Letter = f

It can be seen from the sample output that the values which each of the variables take on at
declaration time are no-zero. In C, this is common, and programmers must ensure that variables are
assigned values before using them.
If the program was run again, the output could well have different values for each of the variables. We
can never assume that variables declare in the manner above will take on a specific value.
Some compilers may issue warnings related to the use of variables, and Turbo C from Borland issues
the following warning,

possible use of 'count' before definition in function main

RADIX CHANGING
Data numbers may be expressed in any base by simply altering the modifier, e.g., decimal, octal, or
hexadecimal. This is achieved by the letter which follows the % sign related to the printf argument.

#include <stdio.h>

main() /* Prints the same value in Decimal, Hex and Octal */


{
int number = 100;

printf("In decimal the number is %d\n", number);


printf("In hex the number is %x\n", number);
printf("In octal the number is %o\n", number);
/* what about %X\n as an argument? */
}

Sample program output


In decimal the number is 100
In hex the number is 64
In octal the number is 144
Note how the variable number is initialized to zero at the time of its declaration.

Gayatri Vidya Parishad Degree College


DEFINING VARIABLES IN OCTAL AND HEXADECIMAL
Often, when writing systems programs, the programmer needs to use a different number base rather
than the default decimal.
Integer constants can be defined in octal or hex by using the associated prefix, e.g., to define an
integer as an octal constant use %o
int sum = %o567;

To define an integer as a hex constant use %0x


int sum = %0x7ab4;
int flag = %0x7AB4; /* Note upper or lowercase hex ok */

MORE ABOUT FLOAT AND DOUBLE VARIABLES


C displays both float and double variables to six decimal places. This does NOT refer to the precision
(accuracy) of which the number is actually stored, only how many decimal places printf() uses to
display these variable types.

The following program illustrates how the different data types are declared and displayed,

#include <stdio.h>

main()
{
int sum = 100;
char letter = 'Z';
float set1 = 23.567;
double num2 = 11e+23;

printf("Integer variable is %d\n", sum);


printf("Character is %c\n", letter);
printf("Float variable is %f\n", set1);
printf("Double variable is %e\n", num2);
}

Sample program output


Integer variable is 100
Character variable is Z
Float variable is 23.567000
Double variable is 11.000000e23
To change the number of decimal places printed out for float or double variables, modify the %f or %e
to include a precision value, eg,

Gayatri Vidya Parishad Degree College


printf("Float variable is %.2f\n", set1 );

In this case, the use of %.2f limits the output to two decimal places, and the output now looks like
Sample program output
Integer variable is 100
Character variable is Z
Float variable is 23.56
Double variable is 11.000000e23

THERE ARE THREE TYPES OF VARIABLES IN C PROGRAM THEY ARE,


1.Local variable
2.Global variable
3.Environment variable
1. EXAMPLE PROGRAM FOR LOCAL VARIABLE IN C:
The scope of local variables will be within the function only.
These variables are declared within the function and cant be accessed outside the function.
In the below example, m and n variables are having scope within the main function only. These are
not visible to test function.
Like wise, a and b variables are having scope within the test function only. These are not visible to
main function.
#include<stdio.h>
void test();

int main()
{
int m = 22, n = 44;
// m, n are local variables of main function
/*m and n variables are having scope
within this main function only.
These are not visible to test funtion.*/
/* If you try to access a and b in this function,
you will get 'a' undeclared and 'b' undeclared error */
print("\nvalues : m = %d and n = %d", m, n);
test();
}

void test()
{
int a = 50, b = 80;
// a, b are local variables of test function
/*a and b variables are having scope
within this test function only.

Gayatri Vidya Parishad Degree College


These are not visible to main function.*/
/* If you try to access m and n in this function,
you will get 'm' undeclared and 'n' undeclared
error */
print("\nvalues : a = %d and b = %d", a, b);
}

Output:
values : m = 22 and n = 44
values : a = 50 and b = 80

2. EXAMPLE PROGRAM FOR GLOBAL VARIABLE IN C:


The scope of global variables will be throughout the program. These variables can be accessed from
anywhere in the program.
This variable is defined outside the main function. So that, this variable is visible to main function and
all other sub functions.
#include<stdio.h>
void test();int m = 22, n = 44;
int a = 50, b = 80;

int main()
{
print("All variables are accessed from main function");
print("\nvalues: m=%d:n=%d:a=%d:b=%d", m,n,a,b);
test();
}

void test()
{
print("\n\nAll variables are accessed from" \
" test function");
print("\nvalues: m=%d:n=%d:a=%d:b=%d", m,n,a,b);
}

OUTPUT:

All variables are accessed from main function


values : m = 22 : n = 44 : a = 50 : b = 80
All variables are accessed from test function
values : m = 22 : n = 44 : a = 50 : b = 80

Gayatri Vidya Parishad Degree College


LOCAL AND GLOBAL VARIABLES
Local
These variables only exist inside the specific function that creates them. They are unknown to other
functions and to the main program. As such, they are normally implemented using a stack. Local
variables cease to exist once the function that created them is completed. They are recreated each
time a function is executed or called.
Global
These variables can be accessed (ie known) by any function comprising the program. They are
implemented by associating memory locations with variable names. They do not get recreated if the
function is recalled.

DEFINING GLOBAL VARIABLES

/* Demonstrating Global variables */


#include <stdio.h>
int add_numbers( void ); /* ANSI function prototype */

/* These are global variables and can be accessed by functions from this point on */
int value1, value2, value3;

int add_numbers( void )


{
auto int result;
result = value1 + value2 + value3;
return result;
}

main()
{
auto int result;
value1 = 10;
value2 = 20;
value3 = 30;
result = add_numbers();
printf("The sum of %d + %d + %d is %d\n",
value1, value2, value3, final_result);
}

Sample Program Output


The sum of 10 + 20 + 30 is 60

Gayatri Vidya Parishad Degree College


The scope of global variables can be restricted by carefully placing the declaration. They are visible
from the declaration until the end of the current source file.

#include <stdio.h>
void no_access( void ); /* ANSI function prototype */
void all_access( void );

static int n2; /* n2 is known from this point onwards */

void no_access( void )


{
n1 = 10; /* illegal, n1 not yet known */
n2 = 5; /* valid */
}

static int n1; /* n1 is known from this point onwards */

void all_access( void )


{
n1 = 10; /* valid */
n2 = 3; /* valid */
}

3. ENVIRONMENT VARIABLES IN C:
Environment variable is a variable that will be available for all C applications and C programs.
We can access these variables from anywhere in a C program without declaring and initializing in an
application or C program.
The inbuilt functions which are used to access, modify and set these environment variables are called
environment functions.
There are 3 functions which are used to access, modify and assign an environment variable in C. They
are,
1. setenv()
2. getenv()
3. putenv()

EXAMPLE PROGRAM FOR GETENV() FUNCTION IN C:


This function gets the current value of the environment variable. Let us assume that environment
variable DIR is assigned to /usr/bin/test/.

#include <stdio.h>
#include <stdlib.h>

Gayatri Vidya Parishad Degree College


int main()
{
print("Directory = %s\n",getenv("DIR"));
return 0;
}

OUTPUT:

/usr/bin/test/
EXAMPLE PROGRAM FOR SETENV() FUNCTION IN C:
This function sets the value for environment variable. Let us assume that environment variable FILE
is to be assigned /usr/bin/example.c

#include <stdio.h>
#include <stdlib.h>

int main()
{
setenv("FILE", "/usr/bin/example.c",50);
print("File = %s\n", getenv("FILE"));
return 0;
}

OUTPUT:

File = /usr/bin/example.c

EXAMPLE PROGRAM FOR PUTENV() FUNCTION IN C:


This function modifies the value for environment variable. Below example program shows that how to
modify an existing environment variable value.

#include <stdio.h>
#include <stdlib.h>

int main()
{
setenv("DIR", "/usr/bin/example/",50);
print("Directory name before modifying = " \
"%s\n", getenv("DIR"));

Gayatri Vidya Parishad Degree College


putenv("DIR=/usr/home/");
print("Directory name after modifying = " \
"%s\n", getenv("DIR"));
return 0;
}

OUTPUT:

Directory name before modifying = /usr/bin/example/


Directory name after modifying = /usr/home/

DIFFERENCE BETWEEN VARIABLE DECLARATION & DEFINITION IN C:


Variable declaration Variable definition
Declaration tells the compiler about data type and size
Definition allocates memory for the variable.
of the variable.
It can happen only one time for a variable in
Variable can be declared many times in a program.
a program.
The assignment of properties and identification to a
Assignments of storage space to a variable.
variable.

AUTOMATIC AND STATIC VARIABLES


C programs have a number of segments (or areas) where data is located. These segments are typically,
_DATA Static data
_BSS Uninitialized static data, zeroed out before call to main()
_STACK Automatic data, resides on stack frame, thus local to functions
_CONST Constant data, using the ANSI C keyword const
The use of the appropriate keyword allows correct placement of the variable onto the desired data
segment.

/* example program illustrates difference between static and automatic variables */


#include <stdio.h>
void demo( void ); /* ANSI function prototypes */

void demo( void )


{
auto int avar = 0;
static int svar = 0;

printf("auto = %d, static = %d\n", avar, svar);


++avar;

Gayatri Vidya Parishad Degree College


++svar;
}

main()
{
int i;

while( i < 3 ) {
demo();
i++;
}
}

Sample Program Output


auto = 0, static = 0
auto = 0, static = 1
auto = 0, static = 2

Sample program output

Static variables are created and initialized once, on the first call to the function. Subsequent calls to
the function do not recreate or re-initialize the static variable. When the function terminates, the
variable still exists on the _DATA segment, but cannot be accessed by outside functions.
Automatic variables are the opposite. They are created and re-initialized on each entry to the function.
They disappear (are de-allocated) when the function terminates. They are created on the _STACK
segment.
MORE ABOUT VARIABLES
Variables must begin with a character or underscore, and may be followed by any combination of
characters, underscores, or the digits 0 - 9. The following is a list of valid variable names,
summary
exit_flag
i
Jerry7
Number_of_moves
_valid_flag
You should ensure that you use meaningful names for your variables. The reasons for this are,
meaningful names for variables are self documenting (see what they do at a glance)
they are easier to understand
there is no correlation with the amount of space used in the .EXE file

Gayatri Vidya Parishad Degree College


makes programs easier to read

CLASS EXERCISE C3
Why are the variables in the following list invalid,
value$sum
exit flag
3lotsofmoney
char

VARIABLE NAMES AND PREFIXES WHEN WRITING WINDOWS OR OS/2 PROGRAMS


During the development of OS/2, it became common to add prefix letters to variable names to
indicate the data type of variables.
This enabled programmers to identify the data type of the variable without looking at its declaration,
thus they could easily check to see if they were performing the correct operations on the data type
and hopefully, reduce the number of errors.
Prefix Purpose or Type
b a byte value
c count or size
clr a variable that holds a color
f bitields or flags
h a handle
hwnd a window handle
id an identity
l a long integer
msg a message
P a Pointer
rc return value
s short integer
ul unsigned long integer
us unsigned short integer
sz a null terminated string variable
psz a pointer to a null terminated string variable
In viewing code written for Windows or OS/2, you may see variables written according to this
convention.
COMMENTS
The addition of comments inside programs is desirable. These may be added to C programs by
enclosing them as follows,

/* bla bla bla bla bla bla */

Gayatri Vidya Parishad Degree College


Note that the /* opens the comment field and */ closes the comment field. Comments may span
multiple lines. Comments may not be nested one inside another.

/* this is a comment. /* this comment is inside */ wrong */


In the above example, the first occurrence of */ closes the comment statement for the entire line,
meaning that the text wrong is interpreted as a C statement or variable, and in this example,
generates an error.
What Comments Are Used For
documentation of variables and their usage
explaining difficult sections of code
describes the program, author, date, modification changes, revisions etc
copyrighting

C - Scope Rules
A scope in any programming is a region of the program where a defined variable can have its existence
and beyond that variable it cannot be accessed. There are three places where variables can be
declared in C programming language
Inside a function or a block which is called local variables.
Outside of all functions which is called global variables.
In the definition of function parameters which are called formal parameters.
Let us understand what are local and global variables, and formal parameters.

Local Variables

Variables that are declared inside a function or block are called local variables. They can be used only
by statements that are inside that function or block of code. Local variables are not known to
functions outside their own. The following example shows how local variables are used. Here all the
variables a, b, and c are local to main() function.

#include <stdio.h>
int main () {
/* local variable declaration */
int a, b;
int c;
/* actual initialization */

Gayatri Vidya Parishad Degree College


a = 10;
b = 20;
c = a + b;
print ("value of a = %d, b = %d and c = %d\n", a, b, c);
return 0;
}

Global Variables

Global variables are defined outside a function, usually on top of the program. Global variables hold
their values throughout the lifetime of your program and they can be accessed inside any of the
functions defined for the program.

A global variable can be accessed by any function. That is, a global variable is available for use
throughout your entire program after its declaration. The following program show how global
variables are used in a program.

#include <stdio.h>
/* global variable declaration */
int g;
int main () {
/* local variable declaration */
int a, b;
/* actual initialization */
a = 10;
b = 20;
g = a + b;
print ("value of a = %d, b = %d and g = %d\n", a, b, g);
return 0;
}

A program can have same name for local and global variables but the value of local variable inside a
function will take preference. Here is an example

Gayatri Vidya Parishad Degree College


#include <stdio.h>
/* global variable declaration */
int g = 20;
int main () {
/* local variable declaration */
int g = 10;
print ("value of g = %d\n", g);
return 0;
}

When the above code is compiled and executed, it produces the following result

value of g = 10

Formal Parameters

Formal parameters, are treated as local variables with-in a function and they take precedence over
global variables. Following is an example

#include <stdio.h>
/* global variable declaration */
int a = 20;
int main () {
/* local variable declaration in main function */
int a = 10;
int b = 20;
int c = 0;
print ("value of a in main() = %d\n", a);
c = sum( a, b);
print ("value of c in main() = %d\n", c);
return 0;
}
/* function to add two integers */

Gayatri Vidya Parishad Degree College


int sum(int a, int b) {
print ("value of a in sum() = %d\n", a);
print ("value of b in sum() = %d\n", b);
return a + b;
}

When the above code is compiled and executed, it produces the following result

value of a in main() = 10
value of a in sum() = 10
value of b in sum() = 20
value of c in main() = 30

Initializing Local and Global Variables

When a local variable is defined, it is not initialized by the system, you must initialize it yourself. Global
variables are initialized automatically by the system when you define them as follows

Data Type Initial Default Value


int 0
char '\0'
float 0
double 0
pointer NULL
It is a good programming practice to initialize variables properly, otherwise your program may produce
unexpected results, because uninitialized variables will take some garbage value already available at
their memory location.
This post examines two aspects of how variables work in programming languages: The scope and
the extent of variables. Example source code is given in JavaScript, but should simple enough to be
universally understandable.

Static versus dynamic


Before we can start our examination, we need to establish how the workings of variables can be
observed. The following are two ways of looking at program code.
Statically, one examines the program as it exists in source code, without running it. Given the
following code, we can make the static assertion that function g is nested inside function f.
function f() {

Gayatri Vidya Parishad Degree College


function g() {

}
}

The adjective lexical is used synonymously with static, because both pertain to the lexicon (the
words, the source) of the program.
Dynamically, one examines what happens while executing the program (at runtime). Given
the following code, f and g have a dynamic relationship, because f invokes g.
function g() {
}
function f() {
g();
}

Variable bindings and their scope and extent

A statement
var x = ...;

establishes a binding for the variable x that maps the variable name to a value. In the following, the
terms variable and binding are often used interchangeably. This is less precise, but makes
explanations shorter. Bindings are characterized by:
Scope (a spatial property): Where can the binding be accessed?
Extent (a temporal property): How long does the binding exist?
There are several variations of implementing scope and extent in a programming language.
Scope: The direct scope of a variable is the syntactic construct in which a binding has been created.
What constructs form scopes depends on the programming language: any kind of block in most
languages, only functions in JavaScript. One has two options when it comes to determining where else
a variable is accessible, in addition to the direct scope:
Static (lexical) scoping: A variable is accessible from the direct scope and all scopes lexically
nested in it. In the following example, x is visible in its direct scope, function f, but also in the
nested scope, function g.
function f() {
var x;
function g(y) {
return x + y;
}
}

Gayatri Vidya Parishad Degree College


Dynamic scoping: In dynamic scoping, a variable declared in a function is accessible in all
invoked functions. The example below illustrates dynamic scoping. If f is invoked, which in turn
invokes g, then myvar at (*) refers to the binding in f.
function g() {
var x = myvar + 1; // (*)
}
function f() {
var myvar = 123;
g();
}

Most modern programming languages use static scoping. Some, such as Common Lisp, additionally
support dynamic scoping (for dynamically encapsulated global variables). Two effects influence
scoping:
Scopes can be nested. The direct scope can be seen as nesting all other scopes where a
variable is accessible. In that case, the nested scopes are called inner scopes, the direct scope is
called outer scope. In static scoping, nesting happens by nesting syntactic constructs. In
dynamic scoping, nesting happens by recursively invoking functions.
Variables can be shadowed. If an inner scope declares a variable with the same name as a
variable in an outer scope, the outer variable is shadowed by the inner one: it cannot be
accessed in the inner scope (or scopes nested in it), because mentions of it refer to the inner
binding. In the following example, the declaration in g shadows the declaration in f. Thus, x has
the value "bar" in g and in h.
function f() {
var x = "foo";
function g() {
var x = "bar";
function h() {
}
}
}

Extent: the most common kinds of extent are


Dynamic extent: A variable exists starting with its declaration until its existence is explicitly
ended. This usually means that the direct scope of the declaration has finished computing. To
handle nested scopes, dynamic extent is often managed via a stack of bindings. Dynamic extent
is common in simpler programming languages. JavaScript, however, can do more. Read on.
Indefinite extent: In JavaScript, the extent of a variable starts with its declaration. Its binding
exists as long as there is code that refers to it. Thus, if a function leaves its static scope, it keeps
variables in outer scopes alive if it refers to them. In the following example,
function g keeps x alive, because it leaves its static scope (the function f). Later, once there are

Gayatri Vidya Parishad Degree College


no more references to g (such as myfunc), both g and the binding for x can be garbage-
collected.
function f(x) {
function g() {
return x;
}
return g;
}
var myfunc = f("hello");
console.log(myfunc()); // output: hello

Note that there exist many different definitions of extent in the literature. We have covered just one
of them [1].

C - Constants & Literals


Constants refer to fixed values that the program may not alter during its execution. These fixed values
are also called literals.

Constants can be of any of the basic data types like an integer constant, a floating constant, a
character constant, or a string literal. There are enumeration constants as well.

Constants are treated just like regular variables except that their values cannot be modified after their
definition.

Integer Literals
An integer literal can be a decimal, octal, or hexadecimal constant. A prefix specifies the base or radix:
0x or 0X for hexadecimal, 0 for octal, and nothing for decimal.
An integer literal can also have a suffix that is a combination of U and L, for unsigned and long,
respectively. The suffix can be uppercase or lowercase and can be in any order.

Here are some examples of integer literals

212 /* Legal */
215u /* Legal */
0xFeeL /* Legal */
078 /* Illegal: 8 is not an octal digit */
032UU /* Illegal: cannot repeat a suffix */
Following are other examples of various types of integer literals

85 /* decimal */

Gayatri Vidya Parishad Degree College


0213 /* octal */
0x4b /* hexadecimal */
30 /* int */
30u /* unsigned int */
30l /* long */
30ul /* unsigned long */

Floating-point Literals
A floating-point literal has an integer part, a decimal point, a fractional part, and an exponent part.
You can represent floating point literals either in decimal form or exponential form.

While representing decimal form, you must include the decimal point, the exponent, or both; and
while representing exponential form, you must include the integer part, the fractional part, or both.
The signed exponent is introduced by e or E.

Here are some examples of floating-point literals

3.14159 /* Legal */
314159E-5L /* Legal */
510E /* Illegal: incomplete exponent */
210f /* Illegal: no decimal or exponent */
.e55 /* Illegal: missing integer or fraction */

Character Constants
Character literals are enclosed in single quotes, e.g., 'x' can be stored in a simple variable of char type.

A character literal can be a plain character (e.g., 'x'), an escape sequence (e.g., '\t'), or a universal
character (e.g., '\u02C0').

There are certain characters in C that represent special meaning when preceded by a backslash for
example, newline (\n) or tab (\t).
Here, you have a list of such escape sequence codes

Following is the example to show a few escape sequence characters

#include <stdio.h>
int main() {
print("Hello\tWorld\n\n");
return 0;
}

Gayatri Vidya Parishad Degree College


When the above code is compiled and executed, it produces the following result

Hello World

String Literals
String literals or constants are enclosed in double quotes "". A string contains characters that are
similar to character literals: plain characters, escape sequences, and universal characters.

You can break a long line into multiple lines using string literals and separating them using white
spaces.

Here are some examples of string literals. All the three forms are identical strings.

"hello, dear"

"hello, \

dear"

"hello, " "d" "ear"

Defining Constants
There are two simple ways in C to define constants
Using #define preprocessor.
Using const keyword.

The #define Preprocessor


Given below is the form to use #define preprocessor to define a constant

#define identifier value


The following example explains it in detail

#include <stdio.h>
#define LENGTH 10
#define WIDTH 5
#define NEWLINE '\n'
int main() {
int area;

Gayatri Vidya Parishad Degree College


area = LENGTH * WIDTH;
print("value of area : %d", area);
print("%c", NEWLINE);
return 0;
}

When the above code is compiled and executed, it produces the following result

value of area : 50

The const Keyword

You can use const prefix to declare constants with a specific type as follows

const type variable = value;


The following example explains it in detail

#include <stdio.h>
int main() {
const int LENGTH = 10;
const int WIDTH = 5;
const char NEWLINE = '\n';
int area;
area = LENGTH * WIDTH;
print("value of area : %d", area);
print("%c", NEWLINE);
return 0;
}

When the above code is compiled and executed, it produces the following result

value of area : 50
Note that it is a good programming practice to define constants in CAPITALS.

C - Storage Classes
A storage class defines the scope (visibility) and life-time of variables and/or functions within a C

Gayatri Vidya Parishad Degree College


Program. They precede the type that they modify. We have four different storage classes in a C
program
auto
register
static
extern

The auto Storage Class


The auto storage class is the default storage class for all local variables.

{
int mount;
auto int month;
}

The example above defines two variables with in the same storage class. 'auto' can only be used
within functions, i.e., local variables.

The register Storage Class


The register storage class is used to define local variables that should be stored in a register instead of
RAM. This means that the variable has a maximum size equal to the register size (usually one word)
and can't have the unary '&' operator applied to it (as it does not have a memory location).

{
register int miles;
}

The register should only be used for variables that require quick access such as counters. It should also
be noted that defining 'register' does not mean that the variable will be stored in a register. It means
that it MIGHT be stored in a register depending on hardware and implementation restrictions.

The static Storage Class


The static storage class instructs the compiler to keep a local variable in existence during the life-time
of the program instead of creating and destroying it each time it comes into and goes out of scope.
Therefore, making local variables static allows them to maintain their values between function calls.

Gayatri Vidya Parishad Degree College


The static modifier may also be applied to global variables. When this is done, it causes that variable's
scope to be restricted to the file in which it is declared.

In C programming, when static is used on a global variable, it causes only one copy of that member to
be shared by all the objects of its class.

#include <stdio.h>
/* function declaration */
void func(void);
static int count = 5; /* global variable */
main() {
while(count--) {
func();
}
return 0;
}
/* function definition */
void func( void ) {
static int i = 5; /* local static variable */
i++;
print("i is %d and count is %d\n", i, count);
}

When the above code is compiled and executed, it produces the following result

i is 6 and count is 4
i is 7 and count is 3
i is 8 and count is 2
i is 9 and count is 1
i is 10 and count is 0

The extern Storage Class


The extern storage class is used to give a reference of a global variable that is visible to ALL the
program files. When you use 'extern', the variable cannot be initialized however, it points the variable
name at a storage location that has been previously defined.

Gayatri Vidya Parishad Degree College


When you have multiple files and you define a global variable or function, which will also be used in
other files, then extern will be used in another file to provide the reference of defined variable or
function. Just for understanding, extern is used to declare a global variable or function in another file.

The extern modifier is most commonly used when there are two or more files sharing the same global
variables or functions as explained below.

First File: main.c

#include <stdio.h>
int count ;
extern void write_extern();
main() {
count = 5;
write_extern();
}

Second File: support.c

#include <stdio.h>
extern int count;
void write_extern(void) {
print("count is %d\n", count);
}

Here, extern is being used to declare count in the second file, where as it has its definition in the first
file, main.c. Now, compile these two files as follows

$gcc main.c support.c


It will produce the executable program a.out. When this program is executed, it produces the
following result

count is 5

C - Operators
An operator is a symbol that tells the compiler to perform specific mathematical or logical
functions. C language is rich in built-in operators and provides the following types of operators
Arithmetic Operators

Gayatri Vidya Parishad Degree College


Relational Operators
Logical Operators
Bitwise Operators
Assignment Operators
Misc Operators
We will, in this chapter, look into the way each operator works.

Arithmetic Operators

The following table shows all the arithmetic operators supported by the C language. Assume
variable A holds 10 and variable B holds 20 then

Show Examples

Operator Description Example


+ Adds two operands. A + B = 30
Subtracts second operand from the first. A B = -10
* Multiplies both operands. A * B = 200
/ Divides numerator by de-numerator. B/A=2
Modulus Operator and remainder of
% B%A=0
after an integer division.
Increment operator increases the integer
++ A++ = 11
value by one.
Decrement operator decreases the A-- = 9
--
integer value by one.
Relational Operators
The following table shows all the relational operators supported by C. Assume variable A holds 10 and
variable B holds 20 then
Show Examples
Operator Description Example
Checks if the values of two operands are equal or not. If yes, then the (A == B) is not
==
condition becomes true. true.
Checks if the values of two operands are equal or not. If the values are
!= (A != B) is true.
not equal, then the condition becomes true.
Checks if the value of left operand is greater than the value of right (A > B) is not
>
operand. If yes, then the condition becomes true. true.
< Checks if the value of left operand is less than the value of right (A < B) is true.

Gayatri Vidya Parishad Degree College


operand. If yes, then the condition becomes true.
Checks if the value of left operand is greater than or equal to the value (A >= B) is not
>=
of right operand. If yes, then the condition becomes true. true.
Checks if the value of left operand is less than or equal to the value of
<= (A <= B) is true.
right operand. If yes, then the condition becomes true.

Logical Operators

Following table shows all the logical operators supported by C language. Assume variable A holds 1
and variable B holds 0, then

Show Examples
Operator Description Example
Called Logical AND operator. If both the operands are non-zero, then the (A && B) is
&&
condition becomes true. false.
Called Logical OR Operator. If any of the two operands is non-zero, then (A || B) is
||
the condition becomes true. true.
Called Logical NOT Operator. It is used to reverse the logical state of its
!(A && B) is
! operand. If a condition is true, then Logical NOT operator will make it
true.
false.

Bitwise Operators

Bitwise operator works on bits and perform bit-by-bit operation. The truth tables for &, |, and ^ is as
follows
p q p&q p|q p^q
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
Assume A = 60 and B = 13 in binary format, they will be as follows

A = 0011 1100

B = 0000 1101

-----------------

A&B = 0000 1100

A|B = 0011 1101

A^B = 0011 0001

Gayatri Vidya Parishad Degree College


~A = 1100 0011

The following table lists the bitwise operators supported by C. Assume variable 'A' holds 60 and
variable 'B' holds 13, then

Show Examples
Operator Description Example
Binary AND Operator copies a bit to the result if it exists
& (A & B) = 12, i.e., 0000 1100
in both operands.
Binary OR Operator copies a bit if it exists in either
| (A | B) = 61, i.e., 0011 1101
operand.
Binary XOR Operator copies the bit if it is set in one
^ (A ^ B) = 49, i.e., 0011 0001
operand but not both.
Binary Ones Complement Operator is unary and has the (~A ) = -61, i.e,. 1100 0011 in
~
effect of 'flipping' bits. 2's complement form.
Binary Left Shift Operator. The left operands value is
<< moved left by the number of bits specified by the right A << 2 = 240 i.e., 1111 0000
operand.
Binary Right Shift Operator. The left operands value is
>> moved right by the number of bits specified by the right A >> 2 = 15 i.e., 0000 1111
operand.

Assignment Operators

The following table lists the assignment operators supported by the C language

Show Examples
Operator Description Example
Simple assignment operator. Assigns values from right side C = A + B will assign the
=
operands to left side operand value of A + B to C
Add AND assignment operator. It adds the right operand to C += A is equivalent to C =
+=
the left operand and assign the result to the left operand. C+A
Subtract AND assignment operator. It subtracts the right
C -= A is equivalent to C =
-= operand from the left operand and assigns the result to the
C-A
left operand.
Multiply AND assignment operator. It multiplies the right
C *= A is equivalent to C =
*= operand with the left operand and assigns the result to the
C*A
left operand.
Divide AND assignment operator. It divides the left operand
C /= A is equivalent to C =
/= with the right operand and assigns the result to the left
C/A
operand.
%= Modulus AND assignment operator. It takes modulus using C %= A is equivalent to C =

Gayatri Vidya Parishad Degree College


two operands and assigns the result to the left operand. C%A
C <<= 2 is same as C = C
<<= Left shift AND assignment operator.
<< 2
C >>= 2 is same as C = C
>>= Right shift AND assignment operator.
>> 2
C &= 2 is same as C = C &
&= Bitwise AND assignment operator.
2
^= Bitwise exclusive OR and assignment operator. C ^= 2 is same as C = C ^ 2
|= Bitwise inclusive OR and assignment operator. C |= 2 is same as C = C | 2

Misc Operators sizeof & ternary

Besides the operators discussed above, there are a few other important operators
including sizeof and ? : supported by the C Language.

Show Examples
Operator Description Example
Returns the size of a
sizeof() sizeof(a), where a is integer, will return 4.
variable.
Returns the address of a
& &a; returns the actual address of the variable.
variable.
* Pointer to a variable. *a;
?: Conditional Expression. If Condition is true ? then value X : otherwise value Y

Operators Precedence in C

Operator precedence determines the grouping of terms in an expression and decides how an
expression is evaluated. Certain operators have higher precedence than others; for example, the
multiplication operator has a higher precedence than the addition operator.

For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has a higher precedence
than +, so it first gets multiplied with 3*2 and then adds into 7.

Here, operators with the highest precedence appear at the top of the table, those with the lowest
appear at the bottom. Within an expression, higher precedence operators will be evaluated first.

Show Examples
Category Operator Associativity
Postix () [] -> . ++ - - Left to right
Unary + - ! ~ ++ - - (type)* & sizeof Right to left
Multiplicative */% Left to right

Gayatri Vidya Parishad Degree College


Additive +- Left to right
Shift << >> Left to right
Relational < <= > >= Left to right
Equality == != Left to right
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left
Comma , Left to right

FORMAT SPECIFIERS
In C programming we need lots of format specifier to work with various data types. Format
specifiers defines the type of data to be printed on standard output. Whether to print formatted
output or to take formatted input we need format specifiers. Format specifiers are also called as
format string.

Format specifiers are the operators used in print() function to print the data which is referred by an
object or a variable. when a value is stored in a particular variable, Then we cannot print the value
stored in the variable directly with out the using format specifiers. We can retrieve the data stored in
the variables and can print them on to the console screen by using these format specifiers in a print
function. Format specifiers start with a percentage(%) symbol and follows a special character to
identify the type of the data. There are basically six types of format specifiers are available in c they
are
%d
%f
%c
%s
%u
%ld
I will explain all these six format specifiers available in c clearly. Keep reading.........

Integer Format Specifier %d :-


This %d format specifier is used to represent integer values. It is used in print() function to print the
integer value stored in the variable. The value stored in a integer variable can be retrieved and printed
by using the %d format specifier. It is a reference to an integer data. When ever we need to print a
integer data, we should use %d format specifier.

Gayatri Vidya Parishad Degree College


Syntax To Use %d Integer Format Specifier:-
print("%d",<variable name>);
Here
%d is the format specifier for an integer data
variable name is the name of the integer variable
When ever we declare the print statement using above syntax, the integer variable returns the value
stored in it. Then the returned integer value is printed by using the integer format specifier %d.

Example To Use %d Integer Format Specifier:-


print("%d",a);

The above example is used to print the value stored in the variable a. Here the variable a returns a
value to the print function and the returned value is printed using the %d format specifier. For
example if there is a integer data 10 in the variable a, then after returning the value, the print
function look like
print("%d",10);

Now the returned value 10 is printed by using the %d format specifier.

Float Format Specifier %f :-


This %f format specifier is used to represent fractional values. It is used in print() function to print the
fractional or floating value stored in the variable. The value stored in a float variable can be retrieved
and printed by using the %f format specifier. It is a reference to an fractional or floating data. When
ever we need to print a fractional or floating data, we should use %f format specifier.

Syntax To Use %f Float Format Specifier:-


print("%f",<variable name>);

Here
%f is the format specifier for an floating or fractional data
variable name is the name of the float variable
When ever we declare the print statement using above syntax, the float variable returns the value
stored in it. Then the returned fractional value is printed by using the float format specifier %f.

Example To Use %f Float Format Specifier:-


print("%f",a);

The above example is used to print the value stored in the variable a. Here the variable a returns a
value to the print function and the returned value is printed using the %f format specifier. For
example if there is a fractional data 5.5 in the variable a, then after returning the value, the print

Gayatri Vidya Parishad Degree College


function look like
print("%f",5.5);

Now the returned value 5.5 is printed by using the %f format specifier.

Character Format Specifier %c :-


This %c format specifier is used to represent characters. It is used in print() function to print the
character stored in a variable. The value stored in a char variable can be retrieved and printed by using
the %c format specifier. It is a reference to a character data. When ever we need to print a character
data, we should use %c format specifier.

Syntax To Use %c Character Format Specifier:-


print("%c",<variable name>);
Here
%c is the format specifier for a character data
variable name is the name of the char variable
When ever we declare the print statement using above syntax, the char variable returns the character
stored in it. Then the returned character is printed by using the character format specifier %c.

Example To Use %c character Format Specifier:-


print("%c",a);

The above example is used to print the character stored in the variable a. Here the variable a returns a
character to the print function and the returned character is printed using the %c format specifier. For
example if there is a character 'S' in the variable a, then after returning the value, the print function
look like
print("%c",S);
Now the returned character 'S' is printed by using the %c format specifier.

String Format Specifier %s :-


This %s format specifier is used to represent strings. It is used in print() function to print a string
stored in the character array variable. A string stored in a character array variable can be retrieved and
printed by using the %s format specifier. It is a reference to a string(collection of characters) data.
When ever we need to print a string, we should use %s format specifier.

Syntax To Use %s String Format Specifier:-


print("%s",<variable name>);

Gayatri Vidya Parishad Degree College


Here
%s is the format specifier for a string
variable name is the name of the character array variable
When ever we declare the print statement using above syntax, the character array variable returns
the string stored in it. Then the returned string is printed by using the string format specifier %s.

Example To use %s String Format Specifier:-


print("%s",a);

The above example is used to print the string stored in the character array variable a. Here the
variable a returns a value to the print function and the returned value is printed using the %s format
specifier. For example if there is a string "codershunt" in the variable a, then after returning the string,
the print function look like
print("%s",codershunt);
Now the returned string "codershunt" is printed by using the %s format specifier.

Address Format Specifier %u :-


This %u format specifier is used to represent address of a variable stored in the memory. It is used in
print() function to print the memory address of a variable. When ever we need to print the memory
address of a variable, we should use %u format specifier.

Syntax To Use %u Address Format Specifier:-


print("%u",<variable name>);

Here
%u is the format specifier for representing the address of a variable
variable name is the name of the variable
When ever we declare the print statement using above syntax, Then the memory address of the
specified variable will be printed.

Example To Use %u Address Format Specifier:-


print("%u",a);

The above example is used to print the memory address of the variable a.

Long Int Format Specifier %ld :-


This %ld format specifier is used to represent long integer values. It is used in print() function to print
the long integer value stored in the variable. The value stored in a long int variable can be retrieved

Gayatri Vidya Parishad Degree College


and printed by using the %ld format specifier. It is a reference to a long integer data. When ever we
need to print a long integer data, we should use %ld format specifier.

Syntax To Use %ld Long Int Format Specifier:-


print("%ld",<variable name>);
Here
%ld is the format specifier for a long integer data
variable name is the name of the long int variable
When ever we declare the print statement using above syntax, the long int variable returns the value
stored in it. Then the returned long integer value is printed by using the long int format specifier %ld.

Example To Use %ld Long Int Format Specifier:-


print("%ld",a);

The above example is used to print the long integer value stored in the variable a. Here the variable a
returns a value to the print function and the returned long integer value is printed using the %ld
format specifier. For example if there is a long integer data 45232 in the variable a, then after
returning the value, the print function look like
print("%ld",45232);
Now the returned value 45232 is printed by using the %ld format specifier.

Rules To Be Followed While Using Print() Function :-


The message which is to be printed should be placed in between double quotes(" ").
separate the format specifiers and variables using comma (,).

The print() function should follow a semi colon at the end. This indicates the compiler that It is the
end of the statement.

As C is a case sensitive language so you should not use capital letters while writing print() function.
how ever you can use capital letters in the body of the message which is to be printed.
Here is a complete list of all format specifiers used in C programming language.

Format specifier Description Supported data types


%c Character char, unsigned char
%d Signed Integer short, unsigned short, int,
long
%e or %E Scientific notation of float values Float, double

Gayatri Vidya Parishad Degree College


%f Floating Point Float
%g or %G Similar as %e or %E Float, Double
%hi Signed Integer(Short) short
%hu Unsigned Integer(Short) Unsigned short
%i Signed Integer Short, unsigned short, int,
long
%l or %ld or %li Signed Integer long
%lf Floating point Double
%Lf Floating-point Long Double
%lu Unsigned Integer unsigned int, unsignedlong
%lli, %lld Signed Integer long long
%llu Unsigned Integer Unsignedlong, long
%o Octal representation of Integer. Short, unsignedshort,int
unsigned int, long
%p Address of pointer to void void *
void *
%s String char *
%u Unsigned Integer unsigned int, unsigned long
%x or %X Hexadecimal representation Short , unsigned short, int
of Unsigned Integer unsigned int, long
%n Prints nothing
%% Prints % character

List Of Header Files in C Programming Language

<assert.h> Conditionally compiled macro that compares its argument to zero


<complex.h> Complex number arithmetic
<ctype.h> Functions to determine the type contained in character data
<errno.h> Macros reporting error conditions
<fenv.h> Floating-point environment
<float.h> Limits of float types
<inttypes.h> Format conversion of integer types
<iso646.h> Alternative operator spellings

Gayatri Vidya Parishad Degree College


<limits.h> Sizes of basic types
<locale.h> Localization utilities
<math.h> Common mathematics functions
<setjmp.h> Non local jumps
<signal.h> Signal handling
<stdalign.h> Align as and align of convenience macros
<stdarg.h> Variable arguments
<stdatomic.h> Atomic types
<stdbool.h> Boolean type
<stddef.h> Common macro definitions
<stdint.h> Fixed-width integer types
<stdio.h> Input/output
<stdlib.h> General utilities: memory management, program utilities, string
conversions, random numbers
<stdnoreturn.h> No return convenience macros
<string.h> String handling
<tgmath.h> Type-generic math (macros wrapping math.h and complex.h)
<threads.h> Thread library
<time.h> Time/date utilities
<uchar.h> UTF-16 and UTF-32 character utilities
<wchar.h> Extended multi byte and wide character utilities
<wctype.h> Wide character classification and mapping utilities

C Standard Library Reference Tutorial


C is a general-purpose, procedural, imperative computer programming language developed in 1972 by
Dennis M. Ritchie at the Bell Telephone Laboratories to develop the Unix operating system.

C is the most widely used computer language, that keeps fluctuating at number one scale of
popularity along with Java programming language which is also equally popular and most widely used
among modern software programmers.

The C Standard Library is a set of C built-in functions, constants and header files like <stdio.h>,
<stdlib.h>, <math.h>, etc. This library will work as a reference manual for C programmers.

Gayatri Vidya Parishad Degree College


Audience
The C Standard Library is a reference for C programmers to help them in their projects related to
system programming. All the C functions have been explained in a user-friendly way and they can be
copied and pasted in your C projects.

Prerequisites
A basic understanding of the C Programming language will help you in understanding the C built-in
functions covered in this library.

C Library - <assert.h>
The assert.h header file of the C Standard Library provides a macro called assert which can be used to
verify assumptions made by the program and print a diagnostic message if this assumption is false.

The defined macro assert refers to another macro NDEBUG which is not a part of <assert.h>. If
NDEBUG is defined as a macro name in the source file, at the point where <assert.h> is included,
the assert macro is defined as follows

#define assert(ignore) ((void)0)

Library Macros

Following is the only function defined in the header assert.h


S.N.O Function & Description
void assert(int expression)
1 This is actually a macro and not a function, which can be used to add diagnostics in your
C program.

C Library - <ctype.h>
The ctype.h header file of the C Standard Library declares several functions that are useful for
testing and mapping characters.

All the functions accepts int as a parameter, whose value must be EOF or representable as an
unsigned char.

All the functions return non-zero (true) if the argument c satisfies the condition described, and
zero(false) if not.

Gayatri Vidya Parishad Degree College


Library Functions

Following are the functions defined in the header ctype.h


S.NO Function & Description
int isalnum(int c)
1
This function checks whether the passed character is alphanumeric.
int isalpha(int c)
2
This function checks whether the passed character is alphabetic.
int iscntrl(int c)
3
This function checks whether the passed character is control character.
int isdigit(int c)
4
This function checks whether the passed character is decimal digit.
int isgraph(int c)
5 This function checks whether the passed character has graphical representation
using locale.
int islower(int c)
6
This function checks whether the passed character is lowercase letter.
int isprint(int c)
7
This function checks whether the passed character is printable.
int ispunct(int c)
8
This function checks whether the passed character is a punctuation character.
int isspace(int c)
9
This function checks whether the passed character is white-space.
int isupper(int c)
10
This function checks whether the passed character is an uppercase letter.
int isxdigit(int c)
11
This function checks whether the passed character is a hexadecimal digit.
The library also contains two conversion functions that accepts and returns an "int".
S.NO Function & Description
int tolower(int c)
1 This function converts uppercase letters to
lowercase.
int toupper(int c)
2 This function converts lowercase letters to
uppercase.

Character Classes
S.NO Character Class & Description
Digits
1
This is a set of whole numbers { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }.

Gayatri Vidya Parishad Degree College


Hexadecimal digits
2
This is the set of { 0 1 2 3 4 5 6 7 8 9 A B C D E F a b c d e f }.
Lowercase letters
3
This is a set of lowercase letters { a b c d e f g h i j k l m n o p q r s t u v w x y z }.
Uppercase letters
4 This is a set of uppercase letters {A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
}.
Letters
5
This is a set of lowercase and uppercase letters.
Alphanumeric characters
6
This is a set of Digits, Lowercase letters and Uppercase letters.
Punctuation characters
7
This is a set of ! " # $ % & ' ( ) * + , - . / : ; < = > ? @ [ \ ] ^ _ ` { | } ~
Graphical characters
8
This is a set of Alphanumeric characters and Punctuation characters.
Space characters
9
This is a set of tab, newline, vertical tab, form feed, carriage return, and space.
Printable characters
10 This is a set of Alphanumeric characters, Punctuation characters and Space
characters.
Control characters
11
In ASCII, these characters have octal codes 000 through 037, and 177 (DEL).
Blank characters
12
These are spaces and tabs.
Alphabetic characters
13
This is a set of Lowercase letters and Uppercase letters.

Gayatri Vidya Parishad Degree College


Gayatri Vidya Parishad Degree College

You might also like