FC Unit 2 notes
FC Unit 2 notes
Unit 2 C - Programming
What is C…?
C is a general purpose and specific purpose high level programming language developed by
Dennis Ritchie and Brian Kernighan in 1972 at “AT & T” Bell Laboratories of USA.
Introduction
C is a high level programming language developed by Dennis Ritchie and Brian Kernighan in
the year 1972 at Bell Telephone Laboratory, USA (now it is AT & T Bell Lab). It is both
general and specific purpose programming language. Now C has become one of the most
commonly used programming language for developing system software and application
software’s.
C is relatively a small programming language. You need not to remember many C keywords
before you start to write programs in C to solve problems. That’s why „C‟ language is called
the lowest high-level programming language. Many other high-level languages have been
developed based on C. Perl is a popular programming language in web designing across the
Interne. Perl actually borrows a lot of features from C. If you understand C, learning Perl is a
snap. Another example is the C++ language, which is simply an extended version of C.
History of C
By 1960 many computer languages came into existence, almost each for a specific purpose.
For example, COBOL was being used for commercial applications, FORTAN for
engineering and scientific applications and so on. At this stage people started thinking that
instead of learning and using so many languages, each for a different purpose, why not use
only one language, which can perform all possible applications.
Therefore, a new language called Combined Programming Language (CPL) was developed
at Cambridge University. CPL turned out to be so big, having so many features, that it was
hard to learn and difficult to implement. In 1967, Basic Combined Programming Language
(BCPL) was developed by Martin Richards at Cambridge University aimed to solve this
problem by CPL down to its basic good features. But unfortunately it turned out to be too
less powerful and too specific. In 1970 a language called B was written by Ken Thompson
at Bell Lab, as a further simplification of CPL and took first character of BCPL for
naming his new language.
In 1972, Dennis Ritchie developed a new language called C by inheriting some of the
features of B and BCPL, added some of his own. He selected the name C for his new
language because C comes after B in the alphabetical order, which indicates advancement to
B. Some sources also said that Dennis Ritchie selected the 2nd character of BCPL for
naming his language. C runs under various operating systems including MS-DOS, UNIX,
Windows etc. In 1978, Dennis Ritchie and Brian Kernighan jointly published a detailed
description of the C language document. It is known as K & RC. C was exclusively used
within Bell Laboratory before it was released to public and commercial applications until
1978.
Page
C - Programming
Merits or Advantages of C
C is the most popular programming language, it has the following advantages:
1. Readability: C programs are very easy to read and understand. Because the program
syntax is easy and which contains English like statements.
2. Maintainability: C programs are easy to maintain. Because the program is divided into a
Page
C - Programming
number of modules and functions. That makes the programmer to easy to debug, test and
maintain.
3. Portability: C programs written in one computer can be ported to other computer easily
with little or no modifications.
4. Reusability: Programs written in C can be reused. We can save our C programs into a
library file and invoke them in our next programs simply by including the library file.
5. Assembly Code: We can write Assembly code in C. But, its impossible to write C code in
Assembly language.
Documentation
Preprocessor Statements
Global Declarations
main()
{
declaration;
statements;
}
user defined functions
programmer while writing C program. All C programs will be having the following
structure.
Documentation
In this section we can give comments about the program, creation or modified date,
author name etc. The statements which are followed by “//” (single line comment) and
the statements which are enclosed between “/*” and “*/” (multi line comment) will be
ignored by the C compiler during compilation and execution.
Preprocessor Statements
The Preprocessor statements begin with # symbol and are also called preprocessor
directives. These statements tell the C compiler to include header files and symbolic
constants into a C program.
Some of the preprocessor statements are:
#include<stdio.h> : for the standard input/output functions. #define NULL 0 : for
defining symbolic constant, NULL=0.
Global Declarations
The variables and functions declared before the main() function are called Global
Variables, and their declarations are called Global Declarations. These variables or
functions can be used and accessed in main() function and other user defined functions.
Main()
Any C program will not execute without the main(). Every C program should contain
only one main(). Execution of C program starts from main(). This main() calls other
Page
C - Programming
built-in functions and user defined functions. And it should be written in lowercase
letters and should not be terminated by a semicolon.
Braces ({,})
Every C program contains a pair of braces ({,}). The left brace indicates the beginning
of main() function and the right indicates the end of the main() function. The braces can
also be used to indicate the beginning and end of user-defined functions and compound
statements.
Declarations
In this section of C program all the variables, arrays, functions etc., used in the C program
are declared with data types and can also be initialized.
Statements
Statements are the instructions to the computer to perform specific operations. These
statements are written according to the syntax of C to solve a particular program. The
statements may be input-output statements, arithmetic statements, control statements,
looping statements and other statements. They also include comments. Comments are
explanatory notes on some instructions.
User-defined functions
These are subprograms. A subprogram is a function. These are written by the user, hence the
name user-defined functions. A Function is a block of statements that gets executed upon
calling to perform a specific task. A program may have any number of functions which
contain local declarations and statements. Functions may be written before or after the main()
function.
A simple C Program Example:
#include<stdio.h>
main()
{
Printf(“Welcome to C programming”);
}
The above program prints only Welcome to C Programming in the output screen. The first
line tells the compiler to include standard input/output header file for accepting and printing
the data. The actual execution of program starts from main(). The program body contains
only one printf() statement. The printf() is included in stdio.h, whenever the main() function
calls printf(), then the content in the printf() will prints on the computer screen.
Characters Set
The character set is the fundamental raw material of any language and they are used to
represent information. Like natural languages, every computer programming language
also has its own set of characters to form lexical elements. The characters used in C are:
Alphabets [A-Z] [a-z]
Digits 0-9
Special Characters
Page
C - Programming
C tokens
The basic and the smallest individual units of a C program are called C tokens. In a
passage of text, individual words and punctuation marks are called tokens.There are 6
types of tokens in C.
1. Key words
2. Identifiers
3. Constants
4. Strings
5. Operators
6. Special Symbols
Key words
All Keywords (Reserved words) have fixed meanings and these meanings cannot be changed
in any circumstances. All C keywords must be written in lowercase letters. Because, in C
bothuppercase and lower case letters are significant. There are 32 keywords in C.
Page
C - Programming
Identifiers
Identifier refers to the names of variables, arrays and functions. These are user-defined
names and consist of sequence of letters and digits.
Rules for forming identifier or declaring a variable:
The first character must be an alphabet or an underscore.
All succeeding characters may be either letters or digits.
Uppercase and lowercase identifiers are different in C.
No special characters are allowed except the underscore “_”.
No two successive underscores are allowed.
Keywords should not be used as identifiers.
Constants
A constant refers to the fixed value that does not change during the execution of a
program. They are also called as literals. Constants can be declared by using the
keyword const.
Constants can be classified
Integer Constant
Integer constants are the whole numbers without a decimal point. They may have prefixed „-„
sign.
Floating-Point Constant
Floating-point constants are the numbers with preceded or followed by the decimal point.
They may have prefixed „-„ sign. Ex: 2.5, 30.2456, -6.27, 1.2536 etc.
Character Constant
Character constants are the characters of type i.e., alphabets, digits or special symbols, which
are enclosed within a pair of single quotes.
Ex: „a‟, „x‟, „?‟, „/‟, „ ‟ etc.
String Constant
String constants are the sequence of characters enclosed within a pair of double
quotes.
Ex: “Hi”, “Welcome”, “Program” etc.
Page
C - Programming
Data Types
Data type defines the type of data that a variable can store.
The data types in are categorized into three types:
1. Built-in data types.
2. Derived data types.
3. User-defined data types.
Size: 2 bytes
2. Float : Variables of floating types can hold real numbers. The keyword float is used for
declaring floating type variables and which can store floating point number. Any float
number is a sequence of digits preceded and followed by decimal point.
Ex: 0.234, 14.263546 etc.
Size: 4 bytes
3. Double : Double is equivalent to float, but, the number of digits after the decimal point is
double than the float. The keyword double is used to indicate double precession floating
point number. Double is used whenever more accuracy is required.The float can have a
maximum of 6 digits after the decimal point. But double can stores 16 digits after the
decimal point.
Ex: 234.000000000000000.
Size: 8 bytes
4. char : The keyword char is used for declaring the character type variables. The char data
type allows a variable to store only one character. A character is any alphabet, digit or any
special character that is written within a single quote.
Ex: „x‟, „*‟ etc.
Size: 1 byte
Data Types Keyword Size (in bytes)
Integer int 2
Real (Floating-Point) float 4
Double Precision double 8
Character char 1
Non-Specific void -
Page
C - Programming
2. unsigned
This can be used for both int and char. It can also be used with the combination of long or short.
The unsigned char can hold numbers in the range of 0 to 255.
3. long
This is used for int data type. When applied to int, it doubles the length of the data type. If an int
is of 2 bytes, then long int is of 4 bytes. Similarly, this can be used with double. When long is
applied to double, it roughly doubles the precision.
4. short
This is used for int data type. When applied to int, it makes the size of an int half.
Variable
The variables are the names used to refer some location in the computer‟s memory that
holds a value. The value of variables changes during the execution of a program. Variables
are also called as Identifiers.
The name of a variable can be composed of letters, digits and the underscore. It must begin
Page
C - Programming
with a letter. Upper and lowercase letters are distinct because C is a case-sensitive.
Ex: sum, area_tri, n1, name, basic_salary etc.
Rules for Declaring a Variable.
The first character must be an alphabet or an underscore.
All succeeding characters may be either letters or digits.
Uppercase and lowercase identifiers are different in C.
No special characters are allowed except the underscore “_”.
No two successive underscores are allowed.
Keywords should not be used as identifiers.
Declaration of Variables
The variables which are used in the program must be declared in the declaration part before
they are used. After declaring the variables then only the compiler will reserve the memory
for these declared variables to store the values.
Syntax:
Data_Type Varlist Semicolon
float sum=0.0;
int n1=10, n2=20; char ch=‟x‟;
2. The initial values are assigned to the variables in theexecutable part of a program.
Ex: x=20; PI=3.142;
name=”Harish”; ch=‟A‟;
Page
C - Programming
float a=b=c=d=5.75;
C defines a new data type qualifier called the const to provide constant-ness to the values
of the variables during the execution of a program. Once a variable is declared as a const
variable, you cannot change its value. Any attempt to modify its value will result in a error
message.
Ex: const float PI=3.142;
const int MAXSIZE=10;
const char name 20 =”Peter”;
Symbolic Constants
A symbolic constant is a name that substitutes a numeric constant or character constant or a
string constant. Symbolic constants are defined using preprocessor statement #define.
Ex: #define PI 3.142
Backslash Constants
The Backslash Constants are also called as Escape Sequences. These are unprintable
characters which can perform special functions in the output statements. Backslash
constants are preceded by backslash (\) symbol and followed by any of characters from the
below table.
Page
C - Programming
\” Double quote
\\ Backslash
0 Null (End of String)
Input/Output Functions
C provides many built-in functions to read data into computer and write data on screen,
printer or in any file. These functions are called standard Input Output library functions. To
perform input/output operations in C program we must include a header file called stdio.h.
There are two types of input/output statements.
1. Formatted Input/Output statement.
2. Unformatted Input/Output statement.
Input Statement Output Statement
Formatted scanf() print()
Unformatted getch() purch()
gets() puts()
scanf(“%d%f”,&a,&b); scanf(“%f%d%c%s”,&avg,&age,&initial,&name);
scanf(“3d”,&n);
In the above scanf() function, the variable n will takes only 3 digits input. If you give more
than 3 digits, it discards last digits after the first 3 digits. For ex, if you give input as 45215
means, that will takes only first 3 digits i.e., 452.
scanf(“5f”,&x);
In the above scanf() function, the variable x will takes only 4 digits input and one decimal
point. Consider the input is 75.1245 then it will store only 75.12 and last two digits are
discarded.
scanf(“%ld,%hd”,&a,&b);
scanf(“%lf”,&b);
Here, the %ld for long int, %hd for short int and %lf for double.
Syntax:printf(“control-string”, var_list);
Eg: printf(“Programming is an art”);printf(“%d”,a);
printf (“%d%f”,a,b); printf(“sum=%d”,sum);
printf(“Name=%s”,name); printf(“Average=%s”,avg);
Page
C - Programming
printf(“6. f”,&x);
In the above printf() function, the variable x has the content 4583.424 means, then it prints only
4583.4 only. The 6.1f indicates that it prints total 6 digits including the decimal point and there
will be only one digit after the decimal point.
Ex:ch=getch();
Ex: gets(name);
Ex:putch(a)
puts() function
The puts() function prints a sequence of characters orstring on the screen.
Syntax: puts(str_var);
Ex: puts(name);
Page
C - Programming
Unary Operators
An operator that acts upon only one operand is known asunary operator. The C unary
operators are:
1. Unary minus
2. Logical NOT operator
3. Bitwise complementation
Unary minus
Any positive operand associated with unary minus operator gets its value changed to
negative.
Ex: Let, a=3, b=4
c=a+(-b)
=3+(-4)
= -1
Binary Operators
The operators operates on two operands are known as binary operators. The binary operators are
classified as follows:
1. Arithmetic Operators
Arithmetic operators are used to perform the arithmetic calculations like addition,
subtraction, multiplication, division and modulus in C programs.
Page
C - Programming
3.Logical Operators
Logical operators are used to perform logical operations (taking decision and comparing)
on two or more conditions. The result of this operator is either true or false.
Operator Meaning Precedence Associativity
&& Logical AND 2 L to R
|| Logical OR 3 L to R
! Logical NOT 1 L to R
The && operator is called the Logical AND operator. It is equivalent to a multiplication
operation. The result of Logical AND is true when both the operands are true; otherwise
the result is false.
Ex: if(avg>=60 && avg<=85)
Page
C - Programming
Ex: !a
Operand !Operand
True False
False True
.Bitwise Operators
The Bitwise Operators are used to manipulate one or more bits from internal operands like char,
int, short, long.
Operator Symbol Name Meaning
& Ampersand Bitwise AND
| Pipeline Bitwise OR
^ Caret Exclusive OR (X-OR)
~ Tilde 1‟s complement
<< Double Less than Left shift of bits
>> Double greater than Right shift of bits
The Bitwise AND (&) operator takes 2 bit patterns and perform AND operation on them. The
result of bitwise AND is 1 when both the bits are 1, otherwise it is 0.
The Bitwise OR ( | ) operator takes 2 bit patterns and perform OR operations on them. The result
of bitwise OR is 1 if any one bit is 1. If both the bits are 0, then the result is 0.
The Bitwise XOR (^) operator takes 2 bit patterns and perform XOR operation on them. The
result of bitwise X-OR is 1, if the bits are different (1 and 0) otherwise it is 0 (when both are 0 or
both are 1).
The Bitwise Complement (~) operator is unary operator. It takes only one operand that is used to
convert each bit 1 to 0 and 0 to 1.
The Left Shift (<<) operator shifts the bits towards left for the given number of times. The Right
Shift (>>) operator shifts the bits towards right for the given number of times.
Page
C - Programming
a<< = 00001000
a>> = 00100001
6.Ternary Operator
The ternary operator is also called as conditional operator in C. It takes three expressions.
The symbol „?‟ is used as a ternary operator. Expression1 is a condition. If the result of
Expression1 is true then Expression2 is executed. If the result of Expression1 is false then
Expression3 is executed.
Syntax:
<expression1> ? <expression2> : <expression3> ;
a. Comma Operator
The comma operator is used to separate variable names. The comma operator is also
associated with for statement. It is also used to link two or more related expressions together.
Ex: sum=(a=10, b=20, a+b);
b. sizeof() Operator
This operator returns the size (number of bytes) of an operand. The operand may be a
constant, a variable or a data type. It should be written in lower case letter.
Syntax:
sizeof(operand);
Ex: x=sizeof(int);
Page
C - Programming
Syntax:
Var Operator = Exp ;
Expressions
An Expression is a statement that has a value. Expression in C is a combination of
operators, operands and parenthesis. An expression involves arithmetic operators is called
arithmetic expression. It takes one or more operands and collects them by arithmetic
operands.
Ex: x = a+b*(-c)
Page
C - Programming
Syntax:
(datatype)variable;
Ex: int x=25, y=4; float z;z=x/float(y);
Library Functions (Mathematical Functions)
There are many standard library functions in C which perform specific operations. The C library
also contains many mathematical functions which are defined in the header file math.h. Some of
the most commonly used mathematicalfunctions are given below.
Function Action
abs(n) Return the absolute value of n.
pow(x,y) Return x to the power y
sqrt(n) Return the square root of n.
floor(n) Return a value rounded down to the next lower integer.
round(n) Return the nearest integer value of the float argument.
log(x) Return the natural logarithm of x.
log 10(x) Return the logarithm (base 10) of x.
cos/sin(x) Return the cosine/sine value of x.
Page