Unit I C

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 27

INTRODUCTION

C is a powerful general purpose and most popular computer programming


language. It was developed in the 1972’s by Dennis M. Ritche at Bell Telephone
laboratories (AT& T Bell Labs). C was extensively used in its development C is an
outgrowth of BCPL (Basic combined Programming Language) developed by Martin
Richards University.

IMPORTANCE OF C

C is often called a middle-level computer language, because it has the features


of both high-level languages, such as BASIC, PASCAL etc., and low-level languages
such as assembly language.

C is highly portable i.e., Software written for one computer can be run on another
computer. C language is well suited for structured programming. An important feature of
‘C’ is its ability to extend itself. A C program is basically a collection of functions. It
encourages us to write out own functions and add to the C library. Also C is modular, i.e.,
a unit of task can be performed by a single function and this unit of task can be reutilized
when needed. The large number of functions makes programming task simple.

BASIC STRUTURE OF A ‘C’ PROGRAM:

C programs consist of one or more functions. Each function performs a specific


task. A function is a group of sequences of statements that are together. And it is similar
to subprograms (or subroutines) in other high-level languages like Pascal.

Every C program starts with a function called main(). This is the place where
program execution begins. Hence, there should be main() function in every program. The
functions are building blocks of C program. Each function has a name and a list of
parameters ( or arguments).

1
Documentation section
Linkage section
Definition section optional
Global declaration section

main ()
{
Declaration part
Execution part / statement part
}
Sub program section
Or optional
User defined section

Documentation section:
This section group of comments that explains about program name, purpose of the
program, program logic, programmer name, date of written program etc.
Comments can be included anywhere into the program. Comments are enclosed
between /* and */.
Linkage Section:
It is the pre processing directive operation section under this we can include the
header files with the # include <header file name. h>
Or
# include “header file name. h”
Whenever we are using standard functions into the main program those are
referred into the header files. When we included header file. Otherwise it gives error
message header file inclusion error
# include < stdio. h> or # include < graphic. h>

2
Definition section:
It is also the pre-processing directive operation. Under this we can define the
symbolic constant with the # define identifier data.
Example: #define
These symbolic constant calls as macros. These macros are global.

Global declaration section:


Under this section we can declared the global variables. These variables can be
used in main program or other user defined function without declaration.
main():
main is a standard function to every program. Without main function program could
not process. It is compulsory for every program.
{ (left brace):
It indicates the beginning of the main. It is also compulsory.
Declaration part:
Whatever the variables, constants, array etc. we are going to be used into the
statement part those thing should be declared along with their storage class and type and
identifier name.
The syntax follows:
Storage Class data type variables
(identifiers)
Separate by a comma.
Example: auto int a,b,c;
Extern int x,y,z;
} (right brace):
It indicates the ending of the program it is also compulsory.
Subprograms:
Here we can write the user define sub-programs when ever we are facing repetitive
task then we can write user defined function. We can write any number of sub programs
there is no limit.

3
The following is a simple C program that prints a message on the screen.
# include <stdio.h>
/* A simple program for printing a message */
main()
{
printf( “ hello , this is a C program.”);
}

The first line

# include <stdio.h>
tells the compiler to read the file stdio.h and include its contents in this file. stdio.h, one of
header files, contain the information about input output functions. The next line is a
comment line Comments in the C program are optional and may appear anywhere in a C
program. Comments are enclosed between /* and */.
main() is the start of the main program. The word main is followed by a pair of
ordinary parenthesis (), which indicates that main is also a function. The left brace {
represents the beginning of the function where as the right brace } represents the end of
the function. It means, the braces enclose the body of function. In this program, the body
consists of only one statement, the one beginning with printf. The printf() function is
causes its arguments to printed on the computer screen. The closing (right) brace of the
main function is the logical end of the program.

The following are some of rules to write C programs.

1. All C statements must end with semicolon.


2. C is case-sensitive. That is upper case and lower case characters are different.
Generally the statements are typed in lower case.
3. A C statement can be written in one line or it can split into multiple lines.
4. Braces must always match upon pairs, i.e., every opening brace { must have a
matching closing brace }.

4
5. No restriction in using blank spaces or blank lines that separates different words
or different parts of program. Blank spaces improve the readability of the
statements. But blank spaces are not allowed within a variable, constant or
keyword.
6. Comments cannot be nested. For example,
/* A simple ‘C’ program, /* it prints a message */ */
is not valid.
7. A comment can be split into more than one line.

Execution of C program:
Steps to be followed in writing and running a C program.
(a) Creation of Source Program
(b) Compilation of the Program (Alt + F9).
(c) Program Execution (ctrl + F9).
(d) Output or Console Screen ( Alt +f5).

5
CONSTANTS, VARIABLES, AND DATA TYPES:
C Tokens
A C program must be syntactically valid sequences of characters of the language.
In every C program, the most basic element recognized by the compiler is single character
or group of characters called C tokens.
Steps in learning C language are…
1. Character Set – Alphabets, Digits and Special Symbols
2. Datatypes, Constants, Variables and Keywords
3. Instructions
4. Functions, Program
The C character set:
The C character set includes the upper case letters A to Z, the lower case a to z,
the decimal digits 0 to 9 and certain special characters/symbols. The character set is
given bellow.
Alphabets A, B, C, …….Z
a, b, c,. ……. Z
Digits 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
Special characters/Symbols~, . : ; ? ‘ “ ! ( ) [ ] { } / \ < > = + - $ # & * % ^
White Spaces blank space,horizontal,carriage return,new line
and form feed
Keywords and Identifiers:
Key words are predefined tokens in C. these are also called as reserved words.
Key words have special meaning to the C compiler. These key words can be only for
their intended action. They cannot be used for any other pupose.
The standard key words are:
auto break case char const continue
default do double else enum extern
float for goto if int long
register return short signed sizeof static
struct switch typedef union unsigned void
volatile while

6
Data types and Sizes:
A data type a set of values and the operations that can be performed on them.
Every data type item (constant, variable etc.) in a C program has a data type associated
with it.
The memory requirements for each data type will determine the permissible range
of values for that type. These requirements may vary from one compiler to another.
Generally the following rule is true for any complier to specify the size of data types:
char ≤ sizeof(short int)≤ sizeof(int) ≤ sizeof(long int) ≤ sizeof(float) ≤ sizeof(double)

Data type Format Specifier

int %d
unsigned int %u
long int %ld
unsigned long int %lu
char %c
float %f
double %lf
long double %Lf

7
Datatype Description Size Range
in Bytes
Signed Character 1 -128 to +127
char/char
Unsigned char Unsigned character 1 0 to 255

Short signed int Short signed integer 2 -32768 to +32767

Short unsigned Short unsigned 2 0 to 65535


integer
int
Long signed int Long signed integer 4 -2,147,483,648 to
2,147,483,648
Long unsigned Long signed integer 4 0 to 4,294,967,295
int
Float Floating point 4 -3.4 e38 to +3.4 e38

Double Double floating point 8 -1.7 e 308 to +1.7 e 308

Long double Long double floating 10 -1.7 e 4932 to + 1.7 e


point
4932
Signed :
It indicates all the bits are positive. Means that it takes only positive values as
well as negative values.
Unsigned:
It indicates all the bits are positive only(all values are positive).
C Datatypes

Basic data types Derived data types

Char integer float double void array structure union pointer

8
Constants and variables:
A constant is a literal, which remain unchanged during the execution of a program.
A variable is a name that is used to store data value and is allowed to vary the value
during the program execution.

Constants:
A constant is a fixed value that cannot be altered during the execution of a program.
C Constants can be classified into two categories.
1. Primary constants.
2. Secondary constants.
Constants

Primary constants Secondary constants

Numeric character logical Array structure union pointer…etc

Integer float
Single char string
Integer constants:
An integer constant is an integer-valued number consisting of a sequence of digits.
The following are the rules for constructing integer constants.
1) An integer constant must have at least one digit.
2) It should not contain either a decimal point or exponent.
3) If a constant is positive, it may not be preceded by a plus sign. If it is a negative,
it must be preceded by a minus sign.
4) Commas, blanks and non digit-characters are not allowed in integer constants.
5) The valid range is –32768 to +32767.
These range my larger for 32 bit computers.

9
Real constants:
Real constants are often called floating-point constants. These are two ways to
represent a real constant decimal form and exponential form.
Real constants expressed in decimal form must have at least one digit and one
decimal point. As in the case of integers, the real constants can be either positive or
negative. Commas, blanks, and non-digit characters are not allowed with in a real
constant.
In exponential form, a real constant is expressed as an integer number or a decimal
number multiplied by an integral power of 10. This simplifies the writing of very large and
very small numbers. In this representation, letter e is written instead of 10, the power is
written just to the right of e. generally, the part appearing before e is called mantissa,
whereas the part following e is called exponent.
Rules for constructing real constants are:
1) The mantissa part and the exponential part should be separated by a letter e.
2) The mantissa part may have a positive or negative sign. Default sign of mantissa
part is positive.
3) Commas, blanks and non-digit characters are not allowed with in a real constant.
4) The exponent part must be an integer.
5) The mantissa part must have at least one digit.
6) Range of real constants expressed in exponential form is –3.4e38 to +3.4e38
String constants:
A string constant is a sequence of characters enclosed in double quote. The
characters may be letters, numbers, blank space or special characters.
Example: “welcome”
“this is a sting”
“a+b=8”
““
“a”
Note that ““ is a null string or empty string. And the single string constant “a” is not
equivalent to the single character constant ‘a’.

10
Each sting constant must end with a special character ‘\0’. This character is called
null character and used to terminate the string. The compiler automatically places a null
‘\0’ character at the end of every string constant. This constant is not visible when the
string is displayed. The null character is very much useful in finding the end of a string.

Variables:
A variable can be considered as a name given to the location in memory. The term
variable is used to denote any value that is referred to a name instead of explicit value. A
variable is able to hold different values during execution of a program.
For example, in the equation 2x+3y=10; since x and y can change, they are
variables, whereas 2,3 and 10 cannot change, hence they are constants.
Rules for constructing variable names:
1) The name of a variable is composed of one to several characters; the first of which
must be a letter.
2) No special characters other than letters, digits, and underscore can be used in
variable name. some compilers permit underscore as the first character.
3) Commas, or blanks are not allowed with in a variable name.
4) Upper case and lower case letters are significant (different).
5) The variable name should not be a C key word. Also it should not have the same
name as a function.
Examples: income, name, rate, marks, sno, etc.
Operators in C :
There are 8 types of operators in C. They are
1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Assignment operators && Compound assignment operators
5. Increment and Decrement operators
6. Bit wise operators
7. Conditional operators
8. Special operators

11
1). Arithmetic Operators:-
These are used for the mathematical operations.
Operator Meaning
+ addition
- subtraction
* multiplication
/ division
% modulus
 The division operator ( / ) gives the quotient of the division.
 The modulus operator ( % ) gives the remainder of the division.
Note:- All operators must works only with two operands. so these are also called as the
"Binary operators". Example:
main()
{
int a =10,b=20,c; /* variable declaration part */
c=a+b;
printf(“%d”, c); /* it displays addition of c value */
c= a-b;
printf(“%d”, c);
c= a*b;
printf(“%d”, c);
c= a/b;
printf(“%d”, c);
c= a%b;
printf(“%d”, c);
getch();
}
Note:
- Compilation of the Program (Alt + F9).
- Program Execution (ctrl + F9).
- Output or Console Screen ( Alt +f5).

12
Output:
30
-10
200
0
10
2). Relational operators:-
These are the operators, which tell the relation between the values or operands.
In C language all relational and logical operators returns 1 or zero. If the expression is
true then it will gives 1 other wise 0.
Operator Meaning
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to
== Equals to
!= Not equals
Examples on relational operators:-
- a=3<4; 1
- a=3>2; 1
- a=2>=3; 0
- a= 5<=5; 1
- a= 5==5; 1
- a= 5!=8; 1
3). Logical operator:-
The logical operators are used to compare more than one condition
Operator Meaning
&& Logical AND
|| Logical OR
! Logical NOT
Truth table for AND (&&) operator:

13
Expression1 Expression2 Result
T T T
T F F
F T F
F F F

Truth table for OR (||) operator:


Expression1 Expression2 Result
T T T
T F T
F T T
F F F

Truth table for NOT (!) operator:


Expression1 Result
T F
F T

examples:-
1. a = 1&&1; 1
2. a = 7&&5; 1
3. a = 5>4 && 4>10; 0
4. a = 5>4 || 4>10; 1
5. a = 1 || 0 1
6. a = !1 0
7. a = 1 && 4>3 1
8. a = ! (5>5); 1
4). Assignment operator (=):
The assignment operator can be used to store the data into the identifier (variable).
The nature of storage is that right side of the data stored into left side of identifier.
Ex: a=10;

14
Assignment operators (+=, - =, * =, / =, % =):
The compound assignment operator can be used to minimize the arithmetic
operations.
Example:
a+= 1; it is equal to a= a+1;
b+=a; it is equal to b= b + a;
c-=a; it is equal to c= c-a;
d*= a ; it is equal to d= d*a;
a/=b; it is equal to a=a/b;
b%=a; it is equal to b=b%a;

5). Increment and Decrement operators:

Increment (++)
Always it increment only one value to the existing identifier. They are two types.
++a pre-increment.
a++ post-increment

pre- increment:
When ever the pre-increment operators using into the arithmetic expressions then
it is increasing the one value to the adjusting identifier and participating into the
expressions. This can be written ++identifier.
Ex: ++a;
Post- increment:
When ever the post incrimination operators including into the arithmetic operators
then the identifier values directly participating into the arithmetic expressions. After that
the identifier value incrementing by one only.
Syntax:
identifier ++ ;
Ex: a++;

15
Decrement operator (- - ):
It is always decreased by one value and result stored into the same identifier. We
have two types of decrement operators.
Pre – decrement ex: --a;
Post – decrement ex: a--;

Pre – decrement:
When ever pre – decrement operators using into the arithmetic expressions then
it is decreasing the one value to the adjusting identifier and processing into the
expressions. This can be written as -- identifier.
Ex: --a;

Post decrement:
When ever the post decrement operators including into the arithmetic operations
then the identifier values directly participating into the arithmetic expressions. After that
the identifier values decrement by one only.
Syntax:
Identifier --;

6). Bitwise operators:


Operator meaning
& Bitwise And
| Bitwise OR
^ Bitwise Exclusive OR (XOR)
<< Left Shift
>> Right shift
~ One’s Complement
The bit wise operators can be used to do the binary operation (binary
manipulations). Like addition sub multiplication etc. C allows the programmer to interact
directly with the hardware of a particular system through bitwise operators and

16
expression. These operators work only with int and char datatypes and cannot be used
with float or double type.
Bitwise Exclusive OR (XOR) Operator:
An exclusive OR set the 0 bit 1, if both bits that are compared are different. The
truth-values for XOR are.
0 ^ 0 = 0
0 ^ 1 = 1
1 ^ 0 = 1
1 ^ 1 = 0
for example 127 ^ 120 is
01111111 127 in binary
01111000 120 in binary
XOR result= 00000111
Bitwise complement operator:
The bitwise complement (or one’s complement) operator ~ (called tilde) changes
each 1 bit in its operand to 0 and changes 0 bit to 1, ~0= 1, ~1= 0.
For example:
Consider that , the int variable has the value 5.
The binary number is 0000000000000101
The bitwise complement ~ is 1111111111111010
Shift Operators >> and <<
The shift operators move all the bits in a variable to the right or left as specified.
The general form of the shift right statement is
Variable >> number of bit positions.
The general form of the shift left statement is
Variable << number of bit positions,
As bit are shifted out to one end, the zeros are entered from the other end. The bits which
are shifted out are lost. The shifting of bit is not a rotation of bits.
Consider the following operations where the initial value of x is 9
X=9 00001001 9
X << 1 00010010 18

17
X << 1 00100100 36
X << 2 10010000 144
X >> 1 01001000 72
X >> 1 00100100 36
X >> 2 00001001 9
It can be noted from the above operations that the left shift by one place is nothing
but multiplications of a number with 2, and the right shift by one place is nothing but
division of a number by 2 .
7). Conditional operator (?:)
C provides a peculiar operator ?: which is useful in reducing the code. It is ternary
operator requiring three operands.
The general format is
Exp1 ? Exp2 : Exp3 ;
Where exp1, exp2 and exp3 are expressions. The constituents of conditional operator
are separated in conditional expressions and the order should not be changed, that is
should be in between the first two expressions and : should be between the second and
third expressions.
In the above conditional expression, exp1 is evaluated first. If the value of exp1 is
non zero (true), then the value returned will be exp2. if the value of exp1 is zero (false).
Then the value returned will be exp3.
Example:
#include < stdio.h>
main()
{
int option;
printf(“Enter any number “);
scanf(“%d”, &option);
option ? printf(“Entered non-zero number”): printf(“entered zero”);
}
example 2: z= (x>10 ? 8: -3);

18
8). Special operators:
1. Comma operator:-
The comma operator allows two or more different expressions to appear when
only one expression is expected. The expressions are separated by the comma
operator.
The general form is
Exp1,exp2, exp3,…expn

2. Size of operator
The sizeof operator in c will determine the size of variables storage in bytes.
The sizeof operator is a unary operator and can be used to know the size of any
variable, constant, etc. the sizeof operator is very useful in writing machine-
independent program.

MANAGING INPUT AND OUTPUT FUNCTIONS:

printf() function: Writing Output Data


The printf() function is used to write information to standard output (normally
monitor screen). The structure of this function is
printf(“ control string “, var1,var2,var3,…….var n);
Example:
printf(“%d”, a);
scanf() function: getting user input
The real power of a technical C program is its ability to interact with the program
user. This means that the program gets input values for variables from users.
The scanf() function is a built-in C function that allows a program to get user input
from the keyboard.
Syntax: scanf(“control string”, &var1,&var2,……&var n);

19
GETS() :

gets reads a whole line of input into a string until a newline or EOF is encountered. It is
critical to ensure that the string is large enough to hold any expected input lines.

When all input is finished, NULL as defined in stdio.h is returned.

PUTS():

puts writes a string to the output, and follows it with a newline character.

Example: Program which uses gets and puts to double space typed input.

#include <stdio.h>

main()
{ char line[256]; /* Define string sufficiently large to
store a line of input */

while(gets(line) != NULL) /* Read line */


{ puts(line); /* Print line */
printf("\n"); /* Print blank line */
}
}

Note that putchar, printf and puts can be freely used together. So can getchar, scanf and
gets.

getchar() and putchar functions: the standard function that prints a single character on
the standard devices.

Ex:

main()

Char ch;

Getchar(ch);

Putchar(ch);

20
ESCAPE SEQUENCES:

Escape sequences are special notations through which we can display our data

Variety of ways:

Some escape sequences and their functions are as follows:

Escape Description Example


Sequence

\n Perform new line & Carriage return operation printf("A\nB");

\t Prints a tab sequence on screen printf ("A\tb");

\’ Prints a single quote character on screen printf ("\’a\’");

\" Prints a double quote character on Screen printf ("\"a\"");

\r Perform carriage return operation printf ("a\rb")

\b Remove one character from left printf ("a\bHi!" );

Example:

#include <stdio.h>

#include <conio.h>

void main(void)

printf( " Example Program (Escape Sequence) \n");

printf( " -----------------------------------------------\n");

printf( "Escape sequnce \t Meaning\n");

printf( " -------------------------------------------------\n");

printf(" \\\\ \t \\" \n");

printf(" \\\’ \t \’ \n");

printf(" \\\" \t \" \n");

21
printf(" \\n \t line feed & carriage return\n ");

printf(" \\t \t Tab characters or eigth spaces\n");

printf(" \\b \t Erase one char from right to left\n");

printf(" \\r \t perform only line feed\n");

getch();

This program produces following output

Example Program (Escape Sequence)

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

Escape Sequence Meaning

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

\\ \

\’ ‘

\" \"

\n line feed & carriage return

\t Tab Characters or eight spaces

\b Erase one char from right to left

\r perform only line feed.

22
C LIBRARY FUNCTIONS:

Header file Description


This is standard input/output header file in which Input/Output
stdio.h
functions are declared
conio.h This is console input/output header file
string.h All string related functions are defined in this header file
stdlib.h This header file contains general functions used in C programs
math.h All maths related functions are defined in this header file
time.h This header file contains time and clock related functions
ctype.h All character handling functions are defined in this header file

STORAGE CLASSES:

Storage class specifiers in C language tells the compiler where to store a variable, how to store the
variable, what is the initial value of the variable and life time of the variable.

Syntax:
storage_specifier data_type variable _name;

Types of Storage Class Specifiers in C:

There are 4 storage class specifiers available in C language. They are,

1. auto
2. extern
3. static
4. register

Storage Specifier Description


Storage place: CPU Memory
Initial/default value: Garbage value
Auto
Scope: local
Life: Within the function only.
Storage place: CPU memory
Initial/default value: Zero
Extern Scope: Global
Life: Till the end of the main program. Variable definition might
be anywhere in the C program.

23
Storage place: CPU memory
Initial/default value: Zero
static Scope: local
Life: Retains the value of the variable between different function
calls.
Storage place: Register memory
Initial/default value: Garbage value
Register
Scope: local
Life: Within the function only.
Note:

 For faster access of a variable, it is better to go for register specifiers rather than auto
specifiers.
 Because, register variables are stored in register memory whereas auto variables are stored
in main CPU memory.
 Only few variables can be stored in register memory. So, we can use variables as register
that are used very often in a C program.

1 #include<stdio.h>
2 void increment(void);
3 int main()
4 {
5 increment();
6 increment();
7 increment();
8 increment();
9 return 0;
10 }
11
12 void increment(void)
13 {
14 auto int i = 0 ;
15 printf ( "%d ", i ) ;
16 i++;
17 }
Output:
0000
2. Example program for static variable in C:

Static variables retain the value of the variable between different function calls.

1 //C static example


2 #include<stdio.h>

24
3 void increment(void);
4 int main()
5 {
6 increment();
7 increment();
8 increment();
9 increment();
10 return 0;
11 }
12 void increment(void)
13 {
14 static int i = 0 ;
15 printf ( "%d ", i ) ;
16 i++;
17 }
Output:
0123
3. Example program for extern variable in C:

The scope of this extern variable is throughout the main program. It is equivalent to global variable.
Definition for extern variable might be anywhere in the C program.

1 #include<stdio.h>
2
3 int x = 10 ;
4 int main( )
5 {
6 extern int y;
7 printf("The value of x is %d \n",x);
8 printf("The value of y is %d",y);
9 return 0;
10 }
11 int y=50;
Output:
The value of x is 10
The value of y is 50
4. Example program for register variable in C:

 Register variables are also local variables, but stored in register memory. Whereas, auto
variables are stored in main CPU memory.
 Register variables will be accessed very faster than the normal variables since they are
stored in register memory rather than main memory.

25
 But, only limited variables can be used as register since register size is very low. (16 bits,
32 bits or 64 bits)

1 #include <stdio.h>
2 int main()
3 {
4 register int i;
5 int arr[5];// declaring array
6 arr[0] = 10;// Initializing array
7 arr[1] = 20;
8 arr[2] = 30;
9 arr[3] = 40;
10 arr[4] = 50;
11 for (i=0;i<5;i++)
12 {
13 // Accessing each variable
14 printf("value of arr[%d] is %d \n", i, arr[i]);
15 }
16 return 0;
17 }
Output:
value of arr[0] is 10
value of arr[1] is 20
value of arr[2] is 30
value of arr[3] is 40
value of arr[4] is 50

COMPILER DIRECTORIES:

A preprocessor is a system software that consists of special statement called directives.


When a C program is compiled the source program is run through the preprocessor.

#define directive

#if

#include

#endif

26
Common Short cut Keys Description

F2 press to Save current work

F3 press to open an existing file

ALT-F3 press to close current

ALT-F9 press to compile only

ALT-F5 press to view the desired output of the program.

CTRL-F9 press to compile+run

ALT-X or ALT-F-X press to exit from TC IDE

27

You might also like