Unit-2 Final

Download as pdf or txt
Download as pdf or txt
You are on page 1of 23

1 C Programming Reference Note

Unit 2: Introduction to C (5T+5P)


2.1 History of C Language
2.2 Basic Structure of C Program
2.3 Escape Sequence
2.4 Comment
2.5 Variables and Constants
2.6 Storage classes in C
2.7 Data Types
2.8 typedef keyword
2.9 Enumeration
2.10 Format Specifiers
2.11 Type Conversion
2.12 Formatted and unformatted I/O functions
2.13 Operators
2.13.1 Arithmetic
2.13.2 Relational
2.13.3 Logical
2.13.4 Assignment
2.13.5 Conditional operator (?:)

1. Write short history about Programming in C.


Ans: Short history about programming in C
• The C programming language is a structure oriented programming language, developed at Bell
Laboratories in 1972 by Dennis Ritchie
• C programming language features were derived from an earlier language called “B” (Basic
Combined Programming Language – BCPL)
• C language was invented for implementing UNIX operating system
• In 1978, Dennis Ritchie and Brian Kernighan published the first edition “The C Programming
Language” and commonly known as K&R C
• In 1983, the American National Standards Institute (ANSI) established a committee to provide a
modern, comprehensive definition of C. The resulting definition, the ANSI standard, or “ANSI C”,
was completed late 1988.
2. Define C programming Language? Write some important features of it.
Ans: C language is a popular, well structure middle level programming language. This was developed by
AT and T Bell laboratory of U.S.A in 1972 by Dennis Ritchie. It's reliable, simple and easy
programming language which supports built-in function and many operators with 32 keywords. C
language is very useful for developing the system software and application software.
Some important Characteristics (features) of C language are:
• General purpose structure programming language
• It has small size.
• C has powerful set of operators.
• C support a rich set of data declaration and data type.
• C has less number of keywords (only 32)
• It is not fully high level and nor fully low level, but intermediate
• It can be compiled on a variety of computer platforms.
• Modular and structural concept is used din C language. So debugging, testing and maintenance are
easy.
2 C Programming Reference Note
• Efficient use of pointer
• Problems are divided into small task or modules, called function.
• Highly portable language and it is machine independent also.
• C has ability to extend itself by adding more function to its library.
• Today's most popular Linux OS and RBDMS My-SQL have been written in C
• C Pointer makes it very strong for memory manipulations.
3. Write some advantages and disadvantages of C programming Language
Ans: Some advantages of C programming Language are:
• It is machine independent programming language.
• It is compact and efficient to use.
• Program code is easy and secured
• It is easier to interact with hardware.
• It is easy to learn and implement C language.
• It is free form language so ,program can be start from any line and column.
• It can be implemented from mobile device to mainframe computer.
• As a middle level language assembly level program can also be compiled in C
• It is mother of all modern programming language python is fully written in C language.
Some disadvantages of C programming Language are:
• There is no runtime checking.
• It has poor error detection system.
• It is complex and hard to fix error.
• There is no strict type checking int data type to float variables.
• Multiple inheritances are not available in C
• The program takes more time to design and implement the software.
• It does not support modern programming methodologies oriented programming language.
• As the program extends it is very difficult to fix the bugs.

Character Set
- Set of characters that are used to form words, numbers and expression in C is called
Ccharacter set.
- Characters in C are grouped into the following four categories:
1. Letters or Alphabets:
 Uppercase alphabets → A…….Z
 Lowercase alphabets → a…….z
2. Digits:
All decimal digits → 0, 1, 2, ........ ,9
3. Special characters:
, → comma ; → semicolon “→ quotation mark & → ampersand etc.
4. White spaces:
Blank spaces, horizontal tab, vertical tab etc.

C Tokens
- C tokens are the basic buildings blocks in C language which are constructed together
to write a C program.
- Each and every smallest individual unit in a C program is known as C tokens.
- C tokens are of six types.
3 C Programming Reference Note

Keywords
- Keywords are predefined words for a C programming language.
- All keywords have fixed meaning and these meanings cannot be changed.
- The keywords cannot be used as variable
names. E.g.
4 C Programming Reference Note

Identifiers
- Every word used in C program to identify the name of variables, functions, arrays,
pointers and symbolic constants are known as identifiers.
- These are user defined names consisting of arbitrarily long sequence of letters and digits
with either a letter or the underscore ( _ ) as a first character.
- There are certain rules that should be followed while naming C identifiers:
1. They must begin with a letter or underscore (_).
2. They must consist of only letters, digits, or underscore. No other special character is
allowed.
3. It should not be a keyword.
4. It must not contain white space.
5. It should be up to 31 characters long as only first 31 characters are significant.
6. Uppercase and lowercase letters are not interchagable.
E.g. Valid and Invalid identifiers

Constants
- A C constant refers to the data items that do not change their value during the program
execution.
- These fixed values are also called literals.
- Several types of C constants that are allowed in C are:
5 C Programming Reference Note

Integer constants:
- Integer constants are whole numbers without any fractional part. It must have at least one
digit and may contain either + or – sign. A number with no sign is assumed to be positive.
- There are three types of integer constants: Decimal integer constant, Octal integer
constant and Hexadecimal integer constant.
- A prefix specifies the base or radix: 0x or 0X for hexadecimal, 0 for octal, and nothing for
decimal.
Decimal integer constant: 1, 3, 65, 5436664, -785
Octal integer constant: 037, 0, 0320, 0432
Hexadecimal integer constant: 0x4, 0X563, 0x1A

Real constants:
- The numbers having fractional parts are called real or floating point constants. These may
be represented in one of the two forms called fractional form or the exponent form and
may also have either + or – sign preceding it.
- Example of valid real constants in fractional form or decimal notation: 0.05, -0.905,
562.05, 0.015
Representing a real constant in exponent form:
- The general format in which a real number may be represented in exponential or scientific
form is: mantissa e exponent
- The mantissa must be either an integer or a real number expressed in decimal notation.
- The letter e separating the mantissa and the exponent can also be written in uppercase i.e.
E and, the exponent must be an integer.
- Examples of valid real constants in exponent form are: 252E85, 0.15E-10, -3e+8, 4.1e8

Character constants:
- A character constant contains one single character enclosed within single quotes.
E.g. ‘a’, ‘Z’, ‘5’
- It should be noted that character constants have numerical values known as ASCII values,
for example, the value of ‘A’ is 65 which is its ASCII value.
6 C Programming Reference Note

String constant:
- String constants are sequence of characters enclosed within double quotes.
- May contain letters, numbers, special characters or blank spaces.
- For e.g., “hello”, “abc”, “hello91”, “2077”

 Symbolic constants
A symbolic constant is a name given to some numeric value, or a character constant or
string constant.
Defining symbolic constants:
1) Using pre-processor directive #define
Syntax: #define CONSTANT_NAME literal
e.g. #define PI 3.14159

2) Using keyword literal


Syntax: Const datatype CONSTANT_NAME = literal
e.g. Const float PI= 3.14159

Special Symbols
The following special symbols are used in C having some special meaning and thus, cannot
be used for some other purpose.
[] () {} , ; : * . = #
Braces { }: These opening and ending curly braces marks the start and end of a block of code
containing more than one executable statement.
Parentheses ( ): These special symbols are used to indicate function calls and function
parameters.
Brackets [ ]: Opening and closing brackets are used as array element reference. These
indicate single and multidimensional subscripts.

Escape Sequence
- An escape sequence is a non-printing characters used in C.
- These non-printing characters can be represented by using escape sequences represented
by a backslash(\) followed by one or more characters.
- Each sequence are typically used to specify actions such as carriage return, backspace,
line feed or move cursors to next line.
E.g.
7 C Programming Reference Note

#include <stdio.h>
#include <conio.h>
main()
{
printf("Hello\tworld!!\n"); Output:
printf("Hello!\n How are you?"); Hello world!!
getch(); Hello!
How are you?
return 0;
}

Delimiters
- A delimiter is a unique character or series of characters that indicates the beginning or
end of a specific statement, string or function body set.
- Delimiter examples include:
- Parentheses: ( )
- Curly brackets: { }
- Escape sequence or comments: /*
- Double quotes for defining string literals: “ ”

Data Types
- A data type is a type of data.
- Data type is a data storage format that can contain a specific type or range of values.
- Data type in C refers to an extensive system used for declaring variable for function of
different types. The type of a variable determines how much space it occupies in storage
and how the bit pattern stored is interpreted.
ANSI C supports three classes of data types:
 Primary/fundamentals data types
 User-defined data types
 Derived data types

Primary Data Types


Primary data types are categorized into five types:
1. Integer type (int):
 Integers are whole numbers.
 It requires 16 bit of storage i.e. 2 bytes.
 Three classes of integer: Integer(int), Short integer (short int) and Long integer
(long int)
Type Size Range
(bytes)
Integer (int) Signed int 2 −215 to 215 − 1
Unsigned int 2 0 to 216 − 1
Short integer Signed short int 2 −215 to 215 − 1
(short int) Unsigned short int 2 0 to 216 − 1
Long integer Signed long int 4 −231 to 231 − 1
(long int) Unsigned long int 4 0 to 232 − 1
8 C Programming Reference Note

 Defined as:
int a;
int x=5;

Signed integer vs Unsigned integer:

2. Floating point type (float):


 Floating point type are fractional numbers.
 A variable of float type requires 4 bytes and the range of values that can be stored in
it, is 3.4e-38 to 3.4e+38.
 Variable is defined as:
float a;
float x=23.7;

3. Character type (char):


 All single character used in programs belong to character type.
 The character data type holds exactly 8 bits (1 byte).
 The unsigned char has values between 0 and 255.
 The signed char has values from -128 to 127.
 Variable is declared as:
char var1= ‘h’;
Here, var1 is a variable of type char which is storing a character ‘h’.

4. Double precision floating point type (double):


i. Double precision:
 It reserves 8 bytes in memory.
 It represents fractional number of the range 1.7e-308 to 3.4e+308
ii. Long double precision:
 It reserves 10 bytes in memory.
 It represents fractional numbers of the range 3.4e-4932 to 1.1e+4932
9 C Programming Reference Note

5. Void type:
 The void type has no value.
 This is usually used to specify a type of function when it does not return any value to
the calling function.
 E.g. void main()

User Defined Data Types


- C supports a feature called type definition which allows users to define an identifier that
would represent an existing data type.
- typedef statement is used to give new name to an existing data type.
- It allows users to define new data types that are equivalent to an existing data types.
- General form: typedef existing_data_type new_name_for_existing_data_type;

One of the fundamental data type


New identifier
- E.g. typedef int salary;
Here salary symbolizes int data types. They can be later used to declare variables as:
salary dept1, dept2;
Therefore dept1 and dept2 are indirectly declared as integer datatype.

Derived Data Types


- Array, functions, pointers are derived data types they are discussed in unit 6, 7 and 9.

Conversion specifier
%d → integer #include <stdio.h>
%f → floating point int main()
%c → character {
%s → string char ch = 'A';
printf("%c\n", ch);
Input/Output return 0;
scanf()/printf() }
#include <stdio.h>
printf("%d",100); int main()
{
scanf("conversion specifier", &variable_name); float a = 12.67;
printf("%f\n", a);
if x is an integer variable. return 0;
scanf("%d",&x) }
10 C Reference Note
Programming

Variables
- A symbolic name which is used to store data item i.e. a numerical quantity or a character
constant.
- Each variable in C has a specific type, which determines the size and layout of the
variable's memory; the range of values that can be stored within that memory; and the set
of operations that can be applied to the variable.
- The same variable can store different value at different portion of a program.
- Variable name may consists of letters, digits or underscore characters.
- The rules for naming variables are similar to those of identifiers.

Variable Declaration:
- Any variable should be defined before using it in a program.
- The variable are declared using following syntax:
data_type variable_name1, variable_name2, ............. ;
E.g. int n1;
int v1, v2, v3;
char c;
float radius;

Preprocessor Directives
- Collection of special statements that are executed at the beginning of a compilation
process.
- Placed in the source program before the main function.
#include<stdio.h> //used for file inclusion
#define PI 3.1416 //defining symbolic constant PI
- These statements are called preprocessor directives as they are processed before
compilation of any other source code in the program.

Statement
- Statement is the complete direction to computer to perform specific task.
- In C, a statement is terminated by semicolon(;)
Types of statement:
1) Null statement: Does nothing.
;
2) Compound statement: Block of statement
{

… Compound statement

;



;
}
. What is statement? Explain the different types of statement?
Ans: A smallest executable entity within a program code is called a statement. An instruction
or one line of code written to do a specific task in a program is called programming
statement. Statements are the basic building blocks of c programming language.
 Simple statement: A simplest executable entity is called statement. A simple statement
is a basic part of program and it is a single line expression which is used to carry out
assignment, calculation or to test logical decision.
 Compound statement: A single instruction composed of two or more individual
instructions is called a compound statement. This type of statement is used to combing
two or more statement in on single line of code. This will shorten the written within a
program.
 Control statement: A statement that affects the flow of execution through a program is
called control statement. Control statements are also known, as control structures in C
language. There are two types of control statements are also known as control
structures in C language. There are two types of control statements: selection and
iteration

Expression
- Combination of variable, constant, operators etc. on the basis of language
grammar.
- Every expression consists of at least on operand and can have one or more
operators.
- Operands are values and operators are symbols that represent particular
actions.
- E.g. a+b, a+b*c, a*b/3

Types of operator
C operators can be classified into following types:
 Arithmetic Operators
 Relational Operators
 Logical Operators
 Assignment Operators
 Increment and Decrement Operators
 Conditional Operators
 Bitwise Operators
 Special Operators

Arithmetic Operators
Arithmetic operators are used to perform arithmetic operations. There are five arithmetic
operators:

College Note
Division Rule:
- int/int = int
- float/float = float
- int/float = float
- float/int = float

Note: For modulo operator, the sign of the result is always the sign of the first operand.
E.g. 10%3=1, -10%3=-1, -10%-3=-1, 10%-3=1

College Note
/* Program to Perform Arithmetic Operations in C */
#include<stdio.h>
int main()
{
int a = 12, b = 3;
int add, sub, mul, div, mod;
add = a + b;
sub = a - b;
mul = a * b;
div = a / b;
mod = a % b;
printf("Addition of two numbers a, b is : %d\n", add);
printf("Subtraction of two numbers a, b is : %d\n", sub);
printf("Multiplication of two numbers a, b is : %d\n", mul);
printf("Division of two numbers a, b is : %d\n", div);
printf("Modulus of two numbers a, b is : %d\n", mod);
}

Relational Operators
- Relational operators are used to compare two operands and taking decisions based on
their relation.
- Result of relational expression is either True(1) or False(0).
- Relational operators are used in decision making and loops.
- Relational operators are:

/* Program to compare two numbers whether they are equal or not in C */


#include <stdio.h>
int main()
{
int m=40, n=20;
if (m == n)
{
printf("m and n are equal");
}
else
{
printf("m and n are not equal");
}
}

College Note
Logical Operators
- Logical operators are used to compare logical and relational expression.
- The operands of logical operators must be either Boolean value (1 or 0) or expression that
produces Boolean value.
- The output of these operators is always 0 (flase) or 1 (true).
- The logical operators are:

Truth table for logical operators:

/* C program to demonstrate working of logical operators */


#include <stdio.h>
int main()
{
int a = 10, b = 4, c = 10, d = 20;

// logical AND example


if (a > b && c == d)
printf("a is greater than b AND c is equal to d\n");
else
printf("AND condition not satisfied\n");

// logical OR example
if (a > b || c == d)
printf("a is greater than b OR c is equal to d\n");
else
printf("Neither a is greater than b nor c is equal to d\n");

// logical NOT example


if (!a)
printf("a is zero\n");
else
printf("a is not zero");

return 0;
}

College Note
Assignment Operator
- Assignment operators are used to assign the result of an expression to a variable.
- The mostly used assignment operator is ‘=’.
- C also supports shorthand assignment operators which simplify operation with
assignment.

/* program to demonstrate working of Assignment operators */

#include <stdio.h>
int main()
{
int a = 10;
printf("Value of a is %d\n", a); //10
a += 10;
printf("Value of a is %d\n", a); //20
a -= 10;
printf("Value of a is %d\n", a); //10
a *= 10;
printf("Value of a is %d\n", a); //100
a /= 10;
printf("Value of a is %d\n", a); //10
return 0;
}

Increment and Decrement Operators


- Increment operator is used to increase the value of an operand by 1.
- Decrement operator is used to decrease the value of an operand by 1.

College Note
Pre-increment operator (++a): the value is incremented first and then the expression is
evaluated.
E.g. a= 10; b=++a; after this statement, a= 11, b = 11.
Post-increment operator (a++): the expression is evaluated first and then the value is
incremented.
E.g. a= 10; b=a++; after this statement, a= 11, b = 10.
Pre-decrement operator (- -a): the value is decremented first and then the expression is
evaluated.
E.g. a= 10; b=--a; after this statement, a= 9, b = 9.
Post-decrement operator (a- -): the expression is evaluated first and then the value is
decremented.
E.g. a= 10; b=a--; after this statement, a= 9, b = 10.

/* program to demonstrate working of increment and decrement operators */

#include <stdio.h>
int main()
{
int a = 5;
int b = 6;
printf("a=%d, b=%d",a,b); //a=5, b=6
b=++a;
printf("a=%d, b=%d",a,b); //a=6,b=6
b=a++;
printf("a=%d, b=%d",a,b); //a=7,b=6
b=a--;
printf("a=%d, b=%d",a,b); //a=6,b=7
b=--a;
printf("a=%d, b=%d",a,b); //a=5, b=5
return 0;
}

Conditional Operator (Ternary Operator)


- It takes three arguments.
- Conditional operators return one value if condition is true and returns another value if
condition is false.
Syntax: (condition) ? value_if_true : value_if_false

if a>b
return 1;
else
E.g. (a>b) ? 1 : 0; return 0;

College Note
6 C Programming Reference Note

Q. Write a program to read two numbers from user and determine the larger number using
conditional (ternary) operator.
#include <stdio.h>
int main()
{
int n1, n2, larger;
printf("Enter two numbers:");
scanf("%d%d",&n1,&n2);
larger = (n1>n2)?n1:n2;
printf("The larger number is %d", larger);
return 0;
}

Bitwise Operator
- Bitwise operators are used for manipulating data at bit level.
- These operators are used for testing the bits or shifting them to the left or to the right.
- Can be applied only to integer-type operands and not to float or double.
- Three types of bitwise operators:
(i) Bitwise logical operators
(ii) Bitwise shift operators
(iii) One’s compliment operator

Bitwise logical operators:


- Performs logical tests between two integer-type operands.
- These operators work on their operands bit-by-bit starting from the least significant (i.e.
rightmost) bit.
- Three logical bitwise operators:
 Bitwise AND (&): The result of ANDing operation is 1 if both the bits have a value 1;
otherwise it is 0.
 Bitwise OR (|): The result of ORing operation is 1 if either of the bits have value of 1;
otherwise it is 0.
 Bitwise XOR (^): The result of exclusive ORing operations is 1 only if one of the bits
have a value of 1; otherwise it is 0.

Truth table for bitwise operators (AND, OR, XOR)

E.g.
If a = 65, b=15
Equivalent binary values of 65 = 0100 0001; 15 = 0000 1111
7 C Programming Reference Note

Bitwise shift operators:


- Are used to move bit patterns either to left or to the right.
- There are two bitwise shift operators:
 Left shift(<<): Causes the operand to be shifted to the left by n positions.
operand<<n
The leftmost n bits in the original bit pattern will be lost and the rightmost n bits empty
position will be filled with 0’s.
 Right shift(>>): Causes the operand to be shifted to the right by n positions.
operand<<n
The empty leftmost n bits positions will be filled with 0’s, if the operand is an unsigned
integer.
E.g.
If a =15; Equivalent binary value of a is 0000 1111

0 0 1 1
8 C Programming Reference Note

Bitwise one’s complement operator:


- It is a unary operator which inverts all the bits represented by its operand. This means that
all 0s becomes 1s and 1s becomes 0s.
E.g.
If a =15; Equivalent binary value of a is 0000 1111

/* program to demonstrate working of bitwise operator */

#include <stdio.h> #include <stdio.h>


void main() void main()
{ {
int a=65,b=15,AND, OR, XOR; unsigned int a=15, left, right;
AND = a&b; left = a<<3;
OR = a|b; right = a>>2;
XOR = a^b; printf("%d\n", left);
printf("AND of a and b=%d\n",AND); printf("%d\n",right);
printf("OR of a and b=%d\n",OR); }
printf("XOR of a and b=%d\n",XOR);
}

Special Operators
 Comma operator (,):
- The comma operator can be used link related expressions together.
- A comma-linked list of expression are evaluated from left-to-right and the value of the
rightmost expression is the value of the combined expressions.
E.g. X=(a=5, b=10, a+b);
- The first assign the value 5 to a
- Assign the value 10 to b
- Assign sum(a+b) to X

 Sizeof operator
- It is used with an operand to return the number of bytes it occupies.
- The operand may be constant, variable or a data type qualifier.

E.g.
9 C Programming Reference Note

#include <stdio.h>
int main()
{
int a;
float b;
double c;
char d;
printf("Size of int=%lu bytes\n",sizeof(a));
printf("Size of float=%lu bytes\n",sizeof(b));
printf("Size of double=%lu bytes\n",sizeof(c));
printf("Size of char=%lu byte\n",sizeof(d));
return 0;
}

Operator precedence and associativity


- The precedence is used to determine how an expression involving more than one operator
is evaluated.
- There are distinct level of precedence.
- The operator at the higher level of precedence are evaluated first.
- Operators of same precedence are evaluated either from “left to right” or “right to left”
depending on the level also known as associativity.
10 C Programming Reference Note

Type conversion in expressions


- When variables and constants of different types are combined in an expression then they
are converted to same data type.
- The process of converting one predefined type into another is called type conversion.
- Type conversion in C can be classified into the following two types:

1. Implicit Type Conversion:

- When the type conversion is performed automatically by the compiler without


programmer‘s intervention, such type of conversion is known as implicit type
conversion or type promotion.
- When the expression contains different types of data items, the operand with a lower
rank will be converted to the type of higher rank operand.

E.g.
#include <stdio.h>
int main()
{
int x = 13; // integer x
char c = 'a'; // character c
float sum;
x = x + c; // c implicitly converted to int. ASCII ('a'=97)
sum = x + 1.0; // x is implicitly converted to float
printf("x = %d, sum = %f", x, sum);
return 0;
}
2. Explicit Type Conversion:

- The type conversion performed by the programmer by posing the data type of theexpression of
specific type is known as explicit type conversion.
- The explicit type conversion is also known as type casting.
- Type casting in C is done in the following form:
(data_type)expression;
where, data_type is any valid C data type, and expression may be constant, variableor expression.

E.g.
#include<stdio.h> int main()
{
float a = 1.2; int b;
b = (int)a + 1; // a is explicitly converted to int type
printf("Value of a is %f\n", a); printf("Value of b
is %d\n",b); return 0;
}

Assignment Questions ( Submission Date :2080/09/14)


Unit-2
1) Define C language? Explain any five Features of C language.
2) What is Data type in C ? Explain the difference types of data types used in C language.
3) What is an operator? Explain the different types of operator used in C language.
4) What is Constant? Explain the types of Constant used in C language.
5) What is Variable? How can you declared Variable C language.
6) Explain any five C-token used in C language.
7) WAP to input the marks of any five subjects and calculate its total and percentage.
8) What is Input/output function? Compare Printf and scanf, gets and puts , getchar and
putchar.
****Good Luck***

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy