Unit-2 Com
Unit-2 Com
Unit-2 Com
C language has standard libraries that allow input and output in a program.
The stdio.h or standard input output library in C that has methods for input and output.
scanf()
The scanf() method, in C, reads the value from the console as per the type specified.
Syntax:
scanf(“%X”, &variableOfXType); where %X is the format specifier in C. It is a way to tell
the compiler what type of data is in a variable and & is the address operator in C, which
tells the compiler to change the real value of this variable, stored at this address in the
memory.
printf()
The printf() method, in C, prints the value passed as the parameter to it, on the console screen.
Syntax:
printf(“%X”, variableOfXType); where %X is the format specifier in C. It is a way to tell
the compiler what type of data is in a variable and & is the address operator in C, which
tells the compiler to change the real value of this variable, stored at this address in the
memory.
The basic type in C includes types like int, float, char, etc. Inorder to input or output the
specific type, the X in the above syntax is changed with the specific format specifier of that
type. The Syntax for input and output for these are:
Integer:
Input: scanf("%d", &intVariable);
Output: printf("%d", intVariable);
Float:
Input: scanf("%f", &floatVariable);
Output: printf("%f", floatVariable);
Character:
Input: scanf("%c", &charVariable);
Output: printf("%c", charVariable);
Data Types
Each variable in C has an associated data type. Each data type requires different amounts of
memory and has some specific operations which can be performed over it. It specifies the
type of data that the variable can store like integer, character, floating, double, etc. The data
type is a collection of data with values having fixed values, meaning as well as its
characteristics.
The data types in C can be classified as follows:
Types Description
Primitive Data Arithmetic types can be further classified into integer and floating data
Types types.
The data type has no value or operator and it does not provide a result
Void Types to its caller. But void comes under Primitive data types.
User Defined It is mainly used to assign names to integral constants, which make a
DataTypes program easy to read and maintain
The data types that are derived from the primitive or built-in datatypes
Derived types are referred to as Derived Data Types.
Different data types also have different ranges up to which they can store numbers. These
ranges may vary from compiler to compiler. Below is a list of ranges along with the memory
requirement and format specifiers on the 32-bit GCC compiler.
Memory Format
Data Type Range
(bytes) Specifier
-2,147,483,648 to
int 4 %d
2,147,483,647
-2,147,483,648 to
long int 4 %ld
2,147,483,647
Integer Types
The integer data type in C is used to store the whole numbers without decimal values. Octal
values, hexadecimal values, and decimal values can be stored in int data type in C. We can
determine the size of the int data type by using the sizeof operator in C. Unsigned int data
type in C is used to store the data values from zero to positive numbers but it can’t store
negative values like signed int. Unsigned int is larger in size than signed int and it uses “%u”
as a format specifier in C programming language. Below is the programming implementation
of the int data type in C.
Range: -2,147,483,648 to 2,147,483,647
Size: 2 bytes or 4 bytes
Format Specifier: %d
Note: The size of an integer data type is compiler-dependent, when processors are 16-bit
systems, then it shows the output of int as 2 bytes. And when processors are 32-bit then it
shows 2 bytes as well as 4 bytes.
Character Types
Character data type allows its variable to store only a single character. The storage si ze of
the character is 1. It is the most basic data type in C. It stores a single character and requires
a single byte of memory in almost all compilers.
Range: (-128 to 127) or (0 to 255)
Size: 1 byte
Format Specifier: %c
Floating-Point Types
In C programming float data type is used to store floating-point values. Float in C is used to
store decimal and exponential values. It is used to store decimal numbers (numbers with
floating point values) with single precision.
Range: 1.2E-38 to 3.4E+38
Size: 4 bytes
Format Specifier: %f
Double Types
A Double data type in C is used to store decimal numbers (numbers with floating point
values) with double precision. It is used to define numeric values which hold numbers with
decimal values in C. Double data type is basically a precision sort of data type that is capable
of holding 64 bits of decimal numbers or floating points. Since double has more precision as
compared to that float then it is much more obvious that it occupies twice the memory as
occupied by the floating-point type. It can easily accommodate about 16 to 17 digits after or
before a decimal point.
Range: 1.7E-308 to 1.7E+308
Size: 8 bytes
Format Specifier: %lf
The void data type in C is used to specify that no value is present. It does not provide a result
value to its caller. It has no values and no operations. It is used to represent nothing. Void is
used in multiple ways as function return type, function arguments as void, and pointers to
void.
Syntax:
// function return type void
int print(void);
Storage Classes in C
Storage Classes are used to describe the features of a variable/function. These features
basically include the scope, visibility and life-time which help us to trace the existence of a
particular variable during the runtime of a program.
C language uses 4 storage classes, namely:
1. auto: This is the default storage class for all the variables declared inside a function or a
block. Hence, the keyword auto is rarely used while writing programs in C language.
Auto variables can be only accessed within the block/function they have been declared
and not outside them (which defines their scope). Of course, these can be accessed within
nested blocks within the parent block/function in which the auto variable was declared.
However, they can be accessed outside their scope as well using the concept of pointers
given here by pointing to the very exact memory location where the variables reside. They
are assigned a garbage value by default whenever they are declared.
2. extern: Extern storage class simply tells us that the variable is defined elsewhere and not
within the same block where it is used. Basically, the value is assigned to it in a different
block and this can be overwritten/changed in a different block as well. So an extern
variable is nothing but a global variable initialized with a legal value where it is declared
in order to be used elsewhere. It can be accessed within any function/block. Also, a
normal global variable can be made extern as well by placing the ‘extern’ keyword before
its declaration/definition in any function/block. This basically signifies that we are not
initializing a new variable but instead we are using/accessing the global variable only.
The main purpose of using extern variables is that they can be accessed between two
different files which are part of a large program. For more information on how extern
variables work, have a look at this link.
3. static: This storage class is used to declare static variables which are popularly used while
writing programs in C language. Static variables have the property of preserving their
value even after they are out of their scope! Hence, static variables preserve the value of
their last use in their scope. So we can say that they are initialized only once and exist till
the termination of the program. Thus, no new memory is allocated because they are not
re-declared. Their scope is local to the function to which they were defined. Global static
variables can be accessed anywhere in the program. By default, they are assigned the
value 0 by the compiler.
4. register: This storage class declares register variables that have the same functionality as
that of the auto variables. The only difference is that the compiler tries to store these
variables in the register of the microprocessor if a free registration is available. This
makes the use of register variables to be much faster than that of the variables stored in
the memory during the runtime of the program. If a free registration is not available, these
are then stored in the memory only. Usually few variables which are to be accessed very
frequently in a program are declared with the register keyword which improves the
running time of the program. An important and interesting point to be noted here is that
we cannot obtain the address of a register variable using pointers.
To specify the storage class for a variable, the following syntax is to be followed:
Syntax:
storage_class var_data_type var_name;
Functions follow the same syntax as given above for variables. Have a look at the following
C example for further clarification:
Operators in C
Operators are the foundation of any programming language. We can define operators as
symbols that help us to perform specific mathematical and logical computations on operands.
In other words, we can say that an operator operates the operands. For example, ‘+’ is an
operator used for addition, as shown below:
c = a + b;
Here, ‘+’ is the operator known as the addition operator and ‘a’ and ‘b’ are operands. The
addition operator tells the compiler to add both of the operands ‘a’ and ‘b’.
The functionality of the C programming language is incomplete without the use of operators.
C has many built-in operators and can be classified into 6 types:
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Bitwise Operators
5. Assignment Operators
6. Other Operators
Example:
a = 10;
b = 20;
ch = 'y';
b) “+=”
This operator is the combination of the ‘+’ and ‘=’ operators. This operator first adds the
current value of the variable on left to the value on the right and then assigns the result to the
variable on the left.
Example:
(a += b) can be written as (a = a + b)
If initially value stored in a is 5. Then (a += 6) = 11.
c) “-=”
This operator is a combination of ‘-‘ and ‘=’ operators. This operator first subtracts the value
on the right from the current value of the variable on left and then assigns the result to the
variable on the left.
Example:
(a -= b) can be written as (a = a - b)
If initially value stored in a is 8. Then (a -= 6) = 2.
d) “*=”
This operator is a combination of the ‘*’ and ‘=’ operators. This operator first multiplies the
current value of the variable on left to the value on the right and then assigns the result to the
variable on the left.
Example:
(a *= b) can be written as (a = a * b)
If initially, the value stored in a is 5. Then (a *= 6) = 30.
e) “/=”
This operator is a combination of the ‘/’ and ‘=’ operators. This operator first divides the
current value of the variable on left by the value on the right and then assigns the result to
the variable on the left.
Example:
(a /= b) can be written as (a = a / b)
If initially, the value stored in a is 6. Then (a /= 2) = 3.
6. Other Operators:
Apart from the above operators, there are some other operators available in C used to perform
some specific tasks. Some of them are discussed here:
a. sizeof operator
sizeof is much used in the C programming language.
It is a compile-time unary operator which can be used to compute the size of its operand.
The result of sizeof is of the unsigned integral type which is usually denoted by size_t.
Basically, the sizeof the operator is used to compute the size of the variable.
(See this article for reference)
b. Comma Operator
The comma operator (represented by the token) is a binary operator that evaluates its first
operand and discards the result, it then evaluates the second operand and returns this value
(and type).
The comma operator has the lowest precedence of any C operator.
Comma acts as both operator and separator. (See this article for reference)
c. Conditional Operator
The conditional operator is of the form Expression1? Expression2: Expression3
Here, Expression1 is the condition to be evaluated. If the condition (Expression1)
is True then we will execute and return the result of Expression2 otherwise if the
condition (Expression1) is false then we will execute and return the result of Expression3.
We may replace the use of if..else statements with conditional operators. (See this article
for reference)
d. dot (.) and arrow (->) Operators
Member operators are used to reference individual members of classes, structures, and
unions.
The dot operator is applied to the actual object. (See this article for reference)
The arrow operator is used with a pointer to an object. (See this article for reference)
e. Cast Operator
Casting operators convert one data type to another. For example, int(2.2000) would return
2.
A cast is a special operator that forces one data type to be converted into another.
The most general cast supported by most of the C compilers is as follows − [ (type)
expression ]. (See this article for reference)
f. &,* Operator
Pointer operator & returns the address of a variable. For example &a; will give the actual
address of the variable.
Pointer operator * is a pointer to a variable. For example *var; will pointer to a variable
var. (See this article for reference
Below is the implementation of the above-mentioned operators:
Operator Precedence Chart
The below table describes the precedence order and associativity of operators in C. The
precedence of the operator decreases from top to bottom.
Dereference right-to-left
*
3 Multiplication/division/modulus left-to-right
*,/,%
4 Addition/subtraction left-to-right
+/-
12 Logical OR left-to-right
||
Assignment right-to-left
=
Strucutre of c Program
All human beings have a definite structure, i.e., head, neck, and four limbs connected to a torso.
Almost everything has a definite structure. Likewise, in the case of programming languages,
all of them have a definite structure. These structures have to be followed while writing the
code.
The structure of a C program can be mainly divided into six parts, each having its purpose. It
makes the program easy to read, easy to modify, easy to document, and makes it consistent in
format.
Section Description
All header files are included in this section which contains different functions
Link from the libraries. A copy of these header files is inserted into your code
before compilation.
For every C program, the execution starts from the main() function. It is
Main() Function
mandatory to include a main() function in every C program.
Includes all user-defined functions (functions the user provides). They can
Subprograms contain the inbuilt functions and the function definitions declared in the
Global Declaration section. These are called in the main() function.
Algorithm
You've to subtract the current year from your birth year and get your age.
Code:
/** //Documentation
* file: age.c
* author: you
* description: program to find our age.
*/
In a C program, single-line comments can be written using two forward slashes i.e., //, and we
can create multi-line comments using /* */. Here, we've used multi-line comments.
/**
* file: age.c
* author: you
* description: program to find our age.
*/
(b) Link
A header file is a file that consists of C declarations that can be used between different files. It
helps us in using others' code in our files. A copy of these header files is inserted into your code
before compilation.
#include <stdio.h>
(c) Definition
A preprocessor directive in C is any statement that begins with the "#" symbol. The #define is
a preprocessor compiler directive used to create constants. In simple terms, #define basically
allows the macro definition, which allows the use of constants in our code.
We've created a constant BORN which is assigned a value of 2000. Generally, uppercase letters
are preferred for defining the constants. The above constant BORN will be replaced by 2000
throughout our code wherever used.
#define is typically used to make a source program easy to modify and compile in different
execution environments.
This section includes all global variables, function declarations, and static variables. The
variables declared in this section can be used anywhere in the program. They're accessible to
all the functions of the program. Hence, they are called global variables.
We've declared our age function, which takes one integer argument and returns an integer.
In the structure of a C program, this section contains the main function of the code. The
compiler starts execution from the main() function. It can use global variables, static variables,
inbuilt functions, and user-defined functions. The return type of the main() function can be
void and also not necessarily int.
int main(void)
{
int current = 2021;
printf("Age: %d", age(current));
return 0;
}
Here, we've declared a variable named current and assigned the value as 2021. Then we've
called the printf() function, with calls the age() function, which takes only one parameter.
(f) Subprograms
This includes the user-defined functions called in the main() function. User-defined functions
are generally written after the main() function irrespective of their order.
When the user-defined function is called from the main() function, the control of the program
shifts to the called function, and when it encounters a return statement, it returns to the main()
function. In this case, we've defined the age() function, which takes one parameter, i.e., the
current year.
This function is called in the main function. It returns an integer to the main function.
#include <stdio.h>
int main()
printf("Hello World");
return 0;
Hello, World
Run Code →
To run the above code on your local machine, you will have to install a C language compiler
on your Computer/Laptop. We will learn how to do that in the next tutorial - Compile and Run
C Code.
If you do not want to install the C compiler on your computer, don't worry. You can use
our Online Compiler to run C programs and Practice. Click on the Run Program
button above to open the compiler.
Pre-processor
Header file
main() function
Variables in C
Statements & expressions in C
All these are essential parts of a C language program. Don't worry about all this, we will learn
about everything one by one and will clear all your confusion.
Let's start with a basic introduction of various code statements that we used in the above Hello
World program.
1. Pre-processor
The #include is the first statement of any C program. It is known as a pre-processor. The task
of a pre-processor is to initialize the environment of the program, i.e. to link the program with
the header files required.
As its name suggests, this line of code is responsible for doing pre-processing, before the
actual code (logic) is executed.
So, when we say #include<stdio.h>, it is to inform the compiler to include the stdio.h header
file which is the standard I/O library into the program before executing the program.
The standard I/O library lets you read input from the keyboard(i.e standard in) and then write
the output to the console screen (i.e. standard out) and it is an extremely useful library.
The #include is not the only pre-processor. Whenever you see any piece of code starting with
a # symbol, that means it's a pre-processor in the C language. We will learn about pre-
processors in detail later.
2. Header file
Header files contain definitions of the functions which can be used in any C program by using
pre-processor #include statement along with the name of the header file.
There are some standard header files that come along with default C installation,
like stdio.h header file. There are many other such files, we will learn about them later.
With time, you will have a clear picture of what header files are, as of now consider them as a
readymade collection of functions that comes packaged with the C language and you can use
them without worrying about how they work, all you have to do is include the header file in
your program.
To use any of the standard library functions, the appropriate header file must be included. This
is done at the beginning of the C source code.
For example, to use the printf() function in a C program, which is used to display anything on
the console screen, the line #include <stdio.h> is required, because the header
file stdio.h contains the printf() function definition.
Everything inside this function in a C program will be executed, hence the actual logic or the
code is always written inside the main() function.
As the name suggests, this is the main(of prime importance or center of attraction) function.
#include <stdio.h>
int main()
printf("Hello World");
return 0;
In the Hello World code example above, there was int written before the main() function,
remember? Well, that is the return type of the main() function. we will discuss it in detail
later.
The curly braces { } just after the main() function enclose the body of the main() function.
The printf() is a function that is used to print(show) anything on the console as output. This
function is defined in the stdio.h header file, which we have included in our C program.
We will cover how to take input and show output in one of the next tutorials.
5. Return Statement
A return statement is used to return a response to the caller function. It is generally the last
statement of any C language function. Do not worry about this too, we will cover this statement
when we learn about functions in the C language.
6. Semicolon
It is important to note that every statement in C should end with a semicolon(;). If you miss
adding any semicolon, the compiler will give an error.
Components of C Program
The following sections describe the various components of the preceding sample program. Line
numbers are included so that you can easily identify the program parts discussed.
(e) Program Statements (Lines 12, 13, 14, 17, 19, 20, 22, and 28)
The real work of a C program is done by its statements. C statements display information
onscreen, read keyboard input, perform mathematical operations, call functions, read disk files,
and all the other operations that a program needs to perform. Most of this book is devoted to
teaching you the various C statements. For now, remember that in your source code, C
statements are generally written one per line and always end with a semicolon. The statements
in bigyear.c are explained briefly in the following sections.
/* A single-line comment */
/* a comment
spanning
multiple lines */
You should not use nested comments. A nested comment is a comment that has been put into
another comment. Most compilers will not accept the following:
/*
/* Nested comment */
*/
Some compilers do allow nested comments. Although this feature might be tempting to use,
you should avoid doing so. Because one of the benefits of C is portability, using a feature such
as nested comments might limit the portability of your code. Nested comments also might lead
to hard-to-find problems.
The second style of comment, the ones beginning with two consecutive forward slashes (//),
are only for single-line comments. The two forward slashes tell the compiler to ignore
everything that follows to the end of the line.
Many beginning programmers view program comments as unnecessary and a waste of time.
This is a mistake! The operation of your program might be quite clear when you write the code;
however, as your programs become larger and more complex, or when you need to modify a
program you wrote 6 months ago, comments are invaluable. Now is the time to develop the
habit of using comments liberally to document all your programming structures and operations.
You can use either style of comments you prefer. Both are used throughout the programs in the
book.
/* The following prints Hello
printf("Hello World!);
might be going a little too far, at least when you’re completely comfortable with
the printf() function and how it works.
Using Braces (Lines 10, 23, 27, and 29)
You use braces {} to enclose the program lines that make up every C function—including
the main() function. A group of one or more statements enclosed within braces is called a block.
As you see in later lessons, C has many uses for blocks.
Running the Program
Take the time to enter, compile, and run Helloworld.c. It provides additional practice in using
your editor and compiler. Recall these steps from Lesson 1, “Getting Started with C”: