Unit 2 New (C Prog)
Unit 2 New (C Prog)
PROGRAM: A computer program is a set of instructions for a computer to perform a specific task. programs
are written in a programming language , then translated into machine code by a compiler and linker so that the
computer can execute it directly or run it line by line (interpreted) by an interpreter program.
PROGRAMMING: The act or process of planning or writing a computer program.
Every program is limited by the language which is used to write it. C is a programmer's language. Unlike
BASIC or Pascal, C was not written as a teaching aid, but as an implementation language. C is a computer
language and a programming tool which has grown popular because programmers like it! It is a tricky language
but a masterful one. C is ideally suited to modern computers and modern programming.
C Language:
USES OF C
• C language is primarily used for system programming. The portability, efficiency, the ability to access
specific hardware addresses and low runtime demand on system resources makes it a good choice for
implementing operating systems and embedded system applications.
• C has been so widely accepted by professionals that compilers, libraries, and interpreters of other
programming languages are often implemented in C.
• For portability and convenience reasons, C is sometimes used as an intermediate language by
implementations of other languages.
• C is widely used to implement end-user applications.
Files in a C program
Pre-
File proce Files
Files
STRUCTURE OF PROGRAM
The structure of a C program is a protocol (rules) to the programmer, while writing a C program. The general
basic structure of C program is shown in the figure below. The whole program is controlled within main ( )
along with left brace denoted by “{” and right braces denoted by “}”. If you need to declare local variables and
executable program structures are enclosed within “{” and “}” is called the body of the main function. The
main ( ) function can be preceded by documentation, preprocessor statements and global declarations.
Documentations:
The documentation section consist of a set of comment lines giving the name of the program, the another name
and other details, which the programmer would like to use later.
Preprocessor Statements (DIRECTIVE)
These statements instruct the compiler to include C preprocessors such as header files and symbolic constants
before compiling the C program. Some of the preprocessor statements are listed below.
The preprocessor statement begin with # symbol
Global Declarations
The variables are declared before the main ( ) function as well as user defined functions are called global
variables. These global variables can be accessed by all the user defined functions including main ( ) function.
The main ( ) function
Each and Every C program should contain only one main ( ). The C program execution starts with main ( )
function. No C program is executed without the main function. The main ( ) function should be written in small
(lowercase) letters and it should not be terminated by semicolon. Main ( ) executes user defined program
statements, library functions and user defined functions and all these statements should be enclosed within left
and right braces.
Braces
Every C program should have a pair of curly braces ({, }). The left braces indicates the beginning of the main (
) function and the right braces indicates the end of the main ( ) function. These braces can also be used to
indicate the user-defined functions beginning and ending. These two braces can also be used in compound
statements.
Local Declarations
The variable declaration is a part of C program and all the variables are used in main ( ) function should be
declared in the local declaration section is called local variables. Not only variables, we can also declare arrays,
functions, pointers etc. These variables can also be initialized with basic data types. For examples.
Code:
main ( )
{
int sum = 0;
int x;
float y;
}
Here, the variable sum is declared as integer variable and it is initialized to zero. Other variables declared as int
and float and these variables inside any function are called local variables.
Program statements
These statements are building blocks of a program. They represent instructions to the computer to perform a
specific task (operations). An instruction may contain an input-output statements, arithmetic statements, control
statements, simple assignment statements and any other statements and it also includes comments that are
enclosed within /* and */ . The comment statements are not compiled and executed and each executable
statement should be terminated with semicolon.
User defined functions
These are subprograms, generally, a subprogram is a function and these functions are written by the user are
called user ; defined functions. These functions are performed by user specific tasks and this also contains set of
program statements. They may be written before or after a main () function and called within main () function.
This is an optional to the programmer.
Now, let us write a small program to display some message shown below.
Code:
# include <stdio.h>
main()
{
printf ("welcome to the world of C/n");
}
CHARACTER SET: Character set are the set of alphabets, letters and some special characters that are valid in
C language.
Alphabets: Uppercase: A B C .................................... X Y Z
Lowercase: a b c ...................................... x y z
Digits: 0 1 2 3 4 5 6 8 9
Special Characters:
Special Characters in C language
, < > . _ ( ) ; $ : % [ ] # ?
' & { } " ^ ! * / | - \ ~ +
White space Characters: blank space, new line, horizontal tab, carriage return and form feed.
USING COMMENTS
• It is a good programming practice to place some comments in the code to help the reader understand the
code clearly.
• Comments are just a way of explaining what a program does. It is merely an internal program
documentation.
• The compiler ignores the comments when forming the object file. This means that the comments are
non-executable statements.
C supports two types of commenting.
• // is used to comment a single statement. This is known as a line comment. A line comment can be
placed anywhere on the line and it does not require to be specifically ended as the end of the line
automatically ends the line.
• /* is used to comment multiple statements. A /* is ended with */ and all statements that lie within these
characters are commented.
C TOKENS
Tokens are individual words and punctuation marks in passage of text. In C, program the smallest individual
units are known as C Tokens. C has six types of Tokens. The Tokens are shown in figure.
1.Keywords
• C has a set of 32 reserved words often known as keywords. All keywords are basically a sequence of
characters that have a fixed meaning. By convention all keywords must be written in lowercase (small)
letters.
• Example: for, while, do-while, auto break, case, char, continue, do, double, else, enum, extern, float,
goto, if, int, long, register, return, short, signed, sizeof, static, struct, switch, typedef, union, unsigned,
void, volatile.
2.Identifiers
• Identifiers are names given to program elements such as variables, arrays and functions.
Rules for forming identifier name
▪ it cannot include any special characters or punctuation marks (like #, $, ^, ?, ., etc) except the
underscore"_".
▪ There cannot be two successive underscores
▪ Keywords cannot be used as identifiers
▪ The names are case sensitive. So, example, “FIRST” is different from “first” and “First”.
▪ It must begin with an alphabet or an underscore.
▪ It can be of any reasonable length. Though it should not contain more than 31 characters.
3.Constant
Constants in C refer to fixed values that do not change during the executing of a program. C Support several
types of constants are listed below.
1. Numeric Constants
i. Integer Constants: An "integer constant" is a decimal (base 10), octal (base 8), or
hexadecimal (base 16) number that represents an integral value. Use integer constants
to represent integer values that cannot be changed. If an integer constant begins with 0x
or 0X, it is hexadecimal. If it begins with the digit 0, it is octal. Otherwise, it is assumed
to be decimal.
ii. Real Constants: A "floating-point constant" is a decimal number that represents a signed real
number. The representation of a signed real number includes an integer portion, a fractional
portion, and an exponent. Use floating-point constants to represent floating-point values that
cannot be changed.
You can omit either the digits before the decimal point (the integer portion of the value) or the
digits after the decimal point (the fractional portion), but not both. You can leave out the
decimal point only if you include an exponent. No white-space characters can separate the
digits or characters of the constant.
Floating-point constants have type float, double, or long double. A floating-point constant
without an f, F, l, or L suffix has type double. If the letter f or F is the suffix, the constant has
type float. If suffixed by the letter l or L, it has type long double
2. Character Constants
i. Single Character Constants:"character constant" is formed by enclosing a single character
from the represent able character set within single quotation marks (' '). Character constants are
used to represent characters in the execution character set.
Escape-sequence: Character combinations consisting of a backslash (\) followed by a
letter or by a combination of digits are called "escape sequences."
Escape Sequence Represents
\a Bell (alert)
\b Backspace
\f Formfeed
\n New line
\r Carriage return
\t Horizontal tab
\v Vertical tab
\' Single quotation mark
\" Double quotation mark
\\ Backslash
\? Literal question mark
\ ooo ASCII character in octal notation
\x hh ASCII character in hexadecimal notation
Unicode character in hexadecimal notation if this escape sequence is
used in a wide-character constant or a Unicode string literal.
\x hhhh
For example, WCHAR f = L'\x4e00' or WCHAR b[] = L"The Chinese
character for one is \x4e00".
int main()
{
printf("Hello\n");
return(0);
}
It is Backslash Character
Takes Control one position back
#include<stdio.h>
int main()
{
printf("Hello\b");
return(0);
}
Cursor Position :
Hell_
printf("Hello\r");
Cursor Position :
Note : Cursor on ‘H’ character from Word Hello
_allo
4. Audible Return : ‘\a’ Character
printf("Hello\a");
Hello
4. String : Collection of characters terminated with special character known as NULL character.
String in C language is enclosed in double quotes.
Example --- “hello” “welcome”.
5. Operator: Operator is a symbol which operates on certain data type.There are many types of operator
present in c language.
Example +, %, > < etc.
6. Special symbol:
( ) ; $ :
DATA TYPES
• A variable is defined as a meaningful name given to the data storage location in computer memory.
• When using a variable, we actually refer to address of the memory where the data is stored. C language
supports two basic kinds of variables.
• Numeric variables can be used to store either integer values or floating point values.
• While an integer value is a whole numbers without a fraction part or decimal point, a floating point
number, can have a decimal point in them.
• Numeric values may also be associated with modifiers like short, long, signed and unsigned.
• By default, C automatically a numeric variable signed..
• Character variables can include any letter from the alphabet or from the ASCII chart and numbers 0 – 9
that are put between single quotes.
To declare a variable specify data type of the variable followed by its name.
Variable names should always be meaningful and must reflect the purpose of their usage in the program.
Variable declaration always ends with a semicolon. Example,
int emp_num;
float salary;
char grade;
double balance_amount;
unsigned short int acc_no;
STREAMS
• A stream acts in two ways. It is the source of data as well as the destination of data.
• C programs input data and output data from a stream. Streams are associated with a physical device
such as the monitor or with a file stored on the secondary memory.
• In a text stream, sequence of characters is divided into lines with each line being terminated with a new-
line character (\n). On the other hand, a binary stream contains data values using their memory
representation.
• we can do input/output from the keyboard/monitor or from any file but in this chapter we will assume
that the source of data is the keyboard and destination of the data is the monitor.
Streams in a C
program
Text Binary
Stream Stream
INPUT OUTPUT IN C
C Standard Library Functions
C Standard library functions or simply C Library functions are inbuilt functions in C programming. Function
prototype and data definitions of these functions are written in their respective header file. For example: If you
want to use printf() function, the header file <stdio.h> should be included.
#include <stdio.h>
int main()
{
/* If you write printf() statement without including header file, this program will show error. */
printf("Catch me if you can.");
}
There is at least one function in any C program, i.e., the main() function (which is also a library function).
This program is called at program starts.
There are many library functions available in C programming to help the programmer to write a good efficient
program.
1).Formated Input Output Functions:-
These function are used to Input data from a standard Input unit such as Keyboard and to get the result
on standard output unit such as Monitor . As name suggest , these function follow a basic fix format .
There are two Input Output functions .
1. printf() 2. scanf()
length Description
h When the argument is a short int or unsigned short int.
l When the argument is a long int or unsigned long int for integer specifiers.
L When the argument is a long double (used for floating point specifiers)
Example:
#include <stdio.h>
int main()
{
printf("%d\n",1234);
printf("%10d\n",1234);
printf("%2d\n",1234);
printf("%-10d\n",1234);
printf("%010d\n",1234);
printf("%+10d\n",1234);
return 0;
}
Output:
1234
1234
1234
1234
0000001234
+1234
Example:
#include <stdio.h>
int main()
{
printf("%*.*f\n",5,1,12.34);
printf("%7.4f\n",12.3456);
printf("%f\n",12.3456);
printf("%8.2f\n",12.3456);
printf("%-8.2f\n",12.3456);
printf("%08.2f\n",12.3456);
printf("%10.2e\n",12.3456);
return 0;
}
Output:
12.3
12.3456
12.345600
12.35
12.35
00012.35
1.23e+01
C - Operator Types
An operator is a symbol that tells the compiler to perform specific mathematical or
logical manipulations. 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
Following table shows all the arithmetic operators supported by C language. Assume variable A
holds 10 and variable B holds 2 then:
Example:
#include <stdio.h>
void main() {
int a,b;
printf("Enter values for a and b");
scanf("%d%d",&a,&b);
printf("sum is =%d",a+b);
printf("difference is =%d",a-b);
printf("multiplication is =%d",a*b);
}
Relational Operators
Following table shows all the relational operators supported by C language. Assume variable A
holds 10 and variable B holds 2, then:
Checks if the value of left operand is greater than the value of (A > B) is true. Means
>
right operand, if yes then condition becomes true. output will be 1
Checks if the value of left operand is less than the value of right
< (A < B) is not true. Means
operand, if yes then condition becomes true.
output will be 0
Checks if the value of left operand is greater than or equal to the (A >= B) is true.Means
>=
value of right operand, if yes then condition becomes true. output will be 1
Checks if the value of left operand is less than or equal to the
<= (A <= B) is not true. Means
value of right operand, if yes then condition becomes true.
output will be 0
Example:
#include <stdio.h>
void main() {
int a,b;
printf("Enter values for a and b");
scanf("%d%d",&a,&b);
printf("Output is = %d",a==b);
}
Output:
Enter values for a and b2
2
Output is = 1
Logical Operators
Following table shows all the logical operators supported by C language. Assume variable A
holds 1 and variable B holds 0, then:
Assignment Operators
There are following assignment operators supported by C language:
Syntax :
where
→ expression1 is Condition
→ expression2 is Statement Followed if Condition is True
→ expression3 is Statement Followed if Condition is False
Meaning of Syntax :
1. Expression1 is nothing but Boolean Condition i.e it results into either TRUE or FALSE
2. If result of expression1 is TRUE then expression2 is Executed
3. Expression1 is said to be TRUE if its result is NON-ZERO
4. If result of expression1 is FALSE then expression3 is Executed
5. Expression1 is said to be FALSE if its result is ZERO
operator .
Example:
#include <stdio.h>
void main() {
int m,a,b,c;
printf("Enter values for a, b and c");
scanf("%d%d%d",&a,&b,&c);
m=(a>b?(a>c?a:c):(b>c?b:c));
printf("Largest number is = %d",m);
}
C – Increment/decrement Operators
→ Increment operators are used to increase the value of the variable by one and decrement
operators are used to decrease the value of the variable by one in C programs.
Syntax:
Increment operator: ++var_name; (or)
var_name++; Decrement operator: – -var_name;
(or) var_name – -;
Example:
Increment operator : ++ i ; i
++ ; Decrement operator : - – i ;
i–-;
Precedence of C Operators:
Operator precedence determines the grouping of terms in an expression. This affects how an
expression is evaluated. Certain operators have higher precedence than others; for example, the
multiplication operator has higher precedence than the addition operator:
For example x = 7 + 3 * 2; Here x is assigned 13, not 20 because operator * has higher
precedenace than + so it first get multiplied with 3*2 and then adds into 7.
If we perform a calculation of two different data type is result in the data-type whose size is greater
among them .
eg.
int and int -----> int
int and float -----> float ( result )
char and int -----> int
char and float -----> float
int and double -----> double
Type Casting :-
We know that Type Conversion are automatically done from compiler , BUT some time we use Type
Casting for avoiding the loss of fractional part also to get desired result . The process of such a local
conversion is known as explicit conversion or casting a value.
The general form of a cast is:
(type- name) expression
eg.
int x = 100 , y = 40 , a ,b ,z ;
float c , d ;
a = x/y ; /* a = 100/40 -----> a = 2 */
c = (float) (x/y) ; /* c = (float) ( 100/40 ) -----> c = 2.500000 */
b = (float) (c*4) ; /* b = 2.5*4 -----> b = 10 */
z = c*4 ; /* z = 2*4 -----> z = 8 */
Arithmetic Expressions
Example:
kk = 3 / 2 * 4 + 3 / 8 + 3
kk = 1 * 4 + 3 / 8 + 3 operation: /
kk = 4 + 3 / 8 + 3 operation: *
kk = 4 + 0 + 3 operation: /
kk = 4 + 3 operation: +
kk = 7 operation: +
Example:
i=2*3/4+4/4+8-2+5/8
i=6/4+4/4+8-2+5/8 operation: *
i=1+4/4+8-2+5/8 operation: /
i = 1 + 1+ 8 - 2 + 5 / 8 operation: /
i=1+1+8-2+0 operation: /
i=2+8-2+0 operation: +
i = 10 - 2 + 0 operation: +
i=8+0 operation : -
i=8 operation: +
Scope of Variables or Visibility: This refers to those parts of the program where the variable is accessible or
active or visible for use ( e.g. for calculations etc.)
Lifetime of Variable: It refers to the period during which the variable retains the memory location or retains a
given value during execution of a program (i.e. it is alive). Here, the variable can be active or dormant but it is
alive not destroyed.
Storage class tells us: 1) Where the variable is stored. 2) Initial value of the variable. 3) Scope of the
variable. Scope specifies the part of the program which a variable is accessed. 4) Life of the variable.
AUTOMATIC STORAGE CLASS: In this automatic storage class, Variable is stored in memory. Default
value is garbage value Scope is local to the block Life is, with in the block in which the variable is defined
REGISTER STORAGE CLASS: Variable is stored in CPU registers. Default value is garbage value.
Scope is local to the block. Life is,with in the block in which the variable is defined. We can not use register
storage class for all types of variables. For example: register float f;
STATIC STORAGE CLASS: Variable is stored in memory. Default value is zero. Scope is local to the block.
Life is,value of the variable persists between different function calls. Example :
main()
{
add();
add();
}
add()
{
static int i=10;
printf(“ %d”,i);
i+=1;
}
Output:
10 11
EXTERNAL STORAGE CLASS: Variable is stored in memory. Default value is zero. Scope is local to the
block. Life is,as long as the program execution doesn’t come to an end.
void increment(void);
int main()
{
increment();
increment();
increment();
increment();
return 0;
}
void increment(void)
{
auto int i = 0 ;
printf ( “%d “, i ) ;
i++;
}
Output:
0000
#include<stdio.h>
void increment(void);
int main()
{
increment();
increment();
increment();
increment();
return 0;
}
void increment(void)
{
static int i = 0 ;
printf ( “%d “, i ) ;
i++;
}
Output:
0123
int x = 10 ;
int main( )
{
extern int y;
printf(“The value of x is %d \n”,x);
printf(“The value of y is %d”,y);
return 0;
}
int y=50;
Output:
The value of x is 10
The value of y is 50
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.
But, only limited variables can be used as register since register size is very low. (16 bits, 32
bits or 64 bits)
#include <stdio.h>
int main()
{
register int i;
int arr[5];// declaring array
arr[0] = 10;// Initializing array
arr[1] = 20;
arr[2] = 30;
arr[3] = 40;
arr[4] = 50;
for (i=0;i<5;i++)
{
// Accessing each variable
printf(“value of arr[%d] is %d \n”, i, arr[i]);
}
return 0;
}
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
Summary of the Main Features of the various Storage Classes
Keyword Declaration Statement Declaration Accessibility Existence/ Place of Default
Or Scope Lifetime Storage value
auto auto datatype var_name; Within Accessible Exists from the time of Primary Garbage
function within the invocation of function memory value
or block function or to its return to the
block where calling function OR
it is from the time of entry
declared into the block to the end
of the block.
extern extern datatype var_name; Outside all Accessible Exists as long as the full Primary Zero
functions within the program is in execution. memory
This var has been or within combination
declared somewhere function of program
else as a global or modules that
external variable. form the full
program.
register register datatype var_name; Within a Accessible Exists from the time of CPU Garbage
function within the invocation of function register value
or block function or to its return to the
block where calling function OR
it is from the time of entry
declared into the block to the end
of the block
static static datatype var_name; Within a Internal Internal static: Primary zero
function static: Preserves the value memory
or block Accessible between the function
within the calls or block entries.
function or
block where
static datatype var_name; Outside it is
External External static: Primary zero
all declared
static: Preserves the value in memory
functions Accessible the program file.
within the
program file
where it is
declared and
not other
files.