0% found this document useful (0 votes)
10 views45 pages

C-programming Unit 1 Notes

The document outlines the curriculum for a C programming course, detailing course objectives, units covering various programming concepts, and expected outcomes. It includes topics such as basics of C programming, arrays, functions, pointers, structures, and file processing. Additionally, it lists textbooks and references for further reading.

Uploaded by

ruthraelumalai
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
10 views45 pages

C-programming Unit 1 Notes

The document outlines the curriculum for a C programming course, detailing course objectives, units covering various programming concepts, and expected outcomes. It includes topics such as basics of C programming, arrays, functions, pointers, structures, and file processing. Additionally, it lists textbooks and references for further reading.

Uploaded by

ruthraelumalai
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 45

DEPARTMENT OF COMPUTER SCIENCE AND

ENGINEERING REGULATION R2021


I YEAR - II SEMESTER

CS3251 – PROGRAMMING IN C
CS3251 PROGRAMMING IN C

COURSE OBJECTIVES:
• To understand the constructs of C Language.
• To develop C Programs using basic programming constructs
• To develop C programs using arrays and strings
• To develop modular applications in C using functions
• To develop applications in C using pointers and structures
• To do input/output and file handling in C

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

UNIT II ARRAYS AND STRINGS


Introduction to Arrays: Declaration, Initialization – One dimensional array – Two dimensional
arrays - String operations: length, compare, concatenate, copy – Selection sort, linear and binary
search.
UNIT III FUNCTIONS AND POINTERS
Modular programming - Function prototype, function definition, function call, Built-in
functions (string functions, math functions) – Recursion, Binary Search using recursive
functions – Pointers – Pointer operators – Pointer arithmetic – Arrays and pointers – Array of
pointers – Parameter passing: Pass by value, Pass by reference.

UNIT IV STRUCTURES AND UNION


Structure - Nested structures – Pointer and Structures – Array of structures – Self referential
structures – Dynamic memory allocation - Singly linked list – typedef – Union - Storage classes
and Visibility.

UNIT V FILE PROCESSING


Files – Types of file processing: Sequential access, Random access – Sequential access file -
Random access file - Command line arguments.
COURSE OUTCOMES: Upon completion of the course, the students will be able to
CO1: Demonstrate knowledge on C Programming constructs
CO2: Develop simple applications in C using basic constructs
CO3: Design and implement applications using arrays and strings
CO4: Develop and implement modular applications in C using functions.
CO5: Develop applications in C using structures and pointers.
CO6: Design applications using sequential and random access file processing.

TOTAL : 45 PERIODS

TEXT BOOKS:
1. ReemaThareja, “Programming in C”, Oxford University Press, Second Edition, 2016.
2. Kernighan, B.W and Ritchie,D.M, “The C Programming language”, Second Edition, Pearson
Education, 2015.

REFERENCES:
1. Paul Deitel and Harvey Deitel, “C How to Program with an Introduction to C++”, Eighth edition,
Pearson Education, 2018.
2. Yashwant Kanetkar, Let us C, 17th Edition, BPB Publications, 2020.

3. Byron S. Gottfried, “Schaum’s Outline of Theory and Problems of Programming with C”,
McGraw-Hill Education, 1996.
4. Pradip Dey, Manas Ghosh, “Computer Fundamentals and Programming in C”, Second Edition,
Oxford University Press, 2013.
5. Anita Goel and Ajay Mittal, “Computer Fundamentals and Programming in C”, 1st Edition,
Pearson Education, 2013.
UNIT 1
BASICS OF C PROGRAMMING(C116.1 ; PO 1,2,3,4,5,9,11,12)
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 .

INTRODUCTION TO PROGRAMMING PARADIGMS

C INTRODUCTION:
The programming language “C‟ was developed in the early 1970s by Dennis Ritchie at Bell Laboratories.
Although C was initially developed for writing system software, today it has become such a popular language
that a variety of software programs are written using this language.
The greatest advantage of using C for programming is that it can be easily used on different types of
computers. Many other programming languages such as C++ and Java are also based on C which means that
you will be able to learn them easily in the future. Today, C is widely used with the UNIX operating system.

PROGRAMMING PARADIGMS:
In computing, a program is a specific set of ordered operation for a computer to perform.The process of
developing and implementing various sets of instruction to enable a computer to perform a certain task is
called PROGRAMMING.
PROGRAMMING PARADIGMS INCLUDE:
1. IMPERATIVE PROGRAMMING PARADIGMS:
Command show how the computation takes place, step by step. Each step affects the global
state of the computation.
2. STRUCTURED PROGRAMMING PARADIGMS:
It is a kind of imperative programming where the control flow is defined by nested loops,
conditionals, and subroutines, rather than via gotos. Variables generally local to blocks.
3. OBJECT ORIENTED PROGRAMMING(OOP) PARADIGMS:
It is a programming paradigms based on the concepts of objects, which may contain data, in
the form of fields, often known as attributes, and code, in the form of procedures, often
known as methods.
4. DECLARATIVE PROGRAMMING PARADIGMS:
The programmer states only what the results should look like , not how to obtain it. No loops,
no assignments, etc. Whatever engines that interprets this code is just supposed go gets the
desired information and can use whatever approach its wants.
5. FUNCTIONAL PROGRAMMING PARADIGMS:
In functional programming, control flow is expressed by combining functional calls, rather
than by assigning values to variables.
6. PROCEDURAL PROGRAMMING PARADIGMS:
This paradigms includes imperative programming with procedure calls.
7. EVENT DRIVEN PROGRAMMING PARADIGMS:
In which the flow of the program is determined by events such as user action(mouse clicks,
key presses), sensor output, or message from other program/threads. It is the dominant
paradigms used in GUI and other applications that are centred on performing certain action in
response to user input.
8. FLOW DRIVEN PROGRAMMING PARADIGMS:
Programming processes communicating with each other over predefined channels.
9. LOGIC PROGRAMMING PARADIGMS:
Here programming is done by specifying a set of facts and rules. An engine infers the answer
to question.
10. CONSTRAINTS PROGRAMMING PARADIGMS:
An engine finds the value that meet the constraints.
One of the characteristics of a language is its support for particular programming
paradigms. For example: small talks has direct support for programming in the object oriented
way, so it might called an object oriented language.
Very few language implement a paradigms 100%, when they do, they are “PURE”. It is
incredibly rare to have a “pure OOP language” or a “pure functional language”.
A lot of language will facilitate programming in one or more paradigms. If a language is
purposely designed to allow programming in many paradigms is called a “multi paradigms
language”.

APPLICATION OF C
1. OPERATING SYSTEM
2. EMBEDDED SYSTEM
3. GUI(GRAPHICAL USER INTERFACE)
4. NEW PROGRAMMING PLATFORMS
5. GOOGLE
6. MOZILLA FIREBOX AND THUNDERBIRD
7. MYSQL
8. COMPILER DESIGN
9. ASSEMBLERS
10. TEXT EDITORS
11. DRIVERS
12. NETWORK DEVICES
13. GAMING AND ANIMATION
FEATURES OF C
PROGRAMMING/ADVANTAGES:
 C is a robust language with rich set of built in function.
 Programs written in c are efficient and fast.
 C is highly portable, programs once written in c can be run on another machine with minor or no
modification.
 C is basically a collection of c library functions, we can also create our own function and add it to
the c library.
 C is easily extensible.
DISADVANTAGE OF C:
 C doesnot provide OOP.
 There is no concepts of namespace in c.
 C doesnot provides binding or wrapping up of a single unit.
 C doesnot provide constructor and destructor.

Part A
Q.n
Questions CO PO
o
1. Who developed the C programming language and when? C116.1 1
2. Why is C considered a portable language? C116.1 1,3
3. What is a programming paradigm? C116.1 1
4. Name any four programming paradigms. C116.1 1
5. Define imperative programming with an example. C116.1 1

6. What is the difference between structured and procedural programming? C116.1 1,2

7. Why is C widely used for system programming? C116.1 1,5

8. What is the main advantage of using C over other high-level languages? C116.1 1,3

9. Mention two disadvantages of C programming C116.1 1


Part B
1. Explain different programming paradigms with examples. C116.1 1,2,3
Discuss the applications of C in various domains such as OS, embedded
2. C116.1 1,3,5,9
systems, and networking.
Compare C with other programming languages like C++, Java, and Python in
3. C116.1 1,2,3,5,11
terms of applications, advantages, and limitations.

STRUCTURE OF C (C116.1 ; PO 1,2,3,4,5,9,11,12)

Documentation section:
The documentation section consists of a set of comment lines giving the name of
the program, the author and other details, which the programmer would like to use later.

Link section: The link section provides instructions to the compiler to link functions
from the system library such as using the #include directive.

Definition section: The definition section defines all symbolic constants such using the #define
directive.
Global declaration section: There are some variables that are used in more than one function.
Such variables are called global variables and are declared in the global declaration section
that
is outside of all the functions. This section also declares all the user-defined functions.
Main () function section: Every C program must have one main function section. This section
contains two parts; declaration part and executable part.
Declaration part:
The declaration part declares all the variables used in the executable part.
Executable part:
There is at least one statement in the executable part. These two parts must appear
between the opening and closing braces. The program execution begins at the opening brace
and ends at the closing brace. The closing brace of the main function is the logical end of the
program. All statements in the declaration and executable part end with a semicolon.

Subprogram section:
If the program is a multi-function program then the subprogram section contains all the
user-defined functions that are called in the main () function. User-defined functions are
generally placed immediately after the main () function, although they may appear in any
order. All section, except the main () function section may be absent when they are not
required.
Part A
Q.no Questions CO PO
1. What is the structure of a C program? C116.1 1,2
2. Why is the #include directive used in C? C116.1 1,3,5
3. What is the purpose of the main() function in C? C116.1 1,3
4. What is the difference between declaration and executable sections? C116.1 1,3
5. What is the role of subprograms in modular programming? C116.1 1,3

Part B

1. Explain the structure of a C program with a diagram and example. C116.1 1,2,3,5,11
Discuss how modular programming is implemented using functions and
2. C116.1 1,2,3,5,9,11
subprograms in C.
Part C
Explain all sections of a C program with a structured example and a
1. C116.1 1,2,3,9,12
detailed diagram.

C PROGRAMMING: DATA-TYPES (C116.1 ; PO 1,2,3,4,5,6,7,9,11,12)


A data-type in C programming is a set of values and is determined to act on
those values. C provides various types of data-types which allow the programmer to
select the appropriate typefor the variable to set its value.
The data-type in a programming language is the collection of data with values having
fixed meaning as well as characteristics. Some of them are integer, floating point, character etc.
Usually, programming languages specify the range values for given data-type.
C Data Types are used to:

• Identify the type of a variable when it declared.


• Identify the type of the return value of a function.
• Identify the type of a parameter expected by a
function. ANSI C provides three types of data types:

1. Primary(Built-in) Data Types:void, int, char, double and float.

2. Derived Data Types:Array, References, and Pointers.

3. User Defined Data Types:Structure, Union, and Enumeration.


Primary Data Types:

Every C compiler supports five primary data types:


void -As the name suggests it holds no value and is generally used for specifyingthe type of
function or what it returns. If the function has a void type, it means that the function will not
return any value.
int-Used to denote an integer type.
Char-Used to denote a character type.
float, double-Used to denote a floating point
type.
int*,float*,char*- used to denote a pointer type.

Declaration of Primary Data Types with variable name:


After taking suitable variable names, they need to be assigned with a data type. This is how the
data types are used along with variables:
Example:
int age;
char
letter;
float height, width;

Derived Data Types


C supports three derived data types:
DATATYPES DESCRIPTION
Arrays Arrays are sequences of data items having homogeneous
values. They have adjacent memory locations to store
values.
References Function pointers allow referencing functions with
a particular signature.

Pointers These are powerful C features which are used to access the
memory and deal with their addresses.

User Defined Data Types

C allows the feature called type definition which allows programmers to define their own

identifier that would represent an existing data type. There are three such types:

Data Types Description

Structure It is a package of variables of different types under a single name. This is


done to handle data efficiently. “struct” keyword is used to define a structure

Union These allow storing various data types in the same memory location.
Programmers can define a union with different members but only a single
member can contain a value at given time.
Enum Enumeration is a special data type that consists of integral constants and each of them
is assigned with a specific name. “enum” keyword is used to define the enumerated
data type.
Example for Data Types and Variable Declarations in C #include <stdio.h> int main()
{

int a = 4000; // positive integer data type float b = 5.2324; // float data type char
c = 'Z'; // char data type
long d = 41657; // long positive integer data type long e = -21556; // long -ve integer data type int f
= -185; // -ve integer data type
short g = 130; // short +ve integer data type short h = -130; // short -ve integer data type double i
= 4.1234567890; // double float data type float j = -3.55; // float data type
}

Let's see the basic data types. Its size is given according to 32 bit architecture.
Data Types Memory Size Range

Char 1 byte −128 to 127

signed char 1 byte −128 to 127

unsigned char 1 byte 0 to 255

Short 2 byte −32,768 to 32,767

signed short 2 byte −32,768 to 32,767

unsigned short 2 byte 0 to 65,535

Int 2 byte −32,768 to 32,767

signed int 2 byte −32,768 to 32,767

unsigned int 2 byte 0 to 65,535

short int 2 byte −32,768 to 32,767

signed short int 2 byte −32,768 to 32,767


unsigned short 2 byte 0 to 65,535
int
long int 4 byte -2,147,483,648 to
2,147,483,647
signed long int 4 byte -2,147,483,648 to
2,147,483,647
unsigned long 4 byte 0 to 4,294,967,295
int
float 4 byte
double long 8 byte
double 10 byte
The storage representation and machine instructions differ from machine to Machine.
sizeof operator can use to get the exact size of a type or a variable on a particular platform.
Example: #include <stdio.h>
#include
<limits.h> int
main() {
printf("Storage size for int is: %d \n", sizeof(int)); printf("Storage
size for char is: %d \n", sizeof(char)); return 0
}
CONSTANTS
A constant is a value or variable that can't be changed in the program, for example:
10, 20, 'a', 3.4, "c programming" etc. There are different types of constants in C programming.

List of Constants in C

Constant Example

Decimal Constant 10, 20, 450 etc.

Real or Floating-point Constant 10.3, 20.2, 450.6 etc.

Octal Constant 021, 033, 046 etc.

Hexadecimal Constant 0x2a, 0x7b, 0xaa etc.

Character Constant 'a', 'b', 'x' etc.

String Constant "c", "c program", "c in javatpoint"

etc 2 ways to define constant in C

There are two ways to define constant in C programming.

1. const keyword
2. #define preprocessor
C const keyword:
The const keyword is used to define constant in C programming.
Example:
const float PI=3.14;
Now, the value of PI variable can't be changed.
#include<stdio.h>
int main()
{
const float PI=3.14;
printf("The value of PI is: %f",PI);
return 0;}
Output:
The value of PI is: 3.140000
C #define preprocessor
The #define preprocessor directive is used to define constant or micro substitution. It can use any
basic data type.
Syntax: #define token value
Let's see an example of #define to define a constant.
#include <stdio.h>
#define PI 3.14
main()
{
printf("%f",PI);
}
Output:
3.140000
Backslash character constant:
C supports some character constants having a backslash in front of it. The lists of backslash
characters have a specific meaning which is known to the compiler. They are also termed as “Escape
Sequence”.
Example:
\t is used to give a tab
\n is used to give new line
Constants Meaning Constants Meaning
\a beep sound \n newline
\v vertical tab \\ backslash

\b backspace \r carriage return


single quote \0 null
form feed \t horizontal tab
\” double quote
ENUMERATION CONSTANTS:
An enum is a keyword, it is an user defined data type. All properties of integer are
applied on Enumeration data type so size of the enumerator data type is 2 byte . It work
like the Integer. It is used for creating an user defined data type of integer. Using enum we
can create sequence of integer constant value.

Syntax: enum tagname{value1,value2,value3,….};

• In above syntax enum is a keyword. It is a user defined data type.

• In above syntax tagname is our own variable. tagname is any variable name.

• value1, value2, value3,are create set of enum values.

It is start with 0 (zero) by default and value is incremented by 1 for the sequential
identifiers in the list. If constant one value is not initialized then by default sequence will be
start from zero and next to generated value should be previous constant value one.

Example:

enum week{sun,mon,tue,wed,thu,fri,sat}; enum week today;

• In above code first line is create user defined data type called week.

• week variable have 7 value which is inside { } braces.

- today variable is declare as week type which can be initialize any data or
value among 7 (sun, mon,).
Example:

#include<stdio.h>
#include<conio.h>
enum abc{x,y,z};
void main()
{
int a;
clrscr();
a=x+y+z; //0+1+2
printf(“sum: %d”,a);
getch();
}
Output:
Sum: 3
KEYWORDS:
A keyword is a reserved word. You cannot use it as a variable name, constant name etc. There
are only 32 reserved words (keywords) in C language.
A list of 32 keywords in c language is given below:

auto break case Char Const Continue default do Double else


enum extern float For Goto If int long register return
short signed sizeof Static Struct Switch typedef union unsigned void

volatile while

Part A
Q.no Questions CO PO
1. What is a data type in C? C116.1 1,3
2. List the three types of data types in C C116.1 1,2,3
3. What is the difference between int and float data types? C116.1 1,2
4. Define primary data types in C with examples. C116.1 1,3
5. What is the purpose of the sizeof operator in C? C116.1 1,5

6. What is the difference between signed and unsigned integers? C116.1 1,3
7. How does const differ from #define in defining constants? C116.1 1,3
Part B

1. Explain the different data types in C with examples and memory sizes. C116.1 1,2,3,5,11
Discuss constants in C with examples of different types of constants and
2. C116.1 1,3,5
their usage.
Explain enumeration constants, their syntax, and use cases in C
3, C116.1 1,2,3,5,9,11
programming.
Part C
Explain primary, derived, and user-defined data types in C with
1. C116.1 1,3,5,7,9,11,12
examples. Compare their storage sizes and use cases.

OPERATORS (C116.1, PO-1,2,3,5,7,9,11,12)


Operator is a special symbol that tells the compiler to perform specific mathematical or logical Operation.
 Arithmetic Operators
 Relational Operators
 Logical Operators
 Bitwise Operators
 Assignment Operators
 Ternary or Conditional Operators

Arithmetic Operators:
Given table shows all the Arithmetic operator supported by C Language. Lets suppose variable A
hold 8 and B hold 3.
Operator Example (int A=8, B=3) Result
+ A+B 11
- A-B 5
* A*B 24
/ A/B 2
% A%4 0

Relational Operators:
Which can be used to check the Condition, it always return true or false. Lets suppose variable
hold 8 and B hold 3.

Logical Operator:

Which can be used to combine more than one Condition?. Suppose you want to combined two
conditions A<B and B>C, then you need to use Logical Operator like (A<B) && (B>C). Here && is
Logical Operator.

Operator Example (int A=8, B=3, C=-10) Result


&& (A<B) && (B>C) False
|| (B!=-C) || (A==B) True
! !(B<=-A) True

Truth table of Logical Operator

C1 C2 C1&&C2 C1||C2 !C1 !C2


T T T T F F
T F F T F T
F T F T T F
F F F F T T

Assignment operators:
Which can be used to assign a value to a variable. Lets suppose variable A hold 8 and B hold 3.

Operator Example (int A=8, B=3) Result


+= A+=B or A=A+B 11
-= A-=3 or A=A+3 5
*= A*=7 or A=A*7 56
/= A/=B or A=A/B 2
%= A%=5 or A=A%5 3
a=b Value of b will be assigned to a
Increment and Decrement Operator:
Increment Operators are used to increased the value of the variable by one and Decrement
Operators are used to decrease the value of the variable by one in C programs.
Both increment and decrement operator are used on a single operand or variable, so it is called as
a unary operator. Unary operators are having higher priority than the other operators it means unary
operators are executed before other operators.
Increment and decrement operators are cannot apply on constant.
The operators are ++, -- Type of Increment Operator
 pre-increment
 post-increment
pre-increment (++ variable):
In pre-increment first increment the value of variable and then used inside the expression
(initialize into another variable).
Syntax:
++variable;
post-increment (variable +
+):
In post-increment first value of variable is used in the expression (initialize into another variable)
and then increment the value of variable.
Syntax:
variable++;
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
int x,i; i=10;
x=++i;
printf(“Pre-increment\n”); Output:
printf(“x::%d”,x); Pre-increment x::10
printf(“i::%d”,i); i::10
i=10; Post-increment x::10
x=i++; i::11
printf(“Post-increment\n”);
printf(“x::%d”,x);
printf(“i::%d”,i);
}
Type of Decrement Operator:
 pre-decrement
 post-decrement
Pre-decrement (-- variable):
In pre-decrement first decrement the value of variable and then used inside the expression
(initialize into another variable).
Syntax:
--variable;

Post-decrement (variable --):


In Post-decrement first value of variable is used in the expression (initialize into another variable)
and then decrement the value of variable.
Syntax:
variable--;
Example:
#include<stdio.h>
#include<conio.h> Output:
void main() Pre-decrement x::9
{ i::9
int x,i; i=10; Post-decrement x::10
i::9
x=--i;
printf(“Pre-decrement\n”);
printf(“x::%d”,x);
printf(“i::%d”,i);
i=10;
x=i--;
printf(“Post-decrement\n”);
printf(“x::%d”,x);
printf(“i::%d”,i);
}

Ternary Operator:
If any operator is used on three operands or variable is known as Ternary Operator. It can be
represented with ? : . It is also called as conditional operator
Advantage of Ternary Operator
Using ?: reduce the number of line codes and improve the performance of application.
Syntax:

Expression 1? Expression 2: Expression 3;

In the above symbol expression-1 is condition and expression-2 and expression-3 will be either
value Or variable or statement or any mathematical expression. If condition will be true expression-2 will
be execute otherwise expression-3 will be executed.
Conditional Operator flow diagram

Example:

find largest number among 3 numbers using ternary operator


#include<stdio.h>
void main()
{
int a,b,c,large; Output:
printf(“Enter any three numbers:”); scanf(“%d Enter any three numbers: 12 67 98
%d%d”,&a,&b,&c); The largest number is 98
large=a>b?(a>c?a:c):(b>c?b:c);
printf(“The largest number is:%d”,large);
}

Special Operators:
C supports some special operators

Operator Description

sizeof() Returns the size of an memory location.

& Returns the address of an memory location.

* Pointer to a variable.
Expression evaluation

Priority In C language expression evaluation is mainly depends on priority and

associativity. This represents the evaluation of expression starts from "what"

operator.
Associativity
It represents which operator should be evaluated first if an expression is containing more than one
operator with same priority.
Precedence of operators :
The precedence rule is used to determine the order of application of operators in evaluating sub
expressions. Each operator in C has a precedence associated with it. The operator with the highest
precedence is operated first.
Associativity of operators :
The associativity rule is applied when two or more operators are having same precedence in the
sub expression. An operator can be left-to-right associative or right-to-left associative.
Rules for evaluation of expression:
• First parenthesized sub expressions are evaluated first.

• If parentheses are nested, the evaluation begins with the innermost sub expression.

• The precedence rule is applied to determine the order of application of operators in

evaluating sub expressions.


• The associability rule is applied when two or more operators are having same precedence in the
sub expression.
EXPRESSION:

An expression is a sequence of operators and operands that specifies computation of a value.

For e.g, a=2+3 is an expression with three operands a,2,3 and 2 operators = & +

Simple Expressions & Compound Expressions:

An expression that has only one operator is known as a simple expression. E.g: a+2

An expression that involves more than one operator is called a compound expression.

E.g: b=2+3*5.

Part A
Q.no Questions CO PO
1. What is an operator in C? C116.1 1,2
2. Name any four types of operators in C. C116.1 1,2,
3. What is the difference between relational and logical operators? C116.1 1,2
4. Define arithmetic operators with examples. C116.1 1,3
5. What is the purpose of the conditional (ternary) operator in C? C116.1 1,5

6. What is the difference between pre-increment and post-increment? C116.1 1,3


7. How does the size of operator work in C? C116.1 1,3
Part B

1. Explain different types of operators in C with examples. C116.1 1,2,3,5,11


Discuss the use of logical and bitwise operators in decision-making with
2. C116.1 1,3,5
suitable examples.
Explain the working of increment and decrement operators with
3, C116.1 1,2,3,5,9,11
examples and memory representation with expression
Part C
Explain all types of operators in C with syntax, examples, precedence,
1. C116.1 1,3,5,7,9,11
and associativity. Provide sample code demonstrating their use.
IO STATEMENT(C116.1, PO- 1,3,5,7,9,11,12)

The I/O functions are classified into two types:

 Formatted Functions

 Unformatted functions

FORMATTED INPUT FUNCTION:


SCANF():
It is used to get data in a specified format. It can accept different data types.
Syntax:
scanf(“Control String”, var1address, var2address, …);
EXAMPLE:
#include<stdio.h>
#include<conio.h>
Void main()
{
int
a,b,sum;
clrscr();
scanf(“%d %d”,&a,&b);
sum= a+b;
}

FORMATTED OUTPUT FUNCTION:


PRINTF():
The printf( ) function is used to print data of different data types on the console in a specified
format.

Syntax:
printf(“Control String”, var1, var2, …);
EXAMPLE:
#include<stdio.h>
#include<conio.h>
Void main()

{
int a,b,sum;
clrscr();
printf(“enter two numbers:”); Enter two numbers: 5 4
scanf(“%d %d”,&a,&b); Sum is 9

sum= a+b;
printf(“sum is:%d”,sum);
}
UNFORMATTED INPUT FUNCTION:
 getchar()
 getch()
 getche()
 gets()
getchar():
This function reads a single character data from the standard input.
Syntax:
variable_name=getchar();

Example:
#include<stdio.h>
OUTPUT:
#include<conio.h> j
void main()
{
Char ch;
ch=getchar();
Printf(“%c”,ch);
}
getch():
getch() accepts only a single character from keyboard. The character entered through getch() is not
displayed in the screen (monitor).
Syntax:
variable_name = getch();

Example:
#include<stdio.h>
#include<conio.h>
void main()
OUTPUT:
{ Ch=a

Char ch;
ch=getch();
Printf(“ch=%c”,ch);
}
getche():

screen. getche() also accepts only single character, but getche() displays the entered character in the

Syntax:
variable_name = getche();
Example:
#include<stdio.h>
#include<conio.h>
void main()
OUTPUT:
{ a
Ch=a
Char ch;
ch=getche();
Printf(“ch=%c”,ch);
}
gets():
This function is used for accepting any string through stdin (keyboard) until enter
key is pressed.
Syntax:
gets(variable_name);
Example:
#include<stdio.h>
#include<conio.h>

void main()
{
Char ch[10]; OUTPUT:
cprogram
gets(ch); Printf(“ch= Ch=cprogram
%s”,ch); getch();
}
UNFORMATTED OUTPUT FUNCTION:
 putchar()
 putch()
 puts()
putchar():
This function prints one character on the screen at a time.
Syntax :
putchar(variable name);
Example: OUTPUT:
#include<stdio.h> enter a character: j
j
#include<conio.h>
void main()
{
Char ch;
printf(“enter a character:”);
ch=getchar();
putchar(ch);
getch();
}
putch():
putch displays any alphanumeric characters to the standard output device. It displays only one
character at a time.
Syntax:
putch(variable_name);

Example:
include<stdio.h>
#include<conio.h>
void main()
{ OUTPUT:
char ch; Press any character:
Pressed character is: e
clrscr();
printf(“Press any character: ”);
ch = getch();
printf(“\nPressed character is:”);
putch(ch);
getch();
}
puts():

This function prints the string or character array

Part A
Q.no Questions CO PO
What is the difference between formatted and unformatted I/O
1. C116.1 1,2
functions in C?
2. What is the syntax of the scanf() function? C116.1 1
3. How does printf() work in C? C116.1 1,3
4. What is the difference between getchar() and getch()? C116.1 1,3
5. Define the use of puts() in C. C116.1 1,5

6. How does the putchar() function work? C116.1 1,3


7. What is the purpose of gets() and why is it discouraged in C? C116.1 1,3
Part B

1. Explain different types of I/O functions in C with examples. C116.1 1,2,3,5,11


Compare formatted and unformatted input/output functions
2. C116.1 1,3,5
with examples.
Explain character and string input/output functions in C with
3, C116.1 1,2,3,5,9,11
sample programs.
Part C
Explain all I/O functions in C with syntax, examples, and
1. proper usage scenarios. Provide a program demonstrating their C116.1 1,3,5,7,9,11,12
implementation.
ASSIGNMEN STATEMENT AND DECISION MAKINF STATEMENT(C116.1, PO- 1,2,3,5,7,9,11,12)
The assignment statement has the following form:
Syntax:
variable = expression/constant/variable;
Its purpose is saving the result of the expression to the right of the assignment operator to the
variable on the left. Here are some rules:
 If the type of the expression is identical to that of the variable, the result is saved in the variable.
 Otherwise, the result is converted to the type of the variable and saved there.
 If the type of the variable is integer while the type of the result is real, the
fractional part, including the decimal point, is removed making it an integer result.
 If the type of the variable is real while the type of the result is integer, then a
decimal point is appended to the integer making it a real number.
 Once the variable receives a new value, the original one disappears and is no more
available. Examples of assignment statements,
b = c ; /* b is assigned the value of c */
a = 9 ; /* a is assigned the value 9*/
b = c+5; /* b is assigned the value of expr c+5 */
 The expression on the right hand side of the assignment statement can be: An
arithmetic expression;
 A relational expression;
 A logical expression;
 A mixed expression.
For
example, int
a;
float b,c ,avg, t;
avg = (b+c) / 2; /*arithmetic expression
*/ a = b && c; /*logical expression*/
a = (b+c) && (b<c); /* mixed expression*/
DECISION MAKING STATEMENTS:
Decision making statement is depending on the condition block need to be executed or not which
is decided by condition.
If the condition is "true" statement block will be executed, if condition is "false" then statement
block will not be executed.
In this section we are discuss about if-then (if), if-then-else (if else), and switch statement. In C
language there are three types of decision making statement.
• if
• if-else
• switch
if Statement:
if-then is most basic statement of Decision making statement. It tells to program to execute a
certain part of code only if particular condition is true.
Syntax:

if(condition)
{
Statements executed if the condition is true
}
FLOWCHART:

Constructing the body of "if" statement is always optional, Create the body when we are having multiple
statements.
For a single statement, it is not required to specify the body.
If the body is not specified, then automatically condition part will be terminated with next semicolon ( ; ).
Example:
#include<stdio.h>
int main()
{
int num=0;
printf(“enter a number:”); OUTPUT:
scanf(“%d”,&num); Enter a number: 4
4 is even number
if(num%2==0)
{
printf(“%d is even number”,num);
}
return 0;
}
if-else statement:
In general it can be used to execute one block of statement among two blocks, in C language if
and else are the keyword in C.
Syntax:
if(expression)
{

else

Flowchar
t:
In the above syntax whenever condition is true all the if block statement are executed remaining
statement of the program by neglecting else block statement. If the condition is false else block statement
remaining statement of the program are executed by neglecting if block statements.
Example:
#include<stdio.h>
void main()
{
int age;
printf(“enter age:”)
scanf(“%d”,&age);
Output:
if(age>=18) Enter age: 18
Eligible to vote
{ Enter age: 17
Not eligible to vote
printf(“age:%d”,age);
printf(“eligible to vote” );
}
else
{
printf(“age:%d”,age);
printf(“not eligible to vote” );
}
Nested if:
When an if else statement is present inside the body of another “if” or “else” then this is called
nested if else.
Syntax of Nested if else statement:

if(condition) {
//Nested if else inside the body of "if"
if(condition2) {
//Statements inside the body of nested "if"
}
else {
//Statements inside the body of nested "else"
}
}
else {
//Statements inside the body of "else"
}
Flowchart:

EXAMPLE:
#include<stdio.h>
void main() Output:
Enter age and salary: 55 55000
{ 65000
int age, salary;
printf(“enter age and salary”);
scanf(%d %d”, &age,&salary);
if(age>50)
{
if(salary<60000)
{
salary=salary+10000
;printf(“%d”,salary);
}
else
{
salary=
salary+5000;
printf(“%d”,salary);
}
}
else
{
salary=salary+1000;
printf(“%d”,salary);
}
printf(“end of program”);
getch();
}
Switch:
A switch statement work with byte, short, char and int primitive data type, it also works with
enumerated types and string.
Syntax:
switch(expression/variable)
{
case value1:
statements;
break;//optional
case value2:
statements;
break;//optional
default:
statements;
break;//optional
}
Rules for apply switch:

1. With switch statement use only byte, short, int, char data type.
2. You can use any number of case statements within a switch.
3. Value for a case must be same as the variable in switch
Flowchart:

Example: #include
<stdio.h> #include
<math.h> #include
<stdlib.h> void
main()
{
// declaration of local variable op; int
op, n1, n2;
printf (" enter 2 number: "); scanf(%d
%d”,&n1,&n2);
printf (" \n 1 Addition \t \t 2 Subtraction \n 3 Multiplication \t 4 Division \n 5 Exit \n \n Please,
Make a choice ");
scanf ("%d", &op); // accepts a numeric input to choose the operation
switch (op)
{
case 1:
printf ("sum is :%d ",n1+n2);
break;
case 2:
printf ("difference is :%d ",n1-n2);
break;
case 3:
printf ("multiplication :%d ",n1*n2);
break;
case 4:
printf ("division :%d ",n1/n2);
break;
case 5:
printf
("exit”);
break;
default:
printf(“enter the number between 1 to 5:”);
}
}

Part A
Q.no Questions CO PO
1. What is an assignment statement in C? C116.1 1,2
2. Give an example of a simple assignment statement. C116.1 1,3
3. What is the difference between = and == operators in C? C116.1 1,2
4. What is the purpose of an if statement in C? C116.1 1,3
5. How does a switch statement work in C? C116.1 1,5

6. What is a nested if statement? C116.1 1,3


7. How does an if-else statement improve program efficiency? C116.1 1,3
Part B

Explain assignment statements in C with examples of


1. C116.1 1,3,5
arithmetic, relational, logical, and mixed expressions.
Discuss decision-making statements (if, if-else, switch) in C
2. C116.1 1,3,5,11
with examples.
Explain nested if and switch statements with a real-world use
3, C116.1 1,2,3,5,9,11
case.
Part C
Explain assignment operators and decision-making
statements in C with syntax, examples, and flowcharts.
1. C116.1 1,3,5,7,9,11,12
Provide sample programs demonstrating their
implementation.
LOOPING STATEMENTS (C116.1, PO-1,2,3,5,7,9,11,12)
Sometimes it is necessary for the program to execute the statement several times, and C loops
execute a block of commands a specified number of times until a condition is met.
What is Loop?
A computer is the most suitable machine to perform repetitive tasks and can tirelessly do a task
tens of thousands of times. Every programming language has the feature to instruct to do such repetitive
tasks with the help of certain form of statements. The process of repeatedly executing a collection of
statement is called looping . The statements get executed many numbers of times based on the condition.
But if the condition is given in such a logic that the repetition continues any number of times with no
fixed condition to stop looping those statements, then this type of looping is called infinite looping.
C supports following types of loops:
• while loops
• do while loops
• for loops
while loops:

C while loops statement allows to repeatedly run the same block of code until a condition is met.
while loop is a most basic loop in C programming. while loop has one control condition, and executes as
long the condition is true.
The condition of the loop is tested before the body of the loop is executed, hence it is called
an entry-controlled loop.
Syntax:
while (condition)
{
statement(s); Increment statement;
}
Example: #include<stdio.h>void main ()
{
int i=1; clrscr();
while(i<=10)
{
printf(“%d”,i); i++;
} getch();
}

Output:
1 2 3 4 5 6 7 8 9 10
Flowchart:

Do..while loops:
C do while loops are very similar to the while loops, but it always executes the code block at
least once and furthermore as long as the condition remains true. This is an exit- controlled loop.
Syntax:
do{
statement(s);
}while( condition );

Flowchart:
EXAMPLE:
#include<stdio.h> void
main ()
{ Output:
int i=1; 1 2 3 4 5 6 7 8 9 10

clrscr();
do
{
printf(“%d”,i); i++;
} while(i<=10);
getch();
}
For loop:
C for loops is very similar to a while loops in that it continues to process a block of code until a
statement becomes false, and everything is defined in a single line. The for loop is also entry-
controlled loop.
Syntax:
for ( init; condition; increment )
{
statement(s);
}
Flowchart:

Example:
#include<stdio.h>
void main ()
{ Output:
int i; clrscr(); 1 2 3 4 5 6 7 8 9 10

for(i=1;i<=10;i++)
{
printf(“%d”,i); getch();
}
Part A
Q.no Questions CO PO
1. What is a loop in C? C116.1 1,2
What is the difference between entry-controlled and exit-
2. C116.1 1,3
controlled loops?
3. How does a while loop work in C? C116.1 1,3
4. What is the syntax of a for loop? C116.1 1,3
5. What is an infinite loop? Give an example. C116.1 1,3
Part B

Explain the different types of loops in C with syntax,


1. C116.1 1,2,3,5,11
flowcharts, and examples.
Compare while, do-while, and for loops with examples.
2. C116.1 1,3,5,11
Discuss their advantages and disadvantages.
Part C
Explain looping constructs in C with proper syntax,
1. examples, and flowcharts. Provide a program demonstrating C116.1 1,3,5,7,9,11,12
their real-world application.
PRE-PROCESSOR DIRECTIVES (C116.1, PO-1,2,3,4,5,6,7,9,11,12)
The C preprocessor is a micro processor that is used by compiler to transform your code before
compilation. It is called micro preprocessor because it allows us to add macros. Preprocessor directives
are executed before compilation.

All preprocessor directives starts with hash #symbol. Let's


see a list of preprocessor directives.
 #include
 #define

 #undef
 #ifdef
 #ifndef
 #if
 #else
 #elif
 #endif
 #error
 #pragma

s.no Preprocessor purposes syntax


directive
1 #include Used to paste code of given file into #include <filename>
current file. It is used include #include “filename”
system- defined and user-defined
header files.
If included file is not found, compiler
renders error.
2 #define Used to define constant or #define PI 3.14
microsubstitution. It can use any
basic data type.
3 #undef Used to undefine the constant or macro #undef PI
defined by #define.
4 #ifdef Checks if macro is defined by #define. If#ifdef MACRO
yes, it executes the code //code
otherwise #else code is executed, if #endi
present. f

5 #ifndef Checks if macro is defined by #define. If#ifndef MACRO


yes, it executes the code //code
otherwise #else code is executed, if #endi
present. f

6 #if Evaluates the expression or condition. #if expression


If condition is true, it //code
executes the code otherwise #elseif or #endi
#else or #endif code is executed f

7 #else Evaluates the expression or condition if #if expression


condition of #if is false. It can be //if code
used with #if, #elif, #ifdef and #else
#ifndef directives. //else code
#endif

8 #error Indicates error. The compiler gives fatal#error First include


error if #error directive is found then compile
and skips further compilation process.

9 #pragma Used to provide additional information #pragma token


to the compiler. The #pragma
directive is used
by the compiler to offer machine or
operating-system feature.

COMPILATION PROCESS:

C is a high level language and it needs a compiler to convert it into an executable code so that the
program can be run on our machine.
How do we compile and run a C program?
Below are the steps we use on an Ubuntu machine with gcc compiler.
 We first create a C program using an editor and save the file as filename.c
$ vi filename.c
The diagram on right shows a simple program to add two numbers.
compile it using below command.
$ gcc –Wall filename.c –o filename
The option -Wall enables all compiler’s warning messages. This option is recommended to
generate bettercode. The option -o is used to specify output file name. If we do not use this option, then
an output file with name a.out is generated.
After compilation executable is generated and we run the generated executable using below
command.
$ ./filename
What goes inside the compilation process?
Compiler converts a C program into an executable. There are four phases for a C program to
become an executable:
1. Pre-processing
2. Compilation
3. Assembly
4. Linking
By executing below command, We get the all intermediate files in the current directory along with the
executable.
$gcc –Wall –save-temps filename.c –o filename
The following screenshot shows all generated intermediate files. Let
us one by one see what these intermediate files contain
Pre-processing:
This is the first phase through which source code is passed. This phase include:
• Removal of Comments
• Expansion of Macros
• Expansion of the included files.
The preprocessed output is stored in the filename.i. Let’s see what’s inside
filename.i:using $vi filename.i
In the above output, source file is filled with lots and lots of info, but at the end our code is
preserved.
Analysis:
• printf contains now a + b rather than add(a, b) that’s because macros have expanded.
• Comments are stripped off.

• #include<stdio.h> is missing instead we see lots of code. So header files has been
expanded andincluded in our source file.
Compiling:
The next step is to compile filename.i and produce an; intermediate compiled output file
filename.s.
This file is in assembly level instructions. Let’s see through this file using $vi filename.s
Assembly:
In this phase the filename.s is taken as input and turned into filename.o by assembler.
This file contain machine level instructions. At this phase, only existing code is converted into
machine language, the function calls like printf() are not resolved. Let’s view this file using
$vi filename.o
Linking:
This is the final phase in which all the linking of function calls with their definitions
are done. Linkerknows where all these functions are implemented.
Linker does some extra work also, it adds some extra code to our program which is
required whenthe program starts and ends.
For example, there is a code which is required for setting up the environment like
passing commandline arguments. This task can be easily verified by using $size filename.o
and $size filename.
Through these commands, we know that how output file increases from an object file
to an executable file. This is because of the extra code that linker adds with our program

Part A
Q.no Questions CO PO
1. What is a preprocessor directive in C? C116.1 1,3
2. How does the #define directive work in C? C116.1 1,2
What is the difference between #include <filename> and
3. C116.1 1,3
#include "filename"?
4. What are the four phases of compilation in C? C116.1 1,3
5. What does the linker do in the compilation process? C116.1 1,3
Part B
Explain different types of preprocessor directives in C with
1. C116.1 1,2,3,5,11
syntax and examples.
Discuss the phases of the compilation process in C with
2. C116.1 1,3,5,11
suitable examples.
Part C
Explain the role of preprocessor directives and describe the C
1. compilation process with detailed examples and flow C116.1 1,3,5,7,9,11,12
diagrams.

You might also like