Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
1 views

Programming in C Unit I

The document provides an overview of the C programming language, including its history, features, character set, tokens, identifiers, keywords, and variables. It explains the structure and syntax of C, detailing various types of tokens, constants, and operators, as well as rules for naming variables. Additionally, it covers the types of variables in C, such as local, global, static, and register variables, along with their respective scopes and characteristics.

Uploaded by

apexg7271
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

Programming in C Unit I

The document provides an overview of the C programming language, including its history, features, character set, tokens, identifiers, keywords, and variables. It explains the structure and syntax of C, detailing various types of tokens, constants, and operators, as well as rules for naming variables. Additionally, it covers the types of variables in C, such as local, global, static, and register variables, along with their respective scopes and characteristics.

Uploaded by

apexg7271
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

B.

Sc: Information Technology- First Year Semester-I


B.Sc: Computer Science- First Year Semester-I

Introduction to C Programming

Unit-I Notes
1.1 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.

1.2 Features of C Language:-

1. Procedural Language
• In a procedural language like C step by step, predefined instructions are carried out.
• C program may contain more than one function to perform a particular task.

2. Fast and Efficient


• C programming language as the middle-level language provides programmers access to direct
manipulation with the computer hardware but higher-level languages do not allow this.
• It’s fast because statically typed languages are faster than dynamically typed languages.

3. Modularity
• The concept of storing C programming language code in the form of libraries for further future uses is
known as modularity.
• C language has its own library to solve common problems.

4. Statically Type
• C programming language is a statically typed language. Meaning the type of variable is checked at the
time of compilation but not at run time.
• This means each time a programmer types a program they have to mention the type of variables used.

5. General-Purpose Language
From system programming to photo editing software, the C programming language is used in various
applications. Some of the common applications where it’s used are as follows:
• Operating systems: Windows, Linux, iOS, Android, OXS
• Databases: PostgreSQL, Oracle, MySQL, MS SQL Server, etc.
6. Rich set of built-in Operators
It is a diversified language with a rich set of built-in operators which are used in writing complex or simplified
C programs.

7. Libraries with Rich Functions


Robust libraries and functions in C help even a beginner coder to code with ease.

8. Middle-Level Language
As it is a middle-level language so it has the combined form of both capabilities of assembly language and
features of the high-level language.

9. Portability
C language is lavishly portable as programs that are written in C language can run and compile on any system
with either no or small changes.

10. Easy to Extend


Programs written in C language can be extended means when a program is already written in it then some
more features and operations can be added to it.

1.3 Charactter Set in C:-

• In the C programming language, the character set refers to a set of all the valid characters that we can
use in the source program for forming words, expressions, and numbers.

Types of Characters in C:

The C programming language provides support for the following types of characters. In other words, these are
the valid characters that we can use in the C language:
• Digits
• Alphabets
• Main Characters
All of these serve a different set of purposes, and we use them in different contexts in the C language.

i)Alphabets
• The C programming language provides support for all the alphabets that we use in the English
language.
• Thus, in simpler words, a C program would easily support a total of 52 different characters- 26
uppercase and 26 lowercase.

Type of Character Description Characters

Lowercase a to z 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
Alphabets

Uppercase A to Z A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W,
Alphabets X, Y, Z
ii)Digits
• The C programming language provides the support for all the digits that help in constructing/
supporting the numeric values or expressions in a program.
• These range from 0 to 9, and also help in defining an identifier
• Thus, the C language supports a total of 10 digits for constructing the numeric values or expressions
in any program.

Type of Character Description Characters

Digits 0 to 9 0, 1, 2, 3, 4, 5, 6, 7, 8, 9

iii)Special Characters
• We use some special characters in the C language for some special purposes, such as logical operations,
mathematical operations, checking of conditions, backspaces, white spaces, etc.
• We can also use these characters for defining the identifiers in a much better way.
The C programming language provides support for the following types of special characters:

Type of Character Examples

Special Characters `~@!$#^*%&()[]{}<>+=_–|/\;:‘“,.?

iv)White Spaces
The white spaces in the C programming language contain the following:
• Blank Spaces
• Carriage Return
• Tab
• New Line

1.4 C Tokens, Identifiers & Keywords:-

• A token in C can be defined as the smallest individual element of the C programming language that is
meaningful to the compiler.
• It is the basic component of a C program.

Types of Tokens in C
The tokens of C language can be classified into six types based on the functions they are used to perform.
The types of C tokens are as follows:
1. C Token – Keywords
• The keywords are pre-defined or reserved words in a programming language.
• Each keyword is meant to perform a specific function in a program.
• Since keywords are referred names for a compiler, they can’t be used as variable names because by
doing so, we are trying to assign a new meaning to the keyword which is not allowed.
• You cannot redefine keywords.

C language supports 32 keywords which are given below:

auto double int struct


break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while

2. C Token – Identifiers
• Identifiers are used as the general terminology for the naming of variables, functions, and arrays.
• These are user-defined names consisting of an arbitrarily long sequence of letters and digits with
either a letter or the underscore(_) as a first character.
• Identifier names must differ in spelling and case from any keywords.
• You cannot use keywords as identifiers; they are reserved for special use.
• Once declared, you can use the identifier in later program statements to refer to the associated value.
• A special identifier called a statement label can be used in goto statements.

Rules for Naming Identifiers:


Certain rules should be followed while naming c identifiers which are as follows:
• They must begin with a letter or underscore(_).
• They must consist of only letters, digits, or underscore. No other special character is allowed.
• It should not be a keyword.
• It must not contain white space.
• It should be up to 31 characters long as only the first 31 characters are significant.

3. C Token – Constants
• The constants refer to the variables with fixed values.
• They are like normal variables but with the difference that their values can not be modified in the
program once they are defined.
• Constants may belong to any of the data types.

Examples of Constants in C:
const int c_var = 20;
const int* const ptr = &c_var;

4. C Token – Strings
• Strings are nothing but an array of characters ended with a null character (‘\0’).
• This null character indicates the end of the string.
• Strings are always enclosed in double quotes. Whereas, a character is enclosed in single quotes in C
and C++.
Examples of String:
char string[20] = {‘g’, ’e’, ‘e’, ‘k’, ‘s’, ‘f’, ‘o’, ‘r’, ‘g’, ’e’, ‘e’, ‘k’, ‘s’, ‘\0’};
char string[20] = “geeksforgeeks”;
char string [] = “geeksforgeeks”;

5. C Token – Special Symbols


The following special symbols are used in C having some special meaning and thus, cannot be used for
some other purpose. Some of these are listed below:
• Brackets[]: Opening and closing brackets are used as array element references. These indicate single
and multidimensional subscripts.
• Parentheses(): These special symbols are used to indicate function calls and function parameters.
• Braces{}: These opening and ending curly braces mark the start and end of a block of code
containing more than one executable statement.
• Comma (, ): It is used to separate more than one statement like for separating parameters in function
calls.
• Colon(:): It is an operator that essentially invokes something called an initialization list.
• Semicolon(;): It is known as a statement terminator. It indicates the end of one logical entity. That’s
why each individual statement must be ended with a semicolon.
• Asterisk (*): It is used to create a pointer variable and for the multiplication of variables.
• Assignment operator(=): It is used to assign values and for logical operation validation.
• Pre-processor (#): The preprocessor is a macro processor that is used automatically by the compiler
to transform your program before actual compilation.
• Period (.): Used to access members of a structure or union.
• Tilde(~): Bitwise One’s Complement Operator.

6. C Token – Operators
Operators are symbols that trigger an action when applied to C variables and other objects. The data items
on which operators act are called operands.
Depending on the number of operands that an operator can act upon, operators can be classified as follows:
• Unary Operators: Those operators that require only a single operand to act upon are known as
unary operators.For Example increment and decrement operators
• Binary Operators: Those operators that require two operands to act upon are called binary
operators. Binary operators can further are classified into:
1. Arithmetic operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Bitwise Operator
• Ternary Operator: The operator that requires three operands to act upon is called the ternary
operator. Conditional Operator(?) is also called the ternary operator.

1.5 Variables in C:-

• A variable in C language is the name associated with some memory location to store data of
different types.
• A variable in C is a memory location with some name that helps store some form of data and
retrieves it when required.
• We can store different types of data in the variable and reuse the same variable for storing some other
data any number of times.

1.5.1 C Variable Syntax:


The syntax to declare a variable in C specifies the name and the type of the variable.
data_type variable_name = value; // defining single variable
or
data_type variable_name1, variable_name2; // defining multiple variable

Here,
• data_type: Type of data that a variable can store.
• variable_name: Name of the variable given by the user.
• value: value assigned to the variable by the user.

Example
int var; // integer variable
char a; // character variable
float fff; // float variables

1.5.2 Aspects of defining a variable:

1. C Variable Declaration
• Variable declaration in C tells the compiler about the existence of the variable with the given
name and data type.
• When the variable is declared, an entry in symbol table is created and memory will be allocated
at the time of initialization of the variable.

2. C Variable Definition
• In the definition of a C variable, the compiler allocates some memory and some value to it.
• A defined variable will contain some random garbage value till it is not initialized.

Example
int var;
char var2;

3. C Variable Initialization
Initialization of a variable is the process where the user assigns some meaningful value to the variable
when creating the variable.

Example
int var = 10; // variable declaration and definition (i.e. Vairable Initialization)

1.5.3 Rules for Naming Variables in C:

i. A variable name must only contain alphabets, digits, and underscore.


ii. A variable name must start with an alphabet or an underscore only. It cannot start with a digit.
iii. No white space is allowed within the variable name.
iv. A variable name must not be any reserved word or keyword.

1.5.4 C Variable Types:


The C variables can be classified into the following types:

1. Local Variables in C
• A Local variable in C is a variable that is declared inside a function or a block of code.
• Its scope is limited to the block or function in which it is declared.
2. Global Variables in C
A Global variable in C is a variable that is declared outside the function or a block of code.
Its scope is the whole program i.e. we can access the global variable anywhere in the C program after it
is declared.

3. Static Variables in C
• A static variable in C is a variable that is defined using the static keyword.
• It can be defined only once in a C program and its scope depends upon the region where it is
declared (can be global or local).
• The default value of static variables is zero.

Syntax of Static Variable in C


static data_type variable_name = initial_value;

As its lifetime is till the end of the program, it can retain its value for multiple function calls as shown in
the example.

4. Automatic Variable in C
• All the local variables are automatic variables by default.
• They are also known as auto variables.
• Their scope is local and their lifetime is till the end of the block.
• If we need, we can use the auto keyword to define the auto variables.
• The default value of the auto variables is a garbage value.

Syntax of Auto Variable in C


auto data_type variable_name;
or
data_type variable_name; (in local scope)

5. External Variables in C
• External variables in C can be shared between multiple C files.
• We can declare an external variable using the extern keyword.
• Their scope is global and they exist between multiple C files.

Syntax of Extern Variables in C


extern data_type variable_name;

6. Register Variables in C
• Register variables in C are those variables that are stored in the CPU register instead of the
conventional storage place like RAM.
• Their scope is local and exists till the end of the block or a function.
• These variables are declared using the register keyword.
• The default value of register variables is a garbage value.

Syntax of Register Variables in C


register data_type variable_name = initial_value;
1.6 Constants & Its Types

• The constants in C are the read-only variables whose values cannot be modified once they are
declared in the C program.
• The type of constant can be an integer constant, a floating pointer constant, a string constant, or a
character constant.
• We can not make any change in the value of the constant variables after they are defined.
• We define a constant in C language using the const keyword. Also known as a const type
qualifier, the const keyword is placed at the start of the variable declaration to declare that
variable as a constant.

Syntax to Define Constant:

const data_type var_name = value;

1.6.1 Types of Constants in C:


The type of the constant is the same as the data type of the variables. Following is the list of the types
of constants
• Integer Constant
• Character Constant
• Floating Point Constant
• Double Precision Floating Point Constant
• Array Constant
• Structure Constant

1.7 Operators in C:

• In C language, operators are symbols that represent operations to be performed on one or more
operands.
• An operator in C can be defined as the symbol that helps us to perform some specific mathematical,
relational, bitwise, conditional, or logical computations on values and variables.
• The values and variables used with operators are called operands. So we can say that the operators
are the symbols that perform operations on operands.
1.7.1 Types of Operators in C
C language provides a wide range of operators that can be classified into 6 types based on their
functionality:

1. Arithmetic Operations in C:
The arithmetic operators are used to perform arithmetic/mathematical operations on operands.

There are 9 arithmetic operators in C language:

S. No. Symbol Operator Description Syntax

Adds two numeric


+ Plus a+b
1 values.

Subtracts right
– Minus operand from left a–b
2 operand.

Multiply two
* Multiply a*b
3 numeric values.

Divide two
/ Divide a/b
4 numeric values.

Returns the
remainder after
% Modulus diving the left a%b
operand with the
5 right operand.
S. No. Symbol Operator Description Syntax

Used to specify
+ Unary Plus the positive +a
6 values.

Flips the sign of


– Unary Minus -a
7 the value.

Increases the
++ Increment value of the a++
8 operand by 1.

Decreases the
— Decrement value of the a–
9 operand by 1.

2. Relational Operators in C
• The relational operators in C are used for the comparison of the two operands.
• All these operators are binary operators that return true or false values as the result of comparison.

These are a total of 6 relational operators in C:

S. No. Symbol Operator Description Syntax

Returns true if the


left operand is less
< Less than than the right a<b
operand. Else
1 false

Returns true if the


left operand is
> Greater than greater than the a>b
right operand.
2 Else false

Returns true if the


left operand is less
Less than or
<= than or equal to a <= b
equal to
the right operand.
3 Else false

Returns true if the


Greater than or
>= left operand is a >= b
equal to
4 greater than or
S. No. Symbol Operator Description Syntax

equal to right
operand. Else
false

Returns true if
== Equal to both the operands a == b
5 are equal.

Returns true if
!= Not equal to both the operands a != b
6 are NOT equal.

3. Logical Operator in C
• Logical Operators are used to combine two or more conditions/constraints or to complement the
evaluation of the original condition in consideration.
• The result of the operation of a logical operator is a Boolean value either true or false.

S. No. Symbol Operator Description Syntax

Returns true if
&& Logical AND both the operands a && b
1 are true.

Returns true if
|| Logical OR both or any of the a || b
2 operand is true.

Returns true if the


! Logical NOT !a
3 operand is false.

4. Bitwise Operators in C
• The Bitwise operators are used to perform bit-level operations on the operands.
• The operators are first converted to bit-level and then the calculation is performed on the operands.
Mathematical operations such as addition, subtraction, multiplication, etc. can be performed at the bit
level for faster processing.

There are 6 bitwise operators in C:


S. No. Symbol Operator Description Syntax

Performs bit-by-
bit AND operation
& Bitwise AND a&b
and returns the
1 result.

Performs bit-by-
bit OR operation
| Bitwise OR a|b
and returns the
2 result.

Performs bit-by-
bit XOR operation
^ Bitwise XOR a^b
and returns the
3 result.

Flips all the set


Bitwise First
~ and unset bits on ~a
Complement
4 the number.

Shifts the number


in binary form by
<< Bitwise Leftshift one place in the a << b
operation and
5 returns the result.

Shifts the number


in binary form by
Bitwise
>> one place in the a >> b
Rightshilft
operation and
6 returns the result.

5. Assignment Operators in C
• Assignment operators are used to assign value to a variable.
• The left side operand of the assignment operator is a variable and the right side operand of the
assignment operator is a value.
• The value on the right side must be of the same data type as the variable on the left side otherwise
the compiler will raise an error.
• The assignment operators can be combined with some other operators in C to provide multiple
operations using single operator. These operators are called compound operators.

In C, there are 11 assignment operators :


S. No. Symbol Operator Description Syntax

Assign the value


Simple of the right
= a=b
Assignment operand to the left
1 operand.

Add the right


operand and left
operand and
+= Plus and assign a += b
assign this value
to the left
2 operand.

Subtract the right


operand and left
operand and
-= Minus and assign a -= b
assign this value
to the left
3 operand.

Multiply the right


operand and left
Multiply and operand and
*= a *= b
assign assign this value
to the left
4 operand.

Divide the left


operand with the
Divide and right operand and
/= a /= b
assign assign this value
to the left
5 operand.

Assign the
remainder in the
Modulus and division of left
%= a %= b
assign operand with the
right operand to
6 the left operand.

Performs bitwise
AND and assigns
&= AND and assign a &= b
this value to the
7 left operand.
S. No. Symbol Operator Description Syntax

Performs bitwise
OR and assigns
|= OR and assign a |= b
this value to the
8 left operand.

Performs bitwise
XOR and assigns
^= XOR and assign a ^= b
this value to the
9 left operand.

Performs bitwise
Rightshift and
Rightshift and
>>= assign this value a >>= b
assign
to the left
10 operand.

Performs bitwise
Leftshift and
Leftshift and
<<= assign this value a <<= b
assign
to the left
11 operand.

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:

i. 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 or datatype.

Syntax
sizeof (operand)

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

Syntax
operand1 , operand2
iii. Conditional Operator ( ? : )
• The conditional operator is the only ternary operator in C++.
• 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.
Syntax
operand1 ? operand2 : operand3;

1.8 Data Types in C:-


A data type specifies the type of data that a variable can store such as integer, floating, character, etc.

There are the following data types in C language:-

Types Data Types

Basic Data Type int, char, float, double

Derived Data Type array, pointer, structure, union

Enumeration Data Type enum

Void Data Type void

1. Basic Data Types:


• The basic data types are integer-based and floating-point based.
• C language supports both signed and unsigned literals.
• The memory size of the basic data types may change according to 32 or 64-bit operating system.
Let's see the basic data types. Its size is given according to 32-bit architecture.
Data Types Memory Size

char 1 byte

signed char 1 byte

unsigned char 1 byte

short 2 byte

signed short 2 byte

unsigned short 2 byte

int 2 byte

signed int 2 byte

unsigned int 2 byte

short int 2 byte

signed short int 2 byte

unsigned short int 2 byte

long int 4 byte

signed long int 4 byte

unsigned long int 4 byte

float 4 byte

double 8 byte

long double 10 byte


i) Int:
• Integers are entire numbers without any fractional or decimal parts, and the int data type is used to
represent them.
• It is frequently applied to variables that include values, such as counts, indices, or other numerical
numbers.
• The int data type may represent both positive and negative numbers because it is signed by
default.
• An int takes up 4 bytes of memory on most devices, allowing it to store values between around -2
billion and +2 billion.

ii) Char:
• Individual characters are represented by the char data type. Typically used to hold ASCII or UTF-8
encoding scheme characters, such as letters, numbers, symbols, or commas.
• There are 256 characters that can be represented by a single char, which takes up one byte of
memory. Characters such as 'A', 'b', '5', or '$' are enclosed in single quotes.

iii) Float:
• To represent integers, use the floating data type.
• Floating numbers can be used to represent fractional units or numbers with decimal places.
• The float type is usually used for variables that require very good precision but may not be very
precise.

iv) Double:
• Use two data types to represent two floating integers.
• When additional precision is needed, such as in scientific calculations or financial applications, it
provides greater accuracy compared to float.
• Double type, which uses 8 bytes of memory and has an accuracy of about 15 decimal places, yields
larger values.

2. Derived Data Type:


• Beyond the fundamental data types, C also supports derived data types, including arrays, pointers,
structures, and unions.
• These data types give programmers the ability to handle heterogeneous data, directly modify
memory, and build complicated data structures.

i) Array:
• An array, a derived data type, lets you store a sequence of fixed-size elements of the same type.
• It provides a mechanism for joining multiple targets of the same data under the same name.
• The index is used to access the elements of the array, with a 0 index for the first entry.
• The size of the array is fixed at declaration time and cannot be changed during program execution.
• The array components are placed in adjacent memory regions.

ii) Pointer:
• A pointer is a derived data type that keeps track of another data type's memory address.
• When a pointer is declared, the data type it refers to is stated first, and then the variable name is
preceded by an asterisk (*).
• Pointers are commonly used in tasks such as function pointers, data structures, and dynamic
memory allocation.

iii) Structure:
• A structure is a derived data type that enables the creation of composite data types by allowing the
grouping of many data types under a single name.
• It gives you the ability to create your own unique data structures by fusing together variables of
various sorts.
• A structure's members or fields are used to refer to each variable within it.
• Any data type, including different structures, can be a member of a structure.
• A structure's members can be accessed by using the dot (.) operator.

iv) Union:
• A derived data type called a union enables you to store various data types in the same memory
address.
• In contrast to structures, where each member has a separate memory space, members of a union all
share a single memory space.
• A value can only be held by one member of a union at any given moment.
• When you need to represent many data types interchangeably, unions come in handy.
• Like structures, you can access the members of a union by using the dot (.) operator.

3. Enumeration Data Type:


• A set of named constants or enumerators that represent a collection of connected values can be
defined in C using the enumeration data type (enum).
• Enumerations give you the means to give names that make sense to a group of integral values,
which makes your code easier to read and maintain.

4. Void Data Type:


• The void data type in the C language is used to denote the lack of a particular type.
• Function return types, function parameters, and pointers are three situations where it is frequently
utilized.

You might also like