Unit 2

You might also like

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

Introduction to C Language

C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972.

It is a very popular language, despite being old.

C is strongly associated with UNIX, as it was developed to write the UNIX operating system.

The C language is imperative and procedural in nature.

As of now, the C language is one of the most widely used computer languages along with Java,
which is mostly used among modern programmers.

Benefits of C Programming Language

Here are a few reasons why programmers choose the C language for running a program:

 It is a structured language.

 The C language is very easy to understand and learn.

 The C language generates very efficient programs.

 It helps you handle various low-level activities.

 The compilation of C programs can occur on various computer programs.

Facts about the C Language

 The C language came into existence for writing an OS known as the UNIX operating system.
 This language is the successor of the B language, which came into existence in the early 1970s.
 The ANSI (American National Standard Institute) formalized this language in 1988.
 The creators of this language have totally written the UNIX OS in C.
 As of today, the C language is the most popular and widely used programming language.

Uses of the C Programming Language

 Procedural Language: The execution of the instructions present in a C program happens step by
step.
 Speed: The C language is much faster as compared to a majority of the programming languages,
such as Python, Java, and many more.
 Portable: A C program can be moved from any given platform to another one, and we can also
run it on that platform without any of the charges.
 General Purposes: We can use the C programming language for developing operating systems,
databases, embedded systems, etc.
History of C Language
C programming language was developed in 1972 by Dennis Ritchie at bell laboratories of AT&T
(American Telephone & Telegraph), located in the U.S.A.

Dennis Ritchie is known as the founder of the c language.

It was developed to overcome the problems of previous languages such as B, BCPL, etc.

Initially, C language was developed to be used in UNIX operating system. It inherits many features of
previous languages such as B and BCPL.

A List of Programming Languages Developed Before C Language:

Language Year of Development Developer

ALGOL 1960 International Group

BCPL 1967 Martin Richards

B 1970 Ken Thompson

Traditional C 1972 Dennis Ritchie

K&R C 1978 Kernighan and Ritchie

ANSI C 1989 ANSI Committee

ANSI/ISO C 1990 ISO Committee

C99 1999 Standardization Committee

Structure of a C program

The Structure of C Program contains different sections listed below:

1. Documentation section

2. Preprocessor section

3. Definition section

4. Global declaration

5. Main function
6. User defined functions

Documentation section

It includes the statement specified at the beginning of a program, such as a program's name, date,
description, and title.

Both methods work as the document section in a program. It provides an overview of the program.
Anything written inside will be considered a part of the documentation section and will not interfere
with the specified code.

Preprocessor section

The preprocessor section contains all the header files used in a program. It informs the system to link
the header files to the system libraries.

The #include statement includes the specific file as a part of a function at the time of the compilation.
Thus, the contents of the included file are compiled along with the function being compiled.
The #include<stdio.h> consists of the contents of the standard input output files, which contains the
definition of stdin, stdout, and stderr. Whenever the definitions stdin, stdout, and stderr are used in a
function, the statement #include<stdio.h> need to be used.

There are various header files available for different purposes. For example, # include <math.h>. It is
used for mathematic functions in a program.

Define section

The define section comprises of different constants declared using the define keyword.

Global declaration

The global section comprises of all the global declarations in the program.

The size of the above global variables is listed as follows:

char = 1 byte

float = 4 bytes

int = 4 bytes

We can also declare user defined functions in the global variable section.

Main function

main() is the first function to be executed by the computer. It is necessary for a code to include the
main(). It is like any other function available in the C library. Parenthesis () are used for passing
parameters (if any) to a function.
Main function is further categorized into local declarations, statements, and expressions.

Local declarations

The variable that is declared inside a given function or block refers to as local declarations.

Statements

The statements refers to if, else, while, do, for, etc. used in a program within the main function.

Expressions

An expression is a type of formula where operands are linked with each other by the use of operators.

User defined functions

The user defined functions specified the functions specified as per the requirements of the user. For
example, color(), sum(), division(), etc.

The program (basic or advance) follows the same sections as listed above.

Return function is generally the last section of a code. But, it is not necessary to include. It is used when
we want to return a value. The return function returns a value when the return type other than the void
is specified with the function.

Return type ends the execution of the function. It further returns control to the specified calling
function.

Escape Sequences in C
Data Types in C
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
Types Arithmetic types can be further classified into integer and floating data types.

The data type has no value or operator and it does not provide a result to its caller. But
Void Types void comes under Primitive data types.

User Defined It is mainly used to assign names to integral constants, which make a program easy to
DataTypes read and maintain

The data types that are derived from the primitive or built-in datatypes are referred to
Derived types 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.

Data Type Memory (bytes) Range Format Specifier

short int 2 -32,768 to 32,767 %hd

unsigned short int 2 0 to 65,535 %hu

unsigned int 4 0 to 4,294,967,295 %u

Int 4 -2,147,483,648 to 2,147,483,647 %d

long int 4 -2,147,483,648 to 2,147,483,647 %ld

unsigned long int 4 0 to 4,294,967,295 %lu

long long int 8 -(2^63) to (2^63)-1 %lld

unsigned long long int 8 0 to 18,446,744,073,709,551,615 %llu

signed char 1 -128 to 127 %c

unsigned char 1 0 to 255 %c

float 4 1.2E-38 to 3.4E+38 %f


Double 8 1.7E-308 to 1.7E+308 %lf

long double 16 3.4E-4932 to 1.1E+4932 %Lf

C Variables
Variables are containers for storing data values.

In C, there are different types of variables (defined with different keywords), for example:

 int - stores integers (whole numbers), without decimals, such as 123 or -123

 float - stores floating point numbers, with decimals, such as 19.99 or -19.99

 char - stores single characters, such as 'a' or 'B'. Char values are surrounded by single quotes

C Variable Names

 All C variables must be identified with unique names.


 These unique names are called identifiers.
 Identifiers can be short names (like x and y) or more descriptive names (age, sum, totalVolume).

The general rules for naming variables are:

 Names can contain letters, digits and underscores


 Names must begin with a letter or an underscore (_)
 Names are case sensitive (myVar and myvar are different variables)
 Names cannot contain whitespaces or special characters like !, #, %, etc.
 Reserved words (such as int) cannot be used as names

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
 Relational Operators
 Logical Operators
 Bitwise Operators
 Assignment Operators
 Misc Operators

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 −

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 after an integer division. B%A=0

++ Increment operator increases the integer value by one. A++ = 11

-- Decrement operator decreases the integer value by one. A-- = 9

Relational Operators
The following table shows all the relational operators supported by C. Assume variable A holds 10 and
variable B holds 20 then −

Operator Description Example

== Checks if the values of two operands are equal or not. If yes, then the (A == B)
condition becomes true. is not
true.

!= Checks if the values of two operands are equal or not. If the values are (A != B)
not equal, then the condition becomes true. is true.
> Checks if the value of left operand is greater than the value of right (A > B) is
operand. If yes, then the condition becomes true. not
true.

< Checks if the value of left operand is less than the value of right operand. (A < B) is
If yes, then the condition becomes true. true.

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

<= Checks if the value of left operand is less than or equal to the value of (A <= B)
right operand. If yes, then the condition becomes true. is 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 −

Operator Description Example

&& Called Logical AND operator. If both the operands are non-zero, then the (A &&
condition becomes true. B) is
false.

|| Called Logical OR Operator. If any of the two operands is non-zero, then (A || B)


the condition becomes true. is true.

! Called Logical NOT Operator. It is used to reverse the logical state of its !(A &&
operand. If a condition is true, then Logical NOT operator will make it B) is
false. true.

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

~A = 1100 0011

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

Operator Description Example

& Binary AND Operator copies a bit to the result if it exists in both (A & B)
operands. = 12,
i.e.,
0000
1100

| Binary OR Operator copies a bit if it exists in either operand. (A | B) =


61, i.e.,
0011
1101

^ Binary XOR Operator copies the bit if it is set in one operand but not (A ^ B) =
both. 49, i.e.,
0011
0001

~ (~A ) =
Binary One's Complement Operator is unary and has the effect of ~(60),
'flipping' bits. i.e,. -
0111101

<< Binary Left Shift Operator. The left operands value is moved left by the A << 2 =
number of bits specified by the right operand. 240 i.e.,
1111
0000

>> Binary Right Shift Operator. The left operands value is moved right by the A >> 2 =
number of bits specified by the right operand. 15 i.e.,
0000
1111

Assignment Operators
The following table lists the assignment operators supported by the C language −

Operator Description Example

= Simple assignment operator. Assigns values from right side operands to C=A+B
left side operand will assign
the value
of A + B to
C

+= Add AND assignment operator. It adds the right operand to the left C += A is
operand and assign the result to the left operand. equivalent
to C = C +
A

-= Subtract AND assignment operator. It subtracts the right operand from C -= A is


the left operand and assigns the result to the left operand. equivalent
to C = C -
A

*= Multiply AND assignment operator. It multiplies the right operand with C *= A is


the left operand and assigns the result to the left operand. equivalent
to C = C *
A

/= Divide AND assignment operator. It divides the left operand with the C /= A is
right operand and assigns the result to the left operand. equivalent
to C = C /
A

%= Modulus AND assignment operator. It takes modulus using two C %= A is


operands and assigns the result to the left operand. equivalent
to C = C %
A

<<= Left shift AND assignment operator. C <<= 2 is


same as C
= C << 2

>>= Right shift AND assignment operator. C >>= 2 is


same as C
= C >> 2

&= Bitwise AND assignment operator. C &= 2 is


same as C
=C&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.

Operator Description Example

sizeof() sizeof(a), where a is integer, will return


Returns the size of a variable.
4.

& &a; returns the actual address of the


Returns the address of a variable.
variable.

* Pointer to a variable. *a;

?: If Condition is true ? then value X :


Conditional Expression.
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.
Category Operator Associativity

Postfix () [] -> . ++ - - Left to right

Unary + - ! ~ ++ - - (type)* & sizeof Right to left

Multiplicative */% Left to right

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


Programming Errors in C
Errors are the problems or the faults that occur in the program, which makes the behavior of the
program abnormal, and experienced developers can also make these faults. Programming errors are
also known as the bugs or faults, and the process of removing these bugs is known as debugging.

These errors are detected either during the time of compilation or execution. Thus, the errors must be
removed from the program for the successful execution of the program.

There are mainly five types of errors exist in C programming:

o Syntax error

o Run-time error

o Linker error

o Logical error

o Semantic error

Syntax error

Syntax errors are also known as the compilation errors as they occurred at the compilation time, or we
can say that the syntax errors are thrown by the compilers. These errors are mainly occurred due to the
mistakes while typing or do not follow the syntax of the specified programming language. These
mistakes are generally made by beginners only because they are new to the language. These errors can
be easily debugged or corrected.

Run-time error

Sometimes the errors exist during the execution-time even after the successful compilation known as
run-time errors. When the program is running, and it is not able to perform the operation is the main
cause of the run-time error. The division by zero is the common example of the run-time error. These
errors are very difficult to find, as the compiler does not point to these errors.

Linker error

Linker errors are mainly generated when the executable file of the program is not created. This can be
happened either due to the wrong function prototyping or usage of the wrong header file. For example,
the main.c file contains the sub() function whose declaration and definition is done in some other file
such as func.c. During the compilation, the compiler finds the sub() function in func.c file, so it generates
two object files, i.e., main.o and func.o. At the execution time, if the definition of sub() function is not
found in the func.o file, then the linker error will be thrown. The most common linker error that occurs
is that we use Main() instead of main().
Logical error

The logical error is an error that leads to an undesired output. These errors produce the incorrect
output, but they are error-free, known as logical errors. These types of mistakes are mainly done by
beginners. The occurrence of these errors mainly depends upon the logical thinking of the developer. If
the programmers sound logically good, then there will be fewer chances of these errors.

Semantic error

Semantic errors are the errors that occurred when the statements are not understandable by the
compiler.

The following can be the cases for the semantic error:

o Use of a un-initialized variable.


int i;
i=i+2;

o Type compatibility
int b = "javatpoint";

o Errors in expressions
int a, b, c;
a+b = c;

o Array index out of bound


int a[10];
a[10] = 34;

How C Programming Language Works:


C is a compiled language. A compiler is a special tool that compiles the program and converts it into the
object file which is machine readable. After the compilation process, the linker will combine different
object files and creates a single executable file to run the program. The following diagram shows the
execution of a ‘C’ program.
C - Storage Classes
A storage class defines the scope (visibility) and life-time of variables and/or functions within a C
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.

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.

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.

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.

You might also like