0% found this document useful (0 votes)
27 views32 pages

Unit 1 PC Notes

Uploaded by

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

Unit 1 PC Notes

Uploaded by

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

UNIT I BASICS OF C PROGRAMMING

Introduction to programming paradigms – Applications of C Language - Structure of C program -


C programming: Data Types - Constants – Enumeration Constants - Keywords – Operators:
Precedence and Associativity - Expressions – Input /Output statements, Assignment statements –
Decision making statements - Switch statement - Looping statements – Preprocessor directives -
Compilation process

1.1 Introduction to programming paradigms

The meaning for Programming Paradigms is ‘Programming Techniques’ or


‘Programming Style’. In general, it is classified into 2 categories they are;

1. Imperative programming paradigm


 The programs in these paradigms are executed step by step by changing the current state
of the program.
 An imperative program consists of some command that computer operates and change the
state of the program.
 Imperative programming mainly focuses on how a program operates
 Some of the programming languages are:C,C++,Java,PHP,Ruby,Scala,Pascal
 The imperative is broadly divided into 3 subcategories

i. Procedural programming paradigm


 It is a procedure call that lets you reuse thecode.
 this feature was an amazing advancement at that time. Example C, C++,Java, etc.
ii. Object Oriented Programming (OOP)
 This is used to work on real-world entities in form of class and objects.
 Class is the blueprint of the object and you can reproduce as many as the object you
want.
 These classes contain some properties and method which all are reproduced in objects.
Example C++, Python, etc.
iii Parallel processing
 In this type of programming, a program is processed by dividing it into multiple
processors.
 The system contains multiple processors to solve the problem in less time.

2. Declarative programming paradigm


 In this, the programmer describes the property of the result without focusing on how to
achieve it.
1
 The approach of this programming is to create some object or elements withinthe program.
 It is used in programming languages used in a database query, regular expression,
functional programming, logical programming, etc.
 Some of the programming languages that support the declarative paradigm are: javascript,
Scala, Lisp, SQL, XQuery, Clojure
 Declarative programing can further be subcategorized into 3 main categories

i. Logic programming paradigm


 Logic programming uses sentences in logical form and creates an expression by using
symbols.
 In machine learning and artificial intelligence, there are many models that use
theseprograms.
 The programs are executed very much like some mathematical statement. It is mainly based
on forming logic.
ii. Functional programming paradigm
 In this, a program is constructed by creating and using functions.
 Rather than a series of statements functional programming use function to map and change
one value to another value.
 Functional programming is the key feature of JavaScript.
iii. Database programming approach
 This programming is based on enquiring data, its modification, movement, etc.
 The most famous programming language that supports this is SQL.

1.2 Applications of C Language

i. Gaming and Animation: C program and its packages are used to create games and animations.
ii. Operating Systems: The Unix operating system was developed using c. It is used to
communicated the user and machine
iii. Google Chrome: Google file system and Google chromium browser were developed using
C/C++.
iv. Mozilla Firefox and Thunderbird: These are open-source email client projects, they were
written in C/C++.
v. MySQL: MySQL, is an open-source project, used in Database Management Systems was written
in C/C++.
vi. Embedded Systems: The extension of the C programming language is known as embedded C. It
is generally utilized for creating microcontroller-based applications. It is closely related to
machine hardware.
vii. New Programming Platforms: C helps to create C++, a programming language including all the
features of C in addition to the concept of object-oriented programming
viii. Compiler Design: One of the most popular uses of the C language was the creation of compilers.
It is used to translate the code as machine readable.
ix. GUI: stands for G
x. raphical User Interface. Adobe Photoshop, one of the most popularly used photo editors, was
created with the help of C.

1.3 Structure of C program

Every C program contains a number of building blocks. These building blocks


should be written in a correct order and procedure, to executewithout any errors.

2
The structure of C Program is given below in details.

Documentation Section
 This section consists of comment lines which include the name of programmer, the author and
otherdetails like time and date of writing the program.
 Documentation section helps anyone to get an overview of the program.
 There are two types of comment lines are available
1. Single line comment (//single line comment)
2. Multi line comment(/*Multi line comment */)

Link Section
 This section consists of the header files that are used in the program.
 It provides instructions to the compiler to link functions from the system library.
Example
#include<stdio.h>
#include<conio.h>
Definition Section
 All the symbolic constants are written in definition section.
 Macros are known as symbolic constants.
Global Declaration Section
 Variables that can be used anywhere in the program are declared in globaldeclaration
 This section also declares the user defined functions.
main() Function Section
 It is necessary have one main() function section in every C program.
 This section contains two parts, declaration and executable part.
 The declaration part declares all the variables that are used in executable part.
 These two parts must be written in between the opening and closing braces.
 Each statement must end with a semicolon (;).
 The execution of program starts at opening braces and ends at closing braces.

3
Subprogram Section
 The subprogram section contains all the user defined functions that are used to perform a
specific task.
 These user defined functions should be called inside the main() function.

1.4. DATA TYPES


A data type specifies the type of data that a variable can store such as integer, floating,
character, etc..
C language supports 3 different types of data types. They are
1. Primary data types: These are fundamental data types. Ex: int, float, void etc.,
2. Derived data types: They are derived datatypes like arrays, functions, pointers.
3. User defined datatypes : They are user defined datatypes like enum, typedef,etc

1. Primary datatypes:
a. Integer type
1. Integers are used to store whole numbers. Eg : int a;
2. Size and range of Integer type on 16-bit machine is given below.
Type Size(bytes) Range
int or signed int 2 -32,768 to 32767
unsigned int 2 0 to 65535
b. Float type
1. Floating types are used to store real numbers. Eg : float b;
2. Size and range of float type on 16-bit machine is given below.
Type Size(bytes) Range
Float 4 3.4E-38 to 3.4E+38
Double 8 1.7E-308 to 1.7E+308

c. Character type
1. Character types are used to store characters. Eg : char c;
2. Size and range of Integer type on 16-bit machine is given below
Type Size(bytes) Range
char or signed char 1 -128 to 127
unsigned char 1 0 to 255
d. void type
1. void type means no value.
2. This is usually used to specify the type of functions.

4
2. Derived datatypes :
Datatypes derived from fundamental datatypes are called derived datatypes. They add new functionalities
to the basic data types. They are Arrays, Pointers
a. Array : It is a collection of variables of same data type Eg : int
a[5];
b. Pointer : It is a special variable that holds the memory address of a variable Eg : int *b;
b=&c;
3. User defined datatypes :
User defined data types are used to create new data types. They are typedef, enum.
a. typedef
 typedef allows the user to create new names for existing datatypes
 Syntax: typedef <exixting dt> <user defined dt>
 Eg : typedef int Number;
#include<stdio.h>
typedef int Number;
void main()
{
Number a,b,c; // Here a,b,& c are integer type
printf("Enter any two integer numbers: ") ; scanf("%d%d",
&a,&b) ;
c = a + b;
printf("\n Sum = %d", c) ;
}
OUTPUT: Enter any two integer numbers: 4 5
Sum = 9

b. enum:
 It is used to define user's own data type and define values that the variable cantake.
 The enumeration type is an integral data type.
Syntax:
enum enum_name
{
const1, const2 ,….
};
Example : enum week { Sun,Mon, Tue, Wed, Thur, Fri, Sat };
Example Program for enum
#include <stdio.h>
enum week {Sun, Mon, Tue, Wed, Thur, Fri, Sat}; void
main()
{
enum week day;
day = Fri;
printf("%d",day);
}
Output: 5

Struct : It is used to store multiple variables of same or different data type under a singlename.
Eg :
struct student
{ int roll;
char name[10];
};

5
Union: It is used to store multiple variables of same or different data type under a single name. Union
variables are stored in a common memory location
Eg :
union student
{ int roll;
char name[10];
};

1.5 Storage Classes


A storage class represents the scope and lifetime of a variable. It tells from what part of code we can
access a variable. A storage class in C is used to describe the following:
The scope of the variable.
The location where the variable will be stored.
The initial value of a variable
Lifetime of variable.
Syntax is storage-class-name <datatype> var1,var2, … var n;
There are total 4 types of standard storage classes
1) auto storage class
 It is a default storage class.
 The scope of an auto variable is limited with the particular block only.
 Once the control goes out of the block, the access is destroyed. This means only the block in
which the auto variable is declared can access it.
 Syntax : auto <data type> var1,var2..var n;
#include <stdio.h> int
main( )
{
auto int j = 1;
{
auto int j= 2;

printf ( " %d ", j);


}
printf ( "\t %d ",j);
}

Output: 2 1
2) extern storage class
 It is a global variable.
 The variables defined using an extern keyword can be accessed by any function.
 These variables are accessible throughout the program.
 Syntax : extern <data type> var1,var2..var n;
 Example
file1.c file2.c
#include <stdio.h> #include “file1.c”
… …
int a=4; main()
void f1() {
{ extern int a;
a=a+1; ….
…. }
}
3) static storage class
6
 Static variables are variables for which the contents of the variables will be retained
throughout the program.
 These are permanent within the function in which they are declared.
 These are capable of retaining their latest values, when the function is invokedagain.
 Syntax : static <data type> var1,var2..var n;
 Example
#include<stdio.h>
#include<conio.h>
void increment();
void main()
{
increment();
increment();
increment();
getch();
}
void increment()
{
static int i = 1 ; printf (
“%d “, i ) ;
i++;
}

Output: 1 2 3

4) register storage class


 Registers are special storage areas within CPU
 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 inregister 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).
 Syntax : register <data type> var1,var2..var n;
Example program
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b; register
int c;clrscr();
printf("Enter the value of a and b:");
scanf("%d %d",&a,&b);
c=a+b;
printf("\nSum of two numbers is %d",c);
getch();
}

Output: Enter the value of a and b: 2 3


Sum of two numbers is 5

[Note: In the above program, variables a and b are storedin RAM and c is stored in the register of the
microprocessor.]
7
Features of storage classes
Features auto extern static register
Storage Memory Memory Memory CPU register
Initialvalue Garbage Zero Zero Garbage
Scope Local Global Local Local
Lifetime Exists as long Exists as Value of the variable Exists as long as
as control long as exists between control remains in
remains in the variable is different the block
block running function call
1.6 CONSTANTS
Constants are the terms that can't be changed during the execution of a program.
1. Integer constants
2. Floating-point constants
3. Character constants
4. String constants
1. Integer constants
 Integer constants are the numeric constants without any fractional part
 There are three types of integer constants in C language: i.Decimal
constant (base 10)
ii.Octal constant (base 8)
iii.Hexadecimal constant (base 16)
Example : mark =90;
2. Floating-point constants: Floating point constants are the numeric constants that have either
fractional form or exponent form.
Example : height =5.6;
3. Character constants: Character constants are the constant which use single quotation
aroundcharacters.
Example: gender=’F’;
4. String constants: String constants are the constants which are enclosed in a pair of double-quote
marks.
Example Explanation
"good" string constant
"" null string constant
" " string constant of six white space
"x" string constant having single character
"Earth is round\n" prints string with newline

1.7 ENUMERATION CONSTANTS


It is a user defined data type
The Keyword enum is used.
It define values that the variable can take.
The enumeration type is an integral data type.
This can help in making program more readable.
Syntax:
enum typename
{
list_of_objects
};

Example
enum week {Mon, Tue, Wed, Thur, Fri, Sat, Sun};

8
Example Program for enum
#include <stdio.h>
enum week {Sun,Mon, Tue, Wed, Thur, Fri, Sat};
void main()
{
enum week day;
day = Fri;
printf("%d",day);
}
Output: 5

1.8 KEYWORDS
1. Keywords are reserved words that have special meaning in C language.
2. The meaning has already been described. These meaning cannot be changed.
3. There are total 32 keywords in C language.
4. Keywords cannot be used as variable names
5. All keywords must be in lowercase
6. C Keywords are given below:
auto Double int struct
break else long switch
case enum register typedef
const extern return union
char float short unsigned
continue for signed volatile
default goto sizeof void
do if static while
1.9 OPERATORS
1. C language supports a rich set of built-in operators.
2. An operator is a symbol that tells the compiler to perform certain mathematical or
logicalmanipulations.
3. Operators are used in program to manipulate data and variables.
Types of operators:
1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Assignment operators
5. Increment /Decrement operators
6. Conditional operators
7. Bitwise operators
8. Special operators

1 Arithmetic operators
C supports all the basic arithmetic operators. The following table shows all the basic arithmetic
operators.
Operator Description Example
+ adds two operands a+b
- subtract second operands from first a-b
* multiply two operand a*b
/ divide numerator by denumerator, givesquotient as result a/b
% divide numerator by denumerator, gives remainder as a%b
result
9
2. Relational operators
The following table shows all relation operators supported by C.
Operator Description Example
== Check if two operand are equal if (a==b)
!= Check if two operand are not equal. if (a!=b)
> Check if operand on the left is greater if (a>b)
than operand on the right
< Check operand on the left is smaller than right if (a<b)
operand
>= check left operand is greater than or equal to if (a>=b)
right operand
<= Check if operand on left is smaller than or if (a<=b)
equal to rightoperand
3. Logical operators
C language supports following 3 logical operators.
Operator Description Example
&& Logical AND if (a>b)&&(a<b)
|| Logical OR if (a>b) ||(a<b)
! Logical NOT !a
4. Assignment Operators
Assignment operator is used to assign the right side value/variable to the left sidevariable.
Operator Description Example
= assigns values from right side operands to left side a=b
operand
+= adds right operand to the left operand and assign the result a+=b is same
to left asa=a+b
-= subtracts right operand from the left operand and a-=b is same as
assign theresult to left operand a=a-b
*= multiply left operand with the right operand and a*=b is same as
assign the result to left operand a=a*b
/= divides left operand with the right operand and a/=b is same as
assign the result to left operand a=a/b
%= calculate modulus using two operands and assign a%=b is same
the result to leftoperand asa=a%b

5. Increment /Decrement operators:


++ a=a+1 (increment and assignment)
-- a=a-1 (decrement and assignment)

Operator Description

++a It will increment the value, and then assign the int a = 10;
value to the variable. [Pre increment] ++a;
Output: 11
--a It will decrement the value, and then assign the int a = 10;
value to the variable. [Pre decrement] --a;
Output: 9

10
a++ It will assign the value to the variable, and then int a = 10, b; b =
increment the value. [Post increment] a++;
Output:b=10,
a=11
a-- It will assign the value to the variable, and then int a = 10, b; b =
decrement the value. [Post decrement] a--;
Output:b=10,a=9

6 Conditional operator or Ternary operator


 It is also known as ternary operator and used to evaluate conditional expression.
 Syntax: value = expr1 ? expr2 : expr3
If expr1 Condition is true , then value is expr2 , Otherwise value is expr3Program:
#include <stdio.h>
#include <conio.h>
void main()
{
int a=10,b=5;
clrscr();
big =(a>b)? a :b;
printf(“big is %d”,big);
getch();
}
Output: big is 10

7. Bitwise operators
 Bitwise operators perform manipulations of data at bit level.
 These operators also perform shifting of bits from right to left. Bitwise operators are not
applied to float ordouble.
Operator Description Ex: Let int a=50; int b = 5
& Bitwise AND c = a & b; C=0
| Bitwise OR c = a | b; C=55
^ Bitwise exclusive OR c = a ^ b; C=-51
<< left shift c = a <<2 C=200
>> right shift c = a >>2 12
Truth Table:
A b a &b a|b a^b
0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 0
8. Special operator
Operator Description Example
sizeof Returns the size of an variable sizeof(x)
& Returns the address of an variable &x
* Pointer to a variable. This points address of another int *x ;
variable
11
, It evaluates the first operand & discards the int i=(5, 10);
result, evaluates the second operand & returns the value as a
result.
. and -> Member operators that used to refer to members Student.roll
of struct , union
1.10. PRECEDENCE AND ASSOCIATIVITY
 If more than one operator is involved in an expression , C language has a predefined rule of
priority for the operators, This is called operator precedence.
 Precedence and Associativity are used for operators in an expression for determining the order of
sub-expressions when they do not have brackets.
 Their associativity indicates in what order, operators of equal precedence in an
expression is applied.
o Precedence rule: This rule decides the order in which different operators areapplied.
Associativity rule: This rule decides the order in which multiple occurrence of the same level operators
are applied.
C OPERATOR PRECEDENCE AND ASSOCIATIVITY TABLE
Operator Description Associativity
() Parentheses left-to-right
[] Square Brackets (array subscript)
. Member selection via object name
-> Member selection via pointer
++ -- Postfix increment/decrement
++ -- Prefix increment/decrement right-to-left
+- Unary plus/minus
!~ Logical negation/bitwise complement
(type) Cast (convert value to temporary value of type)
* Dereference
& Address (of operand)
sizeof Determine size in bytes on this implementation
* / % Multiplication/division/modulus left-to-right
+ - Addition/subtraction left-to-right
<< >> Bitwise shift left, Bitwise shift right left-to-right
< <= Relational less than/less than or equal to left-to-right
> >= Relational greater than/greater than or equal to
== != Relational is equal to/is not equal to left-to-right
& Bitwise AND left-to-right
^ Bitwise exclusive OR left-to-right
| Bitwise inclusive OR left-to-right
&& Logical AND left-to-right
|| Logical OR left-to-right
?: Ternary conditional right-to-left
= Assignment right-to-left
+= -= Addition/subtraction assignment
*= /= Multiplication/division assignment
%= &= Modulus/bitwise AND assignment
^= |= Bitwise exclusive/inclusive OR assignment
<<= >>= Bitwise shift left/right assignment
, comma Left to right
12
sample program :
#include <stdio.h>
main() {
int a = 20;
int b = 10;
int c = 15;
int d = 5;
int e;
e = (a + b) * c / d; // ( 30 * 15 ) / 5
printf("Value of (a + b) * c / d is : %d\n", e );
e = ((a + b) * c) / d; // (30 * 15 ) / 5
printf("Value of ((a + b) * c) / d is : %d\n" , e );
e = a + (b * c) / d; // 20 + (150/5)
printf("Value of a + (b * c) / d is : %d\n" , e );
return 0;
}
Output:
Value of (a + b) * c / d is : 90 Value
of ((a + b) * c) / d is : 90 Value of a +
(b * c) / d is : 50

1.11 EXPRESSIONS
1. It is a collection of operators and operands that represents a specific value.
2. Operator is a symbol which performs tasks like arithmetic operations, logical operations
andconditional operations etc.,
3. Operands are the values on which the operators perform the task.
Syntax:
Variable = expression;
Example:
C=++a
X=a*b-c;
Y=b/c*a;
Z=a-b/c+d;
Rules for evaluation of expression
1. First parenthesized sub expression left to right are evaluated.
2. If parenthesis are nested , the evaluation begins with the innermost sub expression.
3. The precedence rule is applied in determining the order of application of operators in evaluating
subexpressions.
4. The associability rule is applied when two or more operators of the same precedence
level appear in the sub expression
5. Arithmetic expressions are evaluated from left to right using the rules of precedence
Type Conversion in Expression:
Type conversion in C is the process of converting one data type to another. The type conversion is
only performed to those data types where conversion is possible. Type conversion is performed by a
compiler. There are two types of Conversion:
1. Implicit Type Conversion
2. Explicit Type Conversion
Implicit Type Conversion: C permits mixing of constants and variables of different data types in an
expression . C automatically converts any intermediate values to the proper type. This automatic type
conversion is called Implicit type conversion. All the data types of the variables are upgraded to the data
type of the variable with the largest data type. For eg , if one operand is int and other is float , the int
operand will be automatically converted to float and result will be float
13
Explicit Type Conversion : This process is also called type casting and it is user- defined. Here the user
can typecast the result to make it of a particular data type. syntax: (type) expression
Type indicated the data type to which the final result is converted.
Eg : ratio = female_students / male_students
If male_students and female_students are integers , then the result will also be integer ie the decimal part
is rounded and ratio will represent a wrong figure. So , explicit type conversion has to be done as shown
below :
ratio = (float)female_students / male_students
STATEMENTS IN C
It is classified into 5 types:
1. Input /Output Statements
2. Assignment statements
3. Decision making statements
4. Switch statements
5. Looping statements
1.12 INPUT /OUTPUT STATEMENTS

1 Formatted Input/Output Statements

The following are the input and output statements regarding formatted statements.They are:
Input Output
scanf() printf()
fscanf fprintf()
(i) scanf() function
Input data can be passed into the computer using standard input C library function as
scanf(). This function is used for passing mixed input. scanf() function is mainly used to
read information from the standard input device keyboard.
Syntax:
scanf(“control string”,&var1,&var2,…&varn);

Example: int age;


scanf(“%d”,&age);

Basic control strings “%d” for int “%f” for float “%c” for char “%s” for strings.
Program
#include<stdio.h>
main()
{
int age;
float weight;
clrscr();
printf(“Enter your age:”);
scanf(“%d”,&age);
printf(“Enter your weight:”);
14
scanf(“%f”,&weight); printf(“AGE=%d\n”,age);
printf(“WEIGHT=%f”,weight);
}
Output:
AGE=17
Weight=56
Rules – scanf() function
The control string should be used that are relevant to corresponding variable.

 The control strings are enclosed within double quotes.


 No of input items (variables) are used that are separated by commas.
 Variables are preceded with (&) sign except string variable.
 The control strings and the variables should match with each other.
 scanf() statement should b e terminated with semicolon.
(ii) printf() function
Output data can be displayed from the computer using standard output C library
function called printf(). This function is used to display anything whatever we like. printf()
function is mainly used to display information from the standard output device (monitor).
Syntax:
printf(“control string”,&var1,&var2,…&varn);
Example: int n;
printf(“%d”,n);
Program 1:
#include<stdio.h>
main()
{
printf(“Think Positive \n”);
getch();
}
Output :
Think Positive
Rules – printf() function
printf() function is used to print the “character, string, float, integer, octal and
hexadecimal values” onto the output screen.
We use printf() function with %d format specifier to display the value of an integer
variable.
Similarly %c is used to display character, %f for float variable, %s for string
variable, %lf for double and %x for hexadecimal variable.
To generate a newline,we use “\n” in C printf() statement.
2 Unformatted Input/output statements
These statements are used to single/group of characters. The user cannot specify the
type of data. The following are the unformatted input/ output statements available in C
language.
INPUT Output

getchar() putchar()
getc() putc()
gets() puts()

1. getchar() function:
It is single character input function. This function reads character type data from
the standard input. It reads one character at a time till the user presses the enter key.
Syntax:
15
char variable = getchar();
Example:
char gender;
gender=getchar();

16
Program:
#include<stdio.h> main()
{
char gender; gender =
getchar();
printf(“Gender=%c”,gender);
}
Output:
M
Gender=M
2. putchar() function:
It is single character output function. It is used to display one character at a time on
the standard output device.
Syntax:
putchar(character variable);
Example:
char x; putchar(x);

Program1:
#include <stdio.h>
main ()
{ char gender; printf(“Enter
Gender: “); gender =
getchar();
printf(“\n Gender entered: “);putchar(c);

}
Output
Enter Gender: m
Gender entered: m
3. getc() function
This is used to accept a single character from the file
Syntax:
character variable=getc(filepointer);
Example:
FILE *fp;
char c;
c = getc(fp);

4. putc() function:
This is used to display a single character in a character variable to standard
output device. This function is mainly used in file processing.
Syntax:
putc(character variable,fp);
Example:
FILE *fp;
putc(c,fp);

4. gets() an d pu t s() function


It reads a line from stdin and stores it into the string pointed. It stops when, either the
newline character is read or when the end-of-file is reached, whichever comes first. Simply,
the gets() function is used to read the string from the standard input device(keyboard).
Syntax:
17
puts(char type of array variable);
Example:
puts(s);
puts(c);
Program:
#include<stdio.h>
void main ()
{
char s[30];
printf("Enter the string? ");gets(s);
printf("You entered %s",s);
}
Output :
Enter the string? Be positive You
entered Be positive

1.13 ASSIGNMENT STATEMENTS


It is used to assign the value to a variable using assignment operator(=) .
Syntax:
Variable = constant; Variable =variable1; Variable= expression; Examples of
assignment statements,
a=9; /* a is assigned the value 9*/
b=c; /* b is assigned the value of c */
b = c+5;/* b is assigned the value of expr c+5 */

1.14 DECISION MAKING STATEMENTS


The if statement may be implemented in different forms depending on the complexity of conditions
to be tested. The different forms are,
1. Simple if statement
2. if. . else statement
3. Nested if. else statement
4. else if ladder statement

1. Simple if statement :If the expression is true, then 'statement-inside' will be executed, otherwise
'statement-outside' is executed.
Syntax: Flowchart:
if( expression )
{
statement-inside;
}
statement-outside;

Example :
#include<stdio.h>
void main( )
{
int a,b;a=15; b=13;
if (a > b )
{
18
printf("A is big");
}
}
output:
A is big

2. if...else statement :If the 'expression' is true, the 'statement-block1' is executed, else 'statement-
block2' is executed.
Syntax & Flowchart

if( expression )
{
statement-block1;
}
else
{
statement-block2;
}

Example :

#include<stdio.h>
void main( )
{
int a,b;
a=15; b=18;
if (a > b)
{
printf("A is big");
}
else
{
printf("B is big");
}
}
Output: B is big

3. Nested if…else statement: if 'expression' is false the 'statement-block3' will be executed,


otherwise it continues to perform the test for 'expression 1' . If the 'expression 1' is true the 'statement-
block1' is executed otherwise 'statement-block2' is executed. Syntax:

if( expression )
{
if( expression1 )
{
statement-block1;
}
else
{
statement-block 2;
}
}
else
{ 19
statement-block 3;
}
Example #include< stdio.h>
#include< conio.h>
void main( )
{
int a,b,c;
clrscr();
printf("enter 3 numbers");
scanf("%d%d%d",&a,&b,&c);
if(a>b)
{
if( a > c)
{
printf("\n a is greatest");
}
else
{
printf("\n c is greatest");
}
}
else
{
if( b> c)
{
printf("\n b is greatest");
}
else
{
printf("\n c is greatest");
}
}
getch();
}

Output:
enter 3 numbers 10 20 30 c is
greatest

4. else-if ladder: The expression is tested from the top(of the ladder) downwards. As soon as the
true condition is found, the statement associated with it is executed.
Syntax:
if(expression 1)
{
statement-block1;
}
else if(expression 2)
{
statement-block2;
}
else if(expression 3 )
{
statement-block3;
}
else
default-statement;

20
Flowchart:

Example :
#include<stdio.h>
#include<conio.h>
void main( )
{
int a;
printf("enter a number");scanf("%d",&a); printf(“\n”)
if( a%5==0 && a%8==0)
{
printf("divisible by both 5 and 8");
}
else if( a%8==0 )
{
printf("divisible by 8");
}
else if(a%5==0)
{
printf("divisible by 5");
}
else
{
printf("divisible by none");
}
getch();
}
Output:
enter a number10
divisible by 5

1.15 SWITCH STATEMENT


 Switch statement is used to solve multiple option type problems where one value is
associated with each option.
 The expression in switch case evaluates to return a value, which is then compared to the
values in different cases. When it matches, that block of code is executed, if there is no match,
then default block is executed.
21
 Syntax FLOWCHART
switch(expression)
{
case value-1:
block-1;
break;
case value-2:
block-2;
break;
case value-3:
block-3;
break;
case value-4:
block-4;
break;
default:
default-block;
break;
}

Points to Remember
1. We don't use the expressions which may return floating point values in switch
2. It isn't necessary to use break after each block, but if you do not use it, all the
consecutive block ofcodes will get executed after the matching block.
Example :
#include <stdio.h>
void main() {
char operation;
int n1=5, n2=2;
printf("Enter an operator (+, -):");
scanf("%c",&operation);
switch(operation)
{
case '+':
printf("Ans = %d",n1+n2);
break;

case '-':
printf("Ans = %d",n1-n2);
break;

default:
printf("Error! operator is not correct");
}
}
Output :
Enter an operator (+, -): + Ans
=7

1.16 LOOPING STATEMENTS


 A sequence of statements is executed until a specified condition is true.
 This sequence of statements to be executed is kept inside the curly braces { } known as the
Loop body.
 After every execution of loop body, condition is verified, and if it is found to be true
2
22
the loop body is executed again.
 When the condition check returns false, the loop body is not executed.

There are 3 type of Loops in C language


1. while loop
2. for loop
3. do-while loop
1 while loop: while loop can be addressed as an entry control loop. It is completed in 3 steps. They are
variable initialization, test condition and increment or decrement
Syntax : Flow chart

variable initialization ;
while (condition)
{
statements ;
variable increment or decrement ;
}

Eg : Program to print first 10 natural numbers


#include<stdio.h>
#include<conio.h>
void main( )
{
int x;x=1;
while(x<=10)

{
printf("%d\t", x);
x++;
}
getch();
}

Output
1 2 3 4 5 6 7 8 9 10

2 for loop: for loop is used to execute a set of statements repeatedly until a particular condition is satisfied. we
can say it an open ended loop.

Syntax:
for(initialization; condition ; increment/decrement)

{
statement-block;
}

23
Flow chart:

Example
#include<stdio.h>
#include<conio.h>
void main( )
{
int x;
for(x=1; x<=10; x++)
{ printf("%d\t",x);}
getch();
}
Output
1 2 3 4 5 6 7 8 9 10
Nested for loop
We can also have nested for loops, i.e one for loop inside another for loop.

syntax:
for(initialization; condition; increment/decrement)
{
for(initialization; condition; increment/decrement)
{
statement ;
}

Example: #include <stdio.h>


void main()
{
for(int i=1;i<=3;i++) // outer loop
{
for(int j=1;j<=i;j++) // inner loop
{
printf("*"); // printing the value.
}
printf("\n");
}}
Output:
*
**
***
24
do while loop
It is a exit controlled loop. In some situations it is necessary to execute body of the loop before
testing the condition. Such situations can be handled with the help of do- while loop. do statement
evaluates the body of the loop first and at the end, the condition is checked using while statement.
General format of do-while loop is,

Syntax Flowchart
do
{
....
.....
}
while(condition);

Example : Program to print first ten multiple of 5.


#include<stdio.h>
#include<conio.h>
void main()
{
int a,i;a=5; i=1;
do
{
printf("%d\t",a*i);
i++;
} while(i <= 10);
getch();
}
Output : 5 10 15 20 25 30 35 40 45 50

Difference between while and do while [or Entry and exit controlled loop]
Entry Controlled Loop[while] Exit Controlled Loop[do .. while]
Test condition is checked first, and then loop Loop body will be executed first, and then
bodywill be executed conditionis checked
If Test condition is false, loop body will not If Test condition is false, loop body will be
beexecuted executedonce.
for loop and while loop are the examples of do while loop is the example of Exit
EntryControlled Loop controlled loop.
Entry Controlled Loops are used when Exit Controlled Loop is used when checking of
checking oftest condition is mandatory test condition is mandatory after
before executing loop body executing the loop body

1.17 JUMPS IN LOOPS


 Sometimes, while executing a loop, it becomes necessary to skip a part of the loop or to
leave the loop assoon as certain condition becomes true, that is calledjumping out of loop.
 C language allows jumping from one statement to another within a loop as well as jumping out
of the loop.
25
1) break statement
When break statement is encountered inside a loop, the loop is immediately exited and the
program continues with the statement immediately following the loop.

Example: #include<stdio.h>
void main(){
int i = 0;
while (i < 10){
if (i == 3) break;
printf("%d\n", i);
i++;
}}
output:
0
1
2
continue statement
It causes the control to go directly to the test-condition and then continue the loop process.
On encountering continue, cursor leave the current cycle of loop, and starts with the next cycle

Example:
#include<stdio.h>
void main(){
int i = 0;
while (i < 4){
i=i+1;
if (i == 2)
continue;
printf("%d\n", i);
}}
Output:1
3
4
26
1.18 goto statement :
A goto statement in C programming provides an unconditional jump from the 'goto' to a labeled
statement in the same function.
Syntax: The syntax for a goto statement in C is as follows –
goto label;
…………….
……………. label:
statement;
Here label can be any plain text except C keyword and it can be set anywhere in the C program above or
below to goto statement.
Example:
#include <stdio.h> int
main()
{
int num,i=1;
printf("Enter the number whose table you want to print?");
scanf("%d",&num);
table:
printf("%d x %d = %d\n",num,i,num*i);i++;
if(i<=5)
goto table;
}
Output:
Enter the number whose table you want to print?10 10 x 1 =
10
10 x 2 = 20
10 x 3 = 30
10 x 4 = 40
10 x 5 = 50
1.19 PREPROCESSOR DIRECTIVES

 Pre-processors are programs that process our source code before


compilation.
 Pre-processor programs provide pre-processor directives that tell the compiler to pre-
process the source code before compiling.
 All of these pre-processor directives begin with a ‘#’ (hash) symbol. Examples
#include, #define, #ifndef etc.
 Remember that the # symbol only provides a path to the pre-processor
 #include will include extra code in your program.
 Pre-process working flow as follows

27
There are 4 Main Types of Pre-processor Directives
1. Macros
2. File Inclusion
3. Conditional Compilation
4. Other directives
1. Macros
Macros are pieces of code in a program that is given some name. Whenever this name is encountered by
the compiler, the compiler replaces the name with the actual piece of code. The ‘#define’ directive is used
to define a macro. Let us now understand the macro definition with the help of a program:
// macro with parameter
#define AREA(l, b) (l * b)
int main(){
int l1 = 10, l2 = 5, area;
area = AREA(l1, l2);
printf(“Area of rectangle =%d”,area);
return 0;
}
Output : Area of rectangle is: 50

2. File Inclusion
 This type of pre-processor directive tells the compiler to include a file in the source code
program.
 There are 2 types of files they are Header files or Standard files:
 These files contain definitions of pre-defined functions like printf(), scanf(), etc.
 These files must be included to work with these functions.
 Different functions are declared in different header files.
Syntax1 : #include< file_name > // Predefined
Syntax2 : #include"filename" // user defined
Example:
#include <stdio.h> // Predefined
#include "myheader.h" // user defined
Conditional Compilation
Conditional Compilation directives are a type of directive that helps to compile a specific portion of the
program or to skip the compilation of some specific part of the program based on some conditions. This
can be done with the help of the two pre-processing commands;‘ifdef‘,‘endif‘.
Syntax:
#ifdef macro_name
statement1;
statement2;
statement3;
.
.
statementN;
#endif
Example
# include <stdio.h> #
define a 10
void main(){
#ifdef a
printf("Hello I am here..");
#endif
#ifndef a
28
printf(" Not defined ");
#else
printf("Are you There? ");
#endif
}
3. Other Directives
 #undef Directive: The #undef directive is used to undefine an existing macro. This directive
works as:
Ex:#undef LIMIT
Using this statement will undefine the existing macro LIMIT. After this statement, every “#ifdef
LIMIT” statement will evaluate as false.
 #pragma Directive: This directive is a special purpose directive and is used to turn on or off some
features. This type of directives is compiler-specific,
#pragma startup and #pragma exit: These directives help us to specify the functions that are
needed to run before program startup (before the control passes to main()) and just before
program exit
#include<stdio.h> void
func() ; #pragma startup
func #pragma exit func
void main() Output
{ I am in function
printf("\nI am in main"); I am in main
} I am in function

void func()
{
printf("\nI am in function");
}
Predefined Macros
ANSI C defines a number of macros. Although each one is available for use in programming, the
predefined macros should not be directly modified.
Sr.No. Macro & Description
1 DATE : The current date as a character literal in "MMM DD YYYY" format.
2 TIME : The current time as a character literal in "HH:MM:SS" format.
3 FILE :This contains the current filename as a string literal.
4 LINE__ : This contains the current line number as a decimal constant.
5 STDC :Defined as 1 when the compiler complies with the ANSI standard.
Sample Program
#include <stdio.h>
int main() {
printf("File :%s\n", FILE );
printf("Date :%s\n", DATE );
printf("Time :%s\n", TIME );
printf("Line :%d\n", LINE );
printf("ANSI :%d\n", STDC );
}
When the above code in a file test.c is compiled and executed, it produces the followingresult
File :test.c
Date :Jun 2 2012
Time :03:36:24
Line :8
ANSI :1
29
/* Program to print square and cube values using macro substitution*/
#define square(n) (n*n)
#define cube(n) (n*n*n)
#include<stdio.h>
void main()
{
int a=5,sq,cu;
sq=square(a);
cu=cube(a);
printf("Square value of 5 is %d\n",sq);
printf("\nCube value of 5 is %d",cu);
}

Output:
Square value of 5 is 25
Cube value of 5 is 125

30
1.20 COMPILATION PROCESS
1. Creating a C program
2. Compilation
3. Linking
4. Executing

Creating a C program
1. C compiler has an editor for writing source code. There we have to type or work with C
program.
2. It will high light various parts of the program in different color. After creating a C program,
we have to save the file with .c extension.
Example: sample.c

Compilation
1. It is a process of converting source code into machine code.
2. The program which is used to convert source code into machine code calledcompiler.
3. The compiler scans the source code for errors, if any errors occur then the compilation
process willnot be completed it will indicate error.
4. After all errors are cleared as an indication of successful compilation, an object file
will be created with .obj extension.
5. Object code is the intermediate form of the program.
Linking
1 .c program contain pre defined functions
2 Here necessary files are linked to the object code.
3 After linking the libraries the .exe file of the program is created.
4 The linker will also detect errors.
Ex: if a source code uses a lib function that does not exist linker generate a linking
error.If error available, linker won‟t create .exe file

Executing
1. .exe file is given to the system loader, and starts executing.
2. If the .exe files also have some errors, this produce wrong output or halt theprogram.
3. After these errors are removed from the source code, we have to compile it again to create .exe
file.
4. After successful compilation output will be produced.

31
Part A

1. What is meant by a data type? Give its classifications.


2. Differentiate between variable and constant.
3. Define keywords
4. Enlist the rules for naming variable/identifier
5. Write the use of ternary or conditional operator.
6. Summarize the various types of C operators
7. List the types of I/O statements available in C
8. Show the difference between while and do-while.
9. What are the various types of operators of C
10. What is compilation process?
11. Differentiate between formatted and unformatted I/O . give example
12. Differentiate between entry controlled and exit controlled loop
13. Differentiate between break and continue statement
14. How does a pre-processor work
15. What is external storage class
16. What is the use of pre-processor directives
17. List out C tokens
18. What is Enumeration constant
19. Give the difference between the statement a=5 and a==5 in C
20. What is Expression

PART B
1. Describe the structure of a C program with an example.
2. Illustrate about the various data types in C
3. Explain the following:
i. Keywords
ii. Constants
4. Explain the different types of operators used in C‟ with examples.
5. Discuss in detail about operator precedence and expressions with an example
6. Explain in detail the operation of various looping statements in C with suitableexamples.
7. Explain in detail the Decision making statements in C with suitable examples.
8. Explain various storage classes in C
9. Explain the various formatted and unformatted I/O with examples
10. Explain the pre-processor directives with examples.
11. Write a C program to find the biggest of 3 nos
12. Write a C program to find the sum of 10 non-negative numbers entered by user
13. Write a C program to find whether a given number is a palindrome
14. Write briefly about the compilation process
15. Write about I/O statements of C
16. Explain the difference between the else if ladder and switch case statement in C with suitable
example

33

You might also like