0% found this document useful (0 votes)
28 views29 pages

Unit I C

Introduction to C, Tokens .. etc

Uploaded by

Lydia Allwin
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views29 pages

Unit I C

Introduction to C, Tokens .. etc

Uploaded by

Lydia Allwin
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

Introduction to C Programming

 C is a general purpose and structured programming language.

 In 1972, Dennis Ritchie at Bell Laboratories wrote C Language which caused a


revolution in computing world.

 It was mainly developed as a system programming language to write an operating system.

 The main features of C language include low-level access to memory, a simple set of
keywords, and clean style, these features make C language suitable for system
programming like an operating system or compiler development.

 Most of the programs of UNIX are written and run with the help of 'C'.

 Many of the important ideas of 'c' stem are from BCPL by Martin Richards.

 Many of the ideas of C language were derived and taken from 'B' language. BCPL and
CPL are previous versions of 'B' language.

1. History of C

 C was evolved from ALGOL, BCPL and B.

 ALGOL,BCPL and B are the system programming languages.

 C was developed by Dennis Ritchie at the Bell Laboratories in 1972. Added new features
and concepts like “data types”.

 It was developed along with the UNIX operating system.

 In 1983 American National Standards Institute (ANSI) appointed a technical committee


to define a standard for C.

 The committee approved a version of C in December 1989 which is now known as ANSI
C.

 In 1990 International Standards Organization (ISO) has approved C and this version of C
is referred to as C89.

 In 1999 improved version of C99 was introduced, but many compilers do not support all
of the new features incorporated in C99.

The history and development of C is illustrated in figure.


2. Features of C

 It is a robust language with rich set of built-in functions and operators that can be used to
write any complex program.

 The C compiler combines the capabilities of an assembly language with features of a


high-level language.

 Programs Written in C are efficient and fast. This is due to its variety of data type and
powerful operators.

 Another important feature of C program, is its ability to extend itself.

 C is easy to debug.

 C is highly portable.

 This means that programs written for one computer can be run on another with no
modification.
 C language is structures programming. Thus requiring the user to think of a problem in
terms of function modules or blocks.

 A proper collection of the modules make a complete program.

 C program is basically a collection of functions that are supported by C library.

 We can also create our own function and add it to C library.

3. Structure of C Programs

• A c program may consist of one or more sections as shown in figure.

• The documentation section consists of set of comment lines giving the name of the
program, the author details.

• The link section provides instruction to the compiler to link functions from the system
library.

• The definition section defines all symbolic constants.


• There are some variables used in more than one function. Such variables are called global
variables and are declared in global declaration section.

• Every C program must have one main() function.

• This section contains two parts, declaration and executable part.

• The declaration part declares all the variables used in executable part.

• There is at least one statement in the executable part.

• These two parts must appear between the opening and closing braces.

• The program execution begins at the opening brace and ends at the closing brace.

• The closing brace of the main function section is the logical end of the program.

• All statements in the declaration and executable parts must ends with a semicolon.

• The subprogram section contains all the user defined function that are called in main
function.

• User defined function are generally placed immediately after the main function.

Sample C program
4. Character Set

The characters that can be used to form words, numbers and expressions depend upon the
computer on which the program is run. The characters in C are grouped into the following
categories:

1. Letters
2. Digits
3. Special characters
4. White spaces

The entire character set is given in table


Trigraph characters

The sequence consists of three characters ( two question mark followed by another character)

Ex ??=  # number sign

??(  [ left bracket

5. Tokens

• A smallest individual units in a C program are called Tokens.

• The Tokens in C language include:

• 1. Keywords (eg: float, double etc.,)

• 2. Constants (eg: 100, -10.0 etc., )

• 3. Strings (eg: “ABC”, “month” etc.,)

• 4. Operators (eg: +, - etc.,)

• 5. Identifiers (eg: main, total etc.,)

• 6. Special Symbols (eg: [ ],( ) etc.,)

6. Keywords

• Keywords are the system defined identifiers.


• All keywords have fixed meanings that meaning cannot be changed.
• White spaces are not allowed in keywords.
• Keyword may not be used as an identifier.
• It is strongly recommended that keywords should be in lower case letters.
• There are totally 32(Thirty Two) keywords used in a C programming.
The lists of all keywords of ANSI C are listed in table.

int float double long

short signed unsigned const

if else switch break

default do while for

register extern static struct


typedef enum return sizeof

goto union auto case

void char continue volatile

7.Identifiers

• Identifier refers to the names of variables, functions and arrays.

• These are user-defined names and consist of a sequence of letters and digits, with a letter
as a first character.

Rules for Identifiers

• First Character must be an alphabet

• Must consist of only letters, digits or underscore.

• Only first 31 characters are significant

• Cannot use a keyword.

• Must not contain white space.

8.Constant

• A constant in C refer to a fixed value that doesn't change during the execution of a
program.

Numeric Constants

Numeric constants, as the name itself indicates, are those which consist of numerals. They are
further divided into two types:

(a) Integer Constants (b) Real Constants


Integer Constant

• An integer constant is an integer valued number.

• It consists of sequence of digits.

• Integer constants are divided into three different types.

• They are decimal constants (base 10), Octal constants (base 8) and hexadecimal
constants (base 16).

Decimal Integer

• A decimal integer constant consists of any combination of digits taken from the set
0 to 9.

• If the constant consists of two or more digits, the first digit must be other than 0.

• Valid example

 123 -321 0 65478 +78

• Invalid decimal integer constants

• 080 First digit cannot be zero

• 50.3 Illegal character ( . )

• 12,542 Illegal character ( , )

• 25 35 60 Illegal character ( Blank Space )

Octal Integer

• An octal integer constant consists of combination of digits taken from the set 0
through 7.

• However the first digit must be 0, in order to identify the constant as an octal number.

Valid octal integer constants

• 00 06 0753 0663

Invalid octal integer constants

• 543 Does not begin with zero

• 07865 Illegal character ( 8 )


• 06, 593 Illegal character ( , )

• 06.512 Illegal character ( .

Hexadecimal integer constant

• A hexadecimal integer is identified by ox or OX.

• Hexadecimal integer constant consists of digits taken from the set of 0 to 9 and also
include alphabets from A to F (either upper or lower case).

• The letter a to f or A to F represent the decimal values from 10 to 15 respectively i.e.,

• a=10, b=11, c=12, d=13, e=14 and f=15.

Valid hexadecimal integer constants:

0x0 0x1a 0x1BEC 0x7FFF

Invalid hexadecimal integer constants

• 0x16.8b Illegal character ( . )

• 563c Does not begin with 0 or 0x

• 0x7bcg Illegal character ( g )

• 0x12.53 Illegal character ( . )

Real constant

• It represents numbers containing fractional parts (decimal notation). It is also called as


floating point constant.

• In real constant, numbers are shown in decimal notation, having a whole number
followed by decimal notation and fractional part.

• It must have at least one digit.

• It must have a decimal point which may be positive or negative.

• Use of blank space and comma is not allowed between real constants.

• Example: +194.143, -416.41


Exponential form

Another way of representing real constants is the exponential form.

• Exponential form is also known as scientific notation.

• When representing a number in its exponential form, the real constant is represented in
two parts : the mantissa and the exponent.

• The part of the number appearing before the alphabet e is the mantissa and the part
following e is the exponent.

• The general form of the number is thus :

• mantissa e exponent

• The mantissa can be positive or negative with the default sign of the mantissa being
positive.

• - The exponent should have atleast one digit which is a positive or negative integer.

Some valid examples of exponential form of real constants are :

• 3.2e4 (e4 means multiply by 104)

• 4.8e-2 (e-2 means multiply by 10 -2)

• -43e+3 (e3 means multiply by 103)

Invalid examples of exponential form

1.5e -2.5 exponent must be a integer

Single Character Constant

• A Single Character constant contains a single character enclosed within a pair of single
quote marks.

• It is a single alphabet or a digit or a special symbol enclosed in a single quote.

• Maximum length of a character constant is 1.

• Example: 'T', '9', '$' , ‘a’

Character constant have integer values known as ASCII values

String Constant :

A string constant is a sequence of characters enclosed in double quotes.


• It is collection of characters enclosed in double quotes.

• It may contain letters, digits, special characters and blank space.

• Example: "Programming using C, Balagurusamy"

“Hello”

“WELL DONE”

Example : character constant ‘X’ is not equivalent to string constant “X”.

Invalid example for string constant

1. My name is abinesh  Characters are not enclosed in double quotation mark


2. “My name is abinesh  Closing quotation mark is missing

Backslash Character Constant

C supports some special backslash character constants that are used in output functions.
A list of backslash character constants is given in the table.

Constants Name
\a Alert (bell)
\b Backspace
\f Form feed
\n New line
\r Carriage returns
\t Horizontal tab
\v Vertical tab
\’ Apostrophe
\” Double quote
\? Question mark
\\ Backslash
\0 Null character

9. Datatypes

 C language rich in data types.


 The data stored in memory can be of different types.
 For example, your roll number is stored as a number but your name as string.
 Any variable has its associated data type.
 The type of a variable determines the set of values it can have and what operations can be
performed on it.
 Memory requirements for each data type will determine the permissible range of values
for that data type.

ANSI C supports three classes of data types:

 Primary data types

 Derived data Types

 User defined data Types

Primary Datatype

The primary datatypes are as follows

1. int - integer: a whole number.


2. float - floating point value: ie a number with a fractional part.
3. double - a double-precision floating point value.
4. char - a single character.
5. void - Void is a value of a function type that means nothing is returned.

Modifiers are used to alter the meaning of basic data types to fit various needs. Except
the type void, all others data type can have various modifiers preceding them

List of modifiers used in C are:

i) Signed

ii) Unsigned

iii) Long

iv) Short
Integer types

 Integers are whole numbers. C has three classes of integer storage namely, short int, int
and long int in both signed and unsigned forms.

Floating point types

 Floating point numbers are real numbers with 6 digits precision. A double data type is a
precision of 14 digits.

Character types

 A single character can be defined as character type data. The qualifier signed and
unsigned may be explicitly applied.

Void types

 The void has no values. This is usually used to specify the type of functions. The type of
function is said to be void it does not return any value to the calling program.

The table shows the allowed combination of basic data types and qualifiers and their size
and range of values

Keyword Size (bytes) Size in bit Data Range

Char or Signed 1 Byte 8 -128 to +127


char
Unsigned char 1 Byte 8 0 to 255

int or 2 Bytes 16 -32768 to +32767


signed int
unsigned int 2 Bytes 16 0 to 65535

Short int or 1 Byte 8 -128 to +127


signed short
int
unsigned short 1 Byte 8 0 to 255
int
long int or 4 Bytes 32 -2,147,483,648 to
signed long int +2,147,483,647
unsigned long 4 Bytes 32 0 to 4,294,967,295
int
float 4 Bytes 32 -3.4e38 to +3.4e38

double 8 Bytes 64 -1.7e308 to +1.7e308

long double 12-16 Bytes 80 -3.4e4932 to


+1.1e4932

Derived data types in C


Those data types which are derived from the fundamental data types are called derived data
types. Function, arrays, and pointers are derived data types in C programming language.

User-Defined Data type

Those data types which are defined by the user as per his/her will are called user-defined data
types. Examples of such data types are structure, union and enumeration.

1. typedef

C supports a feature known as type definition that allows users to define an identifier
that represent an existing data type. It takes the general form as

typedef type identifier;


 where type refers to an existing data type.
 Identifier refers to the new name given to the data type.
 The identifiers can be later used to declare variables.

Examples

1. typedef int units;


2. typedef float marks;
3. typedef unsigned int price;
2. Enumerated Datatype

Enumeration is a special data type that consists of integral constants, and each of them is
assigned with a specific name. "enum" keyword is used to define the enumerated data type. It is
defined as follows

Enum identifier{ value1,value2,…… valuen};

The identifier is a user-defined enumerated data type which can be used to declare variables that
can have one of the values enclosed within the braces. After definition, variables can be declared
to this type.

Example

enum day { Monday, Tuesday,Sunday};

The compiler automatically assigns integer digits beginning with 0.

10.Variables

• A variable is a data name which is used to store data value.


• A variable may take different values at different times during program execution.
• Variable name is a name given to memory cell location of a computer where data is
stored.
• A variable name can be chosen by the programmer as meaningful one to reflect its
function.
Examples

Average, height, Total, class_strength, age , profit, mark1

Rules

A variable name must follow these conditions:

1. They must begin with a letter


2. ANSI recognizes a length of 31 characters.
3. Uppercase and lower cases are significant.
4. It should not be a keyword.
5. White space is not allowed.
Declaration of variables

The declaration of variable must be done before they are used in the program.
Declaration of variable does two things

1. It tells the compiler what the variable name is.


2. It specifies what type of data the variable will hold.

Primary type declaration

The syntax for declaring the variables is as follows :

Datatype variablename;

datatype v1, v2, ....vn ;

where data type indicates the type and v1, v2, ..., vn indicate the names of the variables.
If you are declaring multiple variables in the same type declaration, then they should be
separated by commas. The type declaration statement itself should end with the semicolon.

Examples of declaring variables and their types:

int a;

char first;

float percent, average;

double ratio;

int sum;

float price$; // Invalid

float price_value; or float pricevalue;

Here in the first statement the variable a is declared to be of type int, percent and average are real
variables whose type is declared as float, first is a character variable whose type is declared as
char.

 If two are more variables of the same data type has to be declared they can be clubbed
as shown in example given below.

i. int a; int b; int c;


this is same as

int a, b, c;

ii. float d; float e; float f;

this can be written as

float d, e, f;

Assigning Values to Variables

Values can be assigned to variables using assignment operator “=” as follows

variablename = value;
Example

initial_value=0; int initial_value;

final_value=100; int final_value;

balance=75.84; float balance;

yes=’x’; char yes;

It is also possible to assign the value of an expression on the right to the variable on the left.

c = a + b;

z = p/q * r;

p = p + 10;

Variables can also be assigned values at the time of their declaration. The following
statements are valid in C :

int i = 10;

float pi = 3.14;

char ch1 = ‘Q’;

double balance = 75.84;

This process of giving initial values to variables is called initialization.

It is also possible to initialize multiple variables using multiple assignment operators as :


a = b = c = 1;
x = y = z = MAX;
The first statement initializes the variables a,b and c to one. The second initializes x,y and z with
MAX. MAX is a symbolic constant.

Declaring a variable as constant


The value of the certain variable to remain constant during the execution of the
program. We can achieve this by declaring the variable with const qualifier at the time of
initialization.
For example,

const float tax_rate = 0.30;

const float pi = 3.14;


The above statement tells the compiler that value of variable must not be modified during the
execution of the program. Any attempt change the value will generate a compile time error.

11.Operators

an operator is a symbol that tells the compiler or interpreter to perform a specific mathematical, logical,
or manipulative operation on one or more operands (values or variables).

Key Points on Operators:

1. Operands: These are the variables or values on which the operator acts. For example, in
a + b, a and b are operands, and + is the operator.
2. Expressions: Operators combine with operands to create expressions. For example, a +
b is an expression that adds a and b.

Types of operators

 Arithmetic Operators
 Relational Operators
 Logical Operators
 Bitwise Operators
 Assignment Operators
 Increment and Decrement Operators
 Conditional (Ternary) Operator
 Sizeof Operator
 Comma Operator
1. Arithmetic Operators

These are used for performing basic mathematical operations.

Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus (remainder)

Note: The division operator (/) yields an integer quotient if both operands are integers;
otherwise, it gives a floating-point result.

Example program
2. Relational Operators

Used to compare two values, often in decision-making structures.

Operator Description
== Equal to
!= Not equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
Examples :

Expression Evaluate to

(5 <= 10) ———————— 1 true

(-35 > 10) ———————— 0

(X < 10) ———————— 1 ( if value of x is less than 10)

3. Logical Operators

These are used to combine conditional expressions.

Operator Description
&& Logical AND (true if both are true)
|| Logical OR
! Logical NOT (reverses truth value)
Logical NOT

Logical AND
Logical OR

C has a set of short hand assignment operator of the form


6. Increment and Decrement Operators

Used to increase or decrease the value of a variable by 1.

Operator Description
++ Increment (adds 1)
-- Decrement (subtracts 1)

Prefix vs. Postfix: ++a (prefix) increments before using the value, while a++ (postfix) uses the
value first, then increments.
7. Conditional (Ternary) Operator

A compact form of if-else for simple conditional assignments.

Syntax Description
condition ? expr1 : expr2 If condition is true, expr1 is evaluated; otherwise, expr2.
Bitwise Operators

Perform operations on binary representations of numbers, often used in low-level programming.

Operator Description
& Bitwise AND
| Bitwise OR
^ Bitwise XOR
~ Bitwise NOT
<< Left shift
>> Right shift

Sizeof Operator

Returns the size (in bytes) of a data type or variable.

Syntax Description
sizeof(data_type) Returns the size in bytes of the specified type

Formatted Input
Formatted functions facilitate supplying input in fixed formats. Formatted
input refers to an input data that has been arranged in a particular format. The
general form of scanf is:

Common Format Specifiers

 %d : Integer
 %f : Floating-point
 %c : Character
 %s : String
 %lf : Double

Example: scanf() to read integer, real (floating-point), character, and string inputs in C:
#include <stdio.h>

int main() {
int integer;
float real;
char character;
char string[50]; // Large enough to hold the input string

printf("Enter an integer: ");


scanf("%d", &integer);

printf("Enter a real number: ");


scanf("%f", &real);

printf("Enter a character: ");


scanf(" %c", &character); // Notice the space before %c to consume any leftover
newline

printf("Enter a string: ");


scanf("%s", string); // No & needed for strings, as the variable name acts as an
address
// Output the values
printf("\nYou entered:\n");
printf("Integer: %d\n", integer);
printf("Real Number: %.2f\n", real);
printf("Character: %c\n", character);
printf("String: %s\n", string);

return 0;
}

Explanation:

 Integer (%d): Reads an integer value and stores it in integer.


 Real (%f): Reads a floating-point number and stores it in real.
 Character (%c): Reads a single character. A leading space before %c helps avoid reading
a newline from previous input.
 String (%s): Reads a string up to whitespace and stores it in string. No & is needed as
arrays are already pointers to their first element.

Formatted output functions providing output in desired formats.


Formatting Options

1. Width Specifier: Defines the minimum width for printing a value (e.g., %5d for an
integer with at least 5 spaces).
2. Precision: Controls the number of digits after the decimal point for floating-point values
(e.g., %.2f for two decimal places).
3. Alignment: By default, printf() right-aligns values. Left alignment can be specified
with - (e.g., %-5d).

Example of Formatted Output


#include <stdio.h>

int main() {
int age = 25;
float height = 5.923;
char initial = 'A';
char name[] = "Alice";

printf("Integer (age): %d\n", age);


printf("Real number (height to 2 decimal places): %.2f\n", height);
printf("Character (initial): %c\n", initial);
printf("String (name): %s\n", name);

// Using width specifiers


printf("Age with width 5: %5d\n", age);
printf("Left-aligned age with width 5: %-5d\n", age);

return 0;
}

Output Explanation

 Precision for Floats (%.2f): Limits the decimal places in height to 2.


 Width Specifier (%5d): Prints age with a minimum width of 5, padding with spaces if
necessary.
 Left Alignment (%-5d): Left-aligns age within a width of 5.
Question Bank

5 Mark

Features of C, Structure of C, Tokens, Datatypes, Variables

15 Mark

Constant, Operator, Formatted input & output

You might also like