0% found this document useful (0 votes)
170 views129 pages

PSLUC Lab Manual Without Test Cases

This document is the lab manual for the Problem Solving Lab using C course offered at Gayatri Vidya Parishad College of Engineering during the 2019-2020 academic year. It was compiled and edited by several professors from the Computer Science and Information Technology departments. The manual contains programs assigned each week related to basic C concepts, operators, conditional statements, loops, functions, arrays, strings, pointers, structures, and files. The programs are intended to help students achieve the course outcomes of applying C concepts and demonstrating usage of various language features.
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)
170 views129 pages

PSLUC Lab Manual Without Test Cases

This document is the lab manual for the Problem Solving Lab using C course offered at Gayatri Vidya Parishad College of Engineering during the 2019-2020 academic year. It was compiled and edited by several professors from the Computer Science and Information Technology departments. The manual contains programs assigned each week related to basic C concepts, operators, conditional statements, loops, functions, arrays, strings, pointers, structures, and files. The programs are intended to help students achieve the course outcomes of applying C concepts and demonstrating usage of various language features.
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/ 129

Gayatri Vidya Parishad

College of Engineering
(Autonomous)

Problem Solving Lab


Using ‘C’
(19CT1102)
LAB MANUAL
2019-2020

COMPILED & EDITED BY


DR.D.N.D HARINI, ASSOCIATE PROFESSOR, CSE DEPT.
MR. D ARUN KUMAR, ASSISTANT PROFESSOR, IT DEPT.
MR. N DURGA PRASAD, ASSISTANT PROFESSOR, CSE DEPT.
MRS. E SIRISHA, ASSISTANT PROFESSOR, CSE DEPT.
CONTRIBUTED BY

WEEK-1 Mr. D Naga Tej, Assistant Professor, IT Dept

Mr. P Praveen Kumar Assistant Professor, IT Dept


WEEK-2
Mrs. A S Lalitha, Assistant Professor, IT Dept

Ms. Lateefa Shaik, Assistant Professor, CSE Dept


WEEK-3
Ms. P Malleswari, Assistant Professor, CSE Dept

Mrs. P Sravya, Assistant Professor, CSE Dept


WEEK-4
Mrs. K Sudha, Assistant Professor, CSE Dept

Mrs. G V Hindumati, Assistant Professor, CSE Dept


WEEK-5
Mrs. V Tulasi, Assistant Professor, CSE Dept

Mrs. G Vani, Assistant Professor, CSE Dept


WEEK-6
Ms. K Havya, Assistant Professor, CSE Dept

Mr. M S N Murthy, Assistant Professor, CSE Dept


WEEK-7
Mrs. E Sirisha, Assistant Professor, CSE Dept

Mrs. P Sai Deepika, Assistant Professor, CSE Dept


WEEK-8
Mrs. K Beulah, Assistant Professor, CSE Dept

Mrs. V L Vinya, Assistant Professor, CSE Dept


WEEK-9
Mrs. R S Bhargavi, Assistant Professor, CSE Dept

Ms. G Naga Kalyani, Assistant Professor, IT Dept


WEEK-10
Ms. B Pranalini, Assistant Professor, IT Dept

Mr. Praveen Dasari, Assistant Professor, CSE Dept


WEEK-11
Mrs. Geetanjali Naik, Assistant Professor, CSE Dept

Mr. P Rahul, Assistant Professor, CSE Dept


WEEK-12
Mr. Ch Kondaiah, Assistant Professor, CSE Dept
ACKNOWLEDGEMENTS
Our Special thanks to Dr. A B K Rao, Principal, Dr. K B Madhuri, HOD IT Dept.,
Dr. P. Krishna Subbarao, HOD CSE Dept., Dr. M Phani Krishna Kishore, Professor,
IT Dept., Mr. N V Brahmaji Rao, Associate Professor, Mr. P Sanoop Kumar,
Assistant Professor, CSE Dept., for their valuable suggestions during the
preparation of this manual
PROBLEM SOLVING LAB USING C

Course Code: 19CT1102 L T P C


0 0 3 1.5
Course Outcomes:
At the end of the Course the student shall be able to:
CO1: Apply the concepts of variables, data types, operators and expressions.
CO2: Demonstrate the usage of Conditional and Unconditional statements.
CO3: Demonstrate the usage of functions and related functions with respect to arrays and
strings.
CO4: Implement the concept of pointers and structures.
CO5: Demonstrate the usage of files and Command Line Arguments.

List of Programs:
Week 1 (Basic Programs)
1. C program to display hello world message.
2. C program to scan all data type variables as input and print it as output.
3. C program to perform arithmetic operations like +,-,*,/,% on two input variables.
4. C program to perform temperature conversions from Centigrade to Fahrenheit and
vice versa.
Week 2 (Programs on Operators)
1. C program to scan an input and perform pre and post increment operation on it and
display the result.
2. C program to perform all bit wise operations.
3. C program to extract the last two digits of a given integer n, where the number of
digits should be greater than 2.
4. C program to display the greatest of three numbers using conditional operator.
5. C program to swap two numbers without using third variable.
Week 3 (Programs on Conditional Statements)
1. C program to check whether a given input integer is in between two values x and y.
2. C program to check whether a given character is a vowel or a consonant or a digit or
a special symbol.
3. C program to display the nature and roots of a quadratic equation.
4. C program to perform arithmetic operations using switch statement.
5. C program to convert upper case character to lower case and vice versa.
Week 4 (Programs on Loop Statements)
1. C program to print odd numbers between specified ranges.
2. C program to display the factors of a given number and check whether it is a prime
or not.
3. C program to display the sum of individual digits of a given integer raised to the
power of n. Also check whether the given integer is Armstrong or not.
4. C Program to demonstrate the usage of unconditional control statements.
5. C program to display the following pattern.

54321
4321
321
21
1
Week 5 (Programs on Functions)
1. C program to demonstrate the various categories of functions with respect to return
type and number of arguments.
2. C program to find the LCM of two numbers using functions.
3. Create a header file which contains the following prototype:
i. int factorial ( int ) ; // non-recursive function
ii. int factorial_rec(int); //Recursive function
iii. int prime ( int ) ;
Use the above functions in a C program by including the above header file.
4. C program to display Pascal’s triangle using functions.
Week 6 (Programs on Arrays)
1. C program to read n integer values into an array and display them
2. C program to count and display the number of positive, negative, even and odd
numbers in a given array of integers and also display their sum.
3. C program to find the smallest and largest numbers in an array of integers.
4. C program to perform addition, multiplication, transpose of given matrices using
functions.
5. C program to check whether a given integer exists in a list of numbers and print its
index value if it is present, otherwise print “No”.
Week 7 (Programs on Strings)
1. C program to convert upper case character to lower case and vice versa in a given
string.
2. C program to delete all vowels in a given string and display the remaining string.
3. C program to check whether a given string is palindrome or not.
4. C program that reads two integers as strings and display their sum.
Week 8 (Programs on Strings)
1. C program to demonstrate the usage of at least 10 predefined string handling
functions.
2. C program that implements the following user defined string handling functions
i. To find the length of the given string
ii. To copy the contents of one string to another
iii. To reverse the contents of a string
iv. To compare two strings
v. To concatenate two strings
Week 9 (Programs on Pointers and Dynamic Memory Allocation)
1. C program to demonstrate the usage of pointers.
2. C program that uses dynamic memory allocation functions to add n elements and
display their average.
3. C program that performs pointer arithmetic.
4. C program that implements call by reference.
Week 10 (Programs on Pointers)
1. C program to demonstrate the following
i. Pointers to Pointers
ii. Array of Pointers
iii. Pointer to Array
iv. Pointers to Functions
Week 11 (Programs on Structures)
1. C program to access and display the members of the structure.
2. C program that demonstrates different ways to access the structure elements using
pointers.
Week 12 (Programs on Files)
1. C program to read the contents of a file and display on to output screen.
2. C program to copy the contents of one file to another.
3. C program to count and display the number of characters, words and lines in a file.
4. C program to print last n characters of a file by reading file name and n value from
command line.
Vision

• To evolve into and sustain as a Centre of Excellence in Technological Education and


Research with a holistic approach.

Mission
• To produce high quality engineering graduates with the requisite theoretical and practical
knowledge and social awareness to be able to contribute effectively to the progress of the
society through their chosen field of endeavor.
• To undertake Research & Development, and extension activities in the fields of Science and
Engineering in areas of relevance for immediate application as well as for strengthening or
establishing fundamental knowledge.

Programme Educational Objectives (PEO’s)


PEO-1: The Graduates will be able to design and develop solutions for real life problems using
modern engineering tools.

PEO-2: Have extensive and effective practical skills in Computer Science and Engineering and the
ability to analyze and interpret experimental results in frontier areas of Computer Science and
Engineering and appetite for higher learning and research in multidisciplinary areas.

PEO-3: Engage in professional development with effective communication, ethical and team work
and adopt current trends through lifelong learning.

Programme Specific Outcomes (PSO’s)

PSO1: Design, develop and test system software and application software for distributed and
centralized computing environments to varying domain and platforms.

PSO2: Understand the working of new hardware architectures and components and design solutions
for real time problems.

PSO3: Model the computer-based systems and design algorithms that explores understanding of the
tradeoffs involved in design choices.
Program Outcomes (PO’s)

PO1: Graduates will be able to apply the knowledge of mathematics, science, engineering
fundamentals and principles of Computer Science & Engineering to solve complex problems in
different domains

PO2: Graduates can identify, formulate, study contemporary domain literature and analyse real life
problems and make effective conclusions using the basic principles of science and engineering

PO3: Graduates will be in a position to design solutions for Engineering problems requiring in depth
knowledge of Computer Science and design system components and processes as per standards with
emphasis on privacy, security, public health and safety.

PO4: Graduates will be able to conduct experiments, perform analysis and interpret data as per the
prevailing research methods and to provide valid conclusions.

PO5: Graduates will be able to select and apply appropriate techniques and use modern software
design and development tools. They will be able to predict and model complex engineering activities
with the awareness of the practical limitations.

PO6: Graduates will be able to carry out their professional practice in Computer Science &
Engineering by appropriately considering and weighing the issues related to society and culture and
the consequent responsibilities.

PO7: Graduates would understand the impact of the professional engineering solutions on
environmental safety and legal issuesPO8: Graduates will transform into responsible citizens by
adhering to professional ethics.

PO8: Graduates will transform into responsible citizens by adhering to professional ethics.

PO9: Graduates will be able to function effectively in a large team of multidisciplinary streams
consisting of persons of diverse cultures without forgetting the significance of each individual’s
contribution.

PO10: Graduates will be able to communicate effectively about complex engineering activities with
the engineering community as well as the general society and will be able to prepare reports.

PO11: Graduates will be able to demonstrate knowledge and understanding of the engineering and
management principles and apply the same while managing projects in multidisciplinary
environments.

PO12: Graduates will engage themselves in self and life-long learning in the context of rapid
technological changes happening in Computer Science and other domains.
Course Outcomes

At the end of the Course, the Student will be able to:

CO 1: Apply the concepts of variables, data types, operators and expressions.


CO 2: Demonstrate the usage of Conditional and Unconditional statements.

CO 3: Demonstrate the usage of functions and related functions with respect to arrays and strings.

CO 4: Implement the concept of pointers and structures.

CO 5: Demonstrate the usage of files and Command Line Arguments.

Course Outcome Versus Program Outcomes

CO/PO PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12
CO1 S M M M
CO2 S S M M
CO3 S M M M
CO4 S M
CO5 S M
S- Strongly Correlated M-Moderately Correlated Blank- No Correlation
CONTINUOUS EVALUATION PROCEDURE

1. Internal Evaluation is done for 40 marks

o 20 marks for day to day work

o 20 marks from internal examination at the end of each cycle

(Average marks shall be considered in each component)

2. End Semester (External) Evaluation is done for 60 marks.

3. Criteria to pass laboratory examination

o Total marks 100 (40 marks internal evaluation+60 marks end


semester evaluation)

o 35% (21 marks) from end semester lab examination

o 40% (40 marks) aggregate from internal and end semester


examinations put together.
GENERAL LABORATORY INSTRUCTIONS

• Students are advised to come to the laboratory at least 5 minutes before (to the starting
time), those who come after 5 minutes will not be allowed into the lab.
• Plan your task properly much before to the commencement, come prepared to the lab
with the synopsis / program / experiment details.
• Student should enter the laboratory with:
i) Laboratory observation notes with all the details (Problem statement, Aim,
Algorithm, Procedure, Program, Expected Output, etc.,) filled in for the lab session.
ii) Laboratory Record updated up to the last session experiments and other utensils (if
any) needed in the lab.
iii)Proper Dress code and Identity card.
• Sign in the laboratory login register, write the TIME-IN, and occupy the computer
system allotted to you by the faculty.
• Execute your task in the laboratory and record the results / output in the lab observation
note book and get certified by the concerned faculty.
• All the students should be polite and cooperative with the laboratory staff, must maintain
the discipline and decency in the laboratory.
• Computer labs are established with sophisticated and high-end branded systems, which
should be utilized properly.
• Students / Faculty must keep their mobile phones in SWITCHED OFF mode during the
lab sessions. Misuse of the equipment, misbehaviors with the staff and systems etc., will
attract severe punishment.
• Students must take the permission of the faculty in case of any urgency to go out; if
anybody found loitering outside the lab / class without permission during working hours
will be treated seriously and punished appropriately.
• Students should LOG OFF/ SHUT DOWN the computer system properly before he/she
leaves the lab after completing the task (experiment) in all aspects. He/she must ensure
the system / seat is kept properly.
Introduction to Visual Studio Code Editor
STEPS TO CREATE A WORKSPACE IN VISUAL STUDIO CODE

• Create a New Folder(with your roll number or name) on your computer.

• Open Visual Studio Code either from start button or by double clicking its icon on
desktop
or

• Click on File menu of Visual Studio Code and select "add folder to workspace"
• Select the Folder created earlier (step1)

• Now click on “add” button to add it to the workspace

• Now the folder you have added will appear in the workspace.
• Now right click added folder from workspace and select new file

• Give a new file name with an extension of .c (for example sample.c) in the blank text box
and click enter
• Now an empty file with sample.c will be opened on the right side of the workspace.

• Type the program in the space provided.

• Save the program by pressing ctrl+s from the keyboard.

Steps to Execute a C Program:


• Open Terminal menu and click on New Terminal.
• Now a command prompt will open with your workspace directory at the bottom of the
editor.

• Type gcc filename.c to execute the program


• Type .\a to run your executable file and to check the output.
STRUCTURE OF A C PROGRAM
C Program structure is divided in to several sections.

Documentation Section
Link Section
Global Declaration Section
main()
{
Local Declarations
Program statements and Expressions
}
User Defined Functions

For Example:

#include <stdio.h>
int main()
{
/* my first program in C */
printf("Hello, World! \n");
return 0;
}

Documentations (Documentation Section)

The Documentation Section consists of a set of comment lines giving the name of the program and
other details. The Link Section provides instructions to the compiler to link functions from the system
library.

Preprocessor Statements (Link Section)

C Preprocessor directives: Before a C program is compiled in a compiler, source code is processed by


aprogram called preprocessor. This process is calledpreprocessing. Commands used in preprocessor are
called preprocessor directives and they begin with “#” symbol.

Global Declarations (Definition Section)

Global variables hold their values throughout the lifetime of your program and they can be accessed
inside any of the functions defined for the program. A global variable can be accessed by any function.
That is, a global variable is available for use throughout your entire program after its declaration.

The main() function

In C, the "main" function is treated the same as everyfunction, it has a return type (and in some cases
accepts inputs via parameters). The only difference is that the main function is "called" by the operating
system when the user runs the program.

Local Declarations

A scope in any programming is a region of the program where a defined variable can have its existence
and beyond that variable it cannot be accessed. There are three places where variables can be declared
in C programming language − Inside a function or a block which is called local variables.

Program Statements & Expressions


An expression statement consists of an optional expression followed by a semicolon (;). If the
expression is present, the statement may have a value. If no expression is present, the statement is often
called the null statement.

The printf function calls are expressions, so statements such as printf ("Hello World!\n"); are expression
statements.

User Defined Functions

A function is a block of code that performs a specific task. Callows you to define functions according
to your need. These functions are known as user-defined functions.
Week-1
Program-1.1: C program to display hello world message

Aim:
The main objective of this program is to make familiar with printf() function and to print a text
on a console (monitor) in multiple ways using printf(). You need to use the below syntax to
write output on console.

Pre-Requisite:

printf() function:
printf() is a predefined function in "stdio.h" header file. stdio stands for Standard Input
Output. Using printf(), we can print data or a user defined message onto the standard output
console that is a monitor.

Syntax:
printf(“user defined message”); // example: printf(“Welcome to GVPCE”);
Commonly used escape sequences in printf are:
• \n (Newline)
• \t (Tab Space)
• \” (Double Quotes)
• \f (New Page)
• \b (Backspace)
• \r (Carriage Return)

Example:
Printf(“Hello\nWorld”);
Output:
Hello
World
Test Cases:
This program requires you to print “Hello World!!!” text in multiple ways by using above
specified escape sequences.

Input Format:
You do not need to read any input in this challenge.
Expected Output Format:
The argument for printf() must be Hello World!!!”. The program has to be tested for the escape
sequences that include new line (\n), tab space (\t), back space (\b), carriage return (\r), Hello
World!!! with in double quotes (\”).

S.No. Input Expected Output Actual Output Remarks


Program-1.2: C program to scan all data type variables as input
and print it as output.
Aim:
The main objective of this program to make familiar with scanf() function and all the primitive
data types in C language.

Pre-Requisites:
scanf() function:
The scanf() function allows you to accept input (character, string, numeric data) from
standard input console that is a key board.
Syntax:
scanf(“format specifiers”,&var1,&var2……); // example: scanf(“%d %f”,&a,&b);
Here the format specifier tells the compiler that it is storing a value into the variable which is
of a particular data type. The following are the list of format specifiers used to read values for
the variables of primitive data types.
Data Type Key word Format Specifier
integer int %d
float float %f
character char %c

& used in the scanf function is an operator, called address operator, which is used to store the
value read from keyboard. It is used to access the memory location of the variable.
Note: &var1 in above syntax denotes the memory address of variable var1.

Datatypes in C:
Each variable in C has an associated data type. Each data type requires different amounts of
memory and has some specific operations which can be performed over it.
Different data types also have different ranges upto which they can store numbers. These ranges
may vary from compiler to compiler. Below is list of ranges along with the memory
requirement and format specifiers on 32 bit gcc compiler.
In general, the range of a particular data type for signed and unsigned variables can be defined
as follows:
For Unsigned variables, the range is 0 to 2n-1
For Signed variables, the range is -2n-1 to 2n-1-1
Note: To know the size of a variable of a particular data type, use sizeof() function.

MEMORY FORMAT
DATA TYPE RANGE
(BYTES) SPECIFIER

short int 2 -32,768 to 32,767 %hd


MEMORY FORMAT
DATA TYPE RANGE
(BYTES) SPECIFIER

unsigned short int 2 0 to 65,535 %hu

unsigned int 4 0 to 4,294,967,295 %u

int 4 -2,147,483,648 to 2,147,483,647 %d

long int 4 -2,147,483,648 to 2,147,483,647 %ld

unsigned long int 4 0 to 4,294,967,295 %lu

long long int 8 -(2^63) to (2^63)-1 %lld

unsigned long long 0 to


8 %llu
int 18,446,744,073,709,551,615

signed char 1 -128 to 127 %c

unsigned char 1 0 to 255 %c

float 4 1.2E-38 to 3.4E+38 %f

double 8 2.3E-308 to 1.7E+308 %lf

long double 12 -(2^95) to (2^95)-1 %Lf

Variable:
A variable in C language is a name given to a storage area that our programs can manipulate.
Each variable in C has a specific data type. Every variable declaration in a c program will end
with a semi colon.
Syntax to declare variable/ variables:
To declare a variable of a single data type, use the following syntax.
Data type variablename; // Example: int num1; or float total; or char ch;
To declare multiple variables of a single data type, use the following syntax.
Data type variablename1, variablename2,……,variablenameN; // Example: int num1, num2,
num3; or float total, average;
This program requires you to read all data type variables using scanf function and print them
onto the output screen using printf function
Formatted printf() syntax:
printf(“Format Specifiers”, List of variables);

Formats for various outputs

SNO FORMAT EXPLANATION


1 %wd w is width in integer and d is conversion specification
w is width in integer, c specifies number of digits after decimal
2 %w.cf
point and f specifies conversion specification
w is width for total characters, c is used for displaying leading
3 %w.cs
blanks and s specifies conversion specification

Test Cases:
Input Format:

Provide the input using keyboard in a sequence of character(X), integer(12) and real value(12.34)
in a Single line or Multiple line.
Expected Output Format:
First line: The char value read is X
Second line: The integer value read is 12 // Six Spaces before integer value without
using \t
Third line: The float value read is 12.34

S.No. Input Expected Output Actual Output Remarks


Program-1.3: C program to perform arithmetic operations like +,-
,*,/,% on two input variables.

Aim:
The main objective of this program to make familiar with all arithmetic operators in C
language.

Pre-Requisites:
C Arithmetic Operators
An arithmetic operator performs mathematical operations such as addition, subtraction,
multiplication, division and modulus division on numerical values.

The following table shows all the arithmetic operators supported by the C language. Assume
variable A holds 7 and variable B holds 2 then

Operator Description Example

+: Addition Adds two operands. A+B=9

−: Subtraction Subtracts second operand from the first. A−B=5

*: Multiplies both operands. A * B = 14


Multiplication

/: Division Divides numerator by de-numerator. A/B=3

%: Modulus Modulus Operator gives remainder after an integer A%B=1


division.

fflush() function
fflush() is a predefined function in "stdio.h" header file. It is typically used for output stream
only. Its purpose is to clear (or flush) the output buffer and move the buffered data to console
(in case of stdout) and clears (or flush) the input buffer (in case of stdin)

Syntax:
fflush (stdin); // on execution the input buffer will be cleared
fflush (stdout); // on execution the output buffer will be cleared
Test Cases:
Input Format:

Provide the input using keyboard in a sequence of two integers or two real values or two
characters in a Single line or multiple lines.
Example:
12 3
Expected Output Format:
The addition is 15
The difference is 9
The product is 36
The quotient is 4
The remainder is 0

S.No. Input Expected Output Actual Output Remarks


Program-1.4: C program to perform temperature conversions
from Centigrade to Fahrenheit and vice versa.

Aim:
The main objective of this program to make familiar with all expression evaluation and type
casting in C language.

Pre-Requisites:
Expression:
An expression is a sequence of operands and operators that reduces to a single value. For
example, the expression, 10+5 reduces to the value of 15.
Syntax:
Variable=expression
All variables used in the expression must be declared and assigned values before evaluation is
attempted. Examples of expressions are:
x= a + b * c;
x= (a + b) * c;
Expressions are evaluated based on operator precedence and associativity rules when an
expression contains more than one operator.
x=5+3*2; // output: x=11
x= (5+3)*2; // output: x=16

Type casting:
A type cast is basically a conversion from one type to another. There are two types of type
conversion
1. Implicit Type conversion:
Also known as ‘automatic type conversion’. Done by the compiler on its own. Generally
takes place when in an expression more than one data type is present. In such condition
type conversion (type promotion) takes place to avoid lose of data.
ex: int x;
float y;
// x is implicitly converted to float
float z = x + 1.0;
2. Explicit Type conversion:
This process is also called type casting and it is user defined. Here the user can type
cast the result to make it of a particular data type.
The syntax in C:
(Type) expression
ex: double x = 1.2;
// Explicit conversion from double to int
int sum = (int) x + 1;

Problem Analysis:
This problem can be solved by using below formula.
Formula for temperature conversion is
(C × 9/5) + 32 = F

Test Cases:
Input Format:

Provide the input using keyboard in a sequence of two values (oC and oF) in a Single
line or Multiple line.
Ex: 100oC
100oF
Expected Output Format:
The temperature in Fahrenheit is 212.000000 F
The temperature in Celsius is 37.777780 C

S.No. Input Expected Output Actual Remarks


Output
Week-2
Program-2.1: C program to scan an input and perform pre and
post increment operation on it and display the result.
Aim:
The main objective of this program is to make familiar with post/pre increment and post/pre
decrement operators.

Pre-Requisite:
Increment operators (++) are used to increase the value of the variable by one and decrement
operators (--) are used to decrease the value of the variable by one in C programs.
Syntax:
Increment operator: ++var_name; (or) var_name++;
Decrement operator: – -var_name; (or) var_name – -;
Example:
Increment operator: ++ i; i ++;
Decrement operator: – – i; i – –;

Difference between Pre/Post Increment & Decrement Operators in C:


Operator Operator/Description

value of i is incremented before


Pre increment operator (++i) assigning it to the variable i

value of i is incremented after


Post increment operator (i++) assigning it to the variable i

value of i is decremented before


Pre decrement operator ( - - i) assigning it to the variable i

value of i is decremented after


Post decrement operator (i- - ) assigning it to variable i

Pre-increment operator:
A pre-increment operator is used to increment the value of a variable before using it in an
expression. In the Pre-Increment, value is first incremented and then used inside the
expression.
Syntax:
var1=++var2;
Post-increment operator:
A post-increment operator is used to increment the value of variable after executing
expression completely in which post increment is used. In the Post-Increment, value is first
used in an expression and then incremented.
Syntax:
var1=var2++;

Pre Increment Post Increment Pre Decrement Post Decrement


a=10; a=10; a=10; a=10;
x=++a; x=a++; x=--a; x=a--;
output: output: output: output:
a=11 a=11 a=9 a=9
x=11 x=10 x=9 x=10

Test Cases:
Input Format:

Provide two values (integer/floating point) as input in single line / multi line using keyboard.
Example:
1 2

Expected Output Format:

First line: After Post Increment of 1st Value 1.000000


Second line: After Pre Increment of 2nd value 3.000000

Note: Apply Post increment on 1st value and Pre Increment on 2nd value

S.No. Input Expected Output Actual Output Remarks


Program-2.2: C program to perform all bit wise operations.
Aim:
The main objective of this program is to make familiar with bitwise operators.

Pre-Requisites:
Bitwise Operators in C:
In C, the following 6 operators are bitwise operators (work at bit-level)
• & (bitwise AND): It takes two numbers as operands and does AND on every bit of
two numbers. The result of AND is 1 only if both bits are 1.
• | (bitwise OR): It takes two numbers as operands and does OR on every bit of two
numbers. The result of OR is 1 if any of the two bits is 1.
• ^ (bitwise XOR): It takes two numbers as operands and does XOR on every bit of
two numbers. The result of XOR is 1 if the two bits are different.
• << (left shift): It takes two numbers, left shifts the bits of the first operand, the second
operand decides the number of places to shift.
• >> (right shift): It takes two numbers, right shifts the bits of the first operand, the
second operand decides the number of places to shift.
• ~ (bitwise NOT): It takes one number and inverts all bits of it
Bitwise operator works on bits and performs bit-by-bit operation. The truth tables for &, |, ^
and ~ is as follows

p q p&q p|q p^q ~p

0 0 0 0 0 1

0 1 0 1 1 1

1 0 0 1 1 0

1 1 1 1 0 0

Important facts about bitwise operators.


• The left shift and right shift operators should not be used for negative numbers
• The bitwise operators should not be used in place of logical operators.
• The left-shift and right-shift operators are equivalent to multiplication and division by
2 respectively.
• The & operator can be used to quickly check if a number is odd or even
• The ~ operator should be used carefully
The following table lists the Bitwise operators supported by C. Assume variable 'A' holds 5
(0000 0101) and variable 'B' holds 6 (0000 0110), then
Operator Description Example

Binary AND Operator copies a bit to the


& (A & B) = 4, i.e., 0000 0100
result if it exists in both operands.

Binary OR Operator copies a bit if it exists in


| (A | B) = 7, i.e., 0000 0111
either operand.

Binary XOR Operator copies the bit if it is


^ (A ^ B) = 3, i.e., 0000 0011
set in one operand but not both.

Binary One's Complement Operator is unary


~ (~A ) = -6, i.e., 1000 0110
and has the effect of 'flipping' bits.

Binary Left Shift Operator. The left operands


<< value is moved left by the number of bits A << 1 = 10 i.e., 0000 1010
specified by the right operand.

Binary Right Shift Operator. The left


operands value is moved right by the
>> A >> 1 = 2 i.e., 0000 0010
number of bits specified by the right
operand.

Sample Code to perform bitwise | (OR) operation:

#include <stdio.h>
int main() {
unsigned int a = 5; /* 5 = 0000 0101 */
unsigned int b = 6; /* 6 = 0000 0110 */
int c = 0;
c = a | b; /* 7 = 0000 0111 */
printf("Value of c is %d\n", c );
return 0;
}

Output:
Value of c is 7

Test Cases:
Input Format:

Provide two unsigned integer values (as left shift and right shift operators cannot be applied on
negative numbers) as input using keyboard in a Single line or multiple line.
Example:
34
Note: Apply Left Shift and Right Shift on First Number by 1 position

Expected Output Format:


The result of bitwise AND is 0

The result of bitwise OR is 7

The result of bitwise XOR is 7

The result of bitwise NOT for num1 is -4

The result of LEFTSHIFT of num1 by 1 is 6

The result of RIGHTSHIFT of num1 by 1 is 1

S.No. Input Expected Output Actual Output Remarks


Program-2.3: C program to extract the last two digits of a given
integer n, where the number of digits should be greater than 2.

Aim:
The main objective of this program to make familiar with the application of arithmetic
operators like / (Division) and % (Modulo Division).

Pre-Requisites:
C Arithmetic Operators
An arithmetic operator performs mathematical operations such as addition, subtraction,
multiplication, division and modulus division on numerical values.

The following table shows all the arithmetic operators supported by the C language. Assume
variable A holds 7 and variable B holds 2 then

Operator Description Example

+: Addition Adds two operands. A+B=9

−: Subtraction Subtracts second operand from the first. A−B=5

*: Multiplication Multiplies both operands. A * B = 14

/: Division Divides numerator by de-numerator. A/B=3

%: Modulus Modulus Operator gives remainder after an A%B=1


integer division.

NOTE: When we are using division (/) operator the result will completely depend upon the
data type it belongs to.

For Example: Consider the below two scenarios.

int a,b; int a,b;


int c; float c;
a=7; a=7;
b=3; b=3;
c=a/b; c=(float)a/b;
d=a%b; d=a%b;
output: output:
c=2 // Quotient (integral part) c=2.3333 // Quotient
d=1 // Remainder d=1 //Remainder
If you want the correct result then change the data type to float. Don’t get confused.

If you notice the result in above table, we got two different results for the same calculation.
Because for the first result, both a and b are integers and the output is also an integer
(integerdiv). So the compiler neglects the term after the decimal point and shows answer 2
instead of 2.3333 and a % b is 1 because the remainder is 1.

Next, we changed the output data type to float (floatdiv), and also converted the result to float
to get our desired result.

NOTE: Modulus division (%) operator cannot be applied to floating point numbers.

Test Cases:
Input Format:

Provide an integer value with minimum 2 digits as input using keyboard

Example:
123

Expected Output Format:


The last two digits of the given integer are 23

S.No. Input Expected Output Actual Output Remarks


Program-2.4: C program to display the greatest of three numbers
using conditional operator.

Aim:
The main objective of this program to make familiar with the usage of conditional operator.

Pre-Requisites:
Conditional Operator
1. It is also called Ternary Operator.
2. It is represented using ? :
3. Ternary Operator takes 3 arguments
Syntax:
expression1 ? expression2 : expression3;
Where
• expression1 is Condition
• expression2 is executed if expression1 is True
• expression3 is executed if expression1 is False

Meaning of Syntax:

• expression1 is nothing but Boolean Condition i.e. it results in either TRUE or FALSE
• If result of expression1 is TRUE then expression2 is Executed
• expression1 is said to be TRUE if its result is NON-ZERO
• If result of expression1 is FALSE then expression3 is Executed
• expression1 is said to be FALSE if its result is ZERO.
Sample Code Snippet:
Consider the below scenario to check whether given number is Even or Odd using
conditional operator

(num%2==0)?printf(“Even”):printf(“Odd”);

Test Cases:
Input Format:

Provide the input using keyboard in a sequence of three values (integer/float) in a Single line
or multiple lines.

Ex: 12.5
11
9.5
Expected Output Format:
The greatest of the three numbers is 12.500000

S.No. Input Expected Output Actual Remarks


Output
Program-2.5: C program to swap two numbers without using
third variable.
Aim:
The main objective of this program to make familiar with interchanging values of two
variables without using temporary variable.

Pre-Requisites:
To solve this problem, you should have the knowledge of following C programming topics:
• C Data Types
• C Programming Operators
• C Input Output (I/O)

Problem Analysis:
Method1 (Using Arithmetic Operators):
The idea is to get sum in one of the two given numbers. The numbers can then be swapped
using the sum and subtraction from sum.

Method 2 (Using Bitwise XOR)


The bitwise XOR operator can be used to swap two variables. The XOR of two numbers x
and y returns a number which has all the bits as 1 wherever bits of x and y differ. For
example XOR of 10 (In Binary 1010) and 5 (In Binary 0101) is 1111 and XOR of 7 (0111)
and 5 (0101) is (0010).

Problems with above methods


1) Both Arithmetic solutions may cause arithmetic overflow. If x and y are too large, addition
may go out of integer range.

Test Cases:
Input Format:

Provide the input using keyboard in a sequence of two values (char/integer/float) in a


Single line or multiple lines.
Ex: 12
13
Expected Output Format:
The values before swapping are 12 13
The values after swapping are 13 12

S.No. Input Expected Output Actual Remarks


Output
Week-3
Pre-Requisite:
To solve Week 3 problems, you should have the knowledge of Conditional Statements or
Decision making statements.

Conditional statements or Decision making statements:


Introduction:
Decision making or branching statements are used to select one path based on the result of
the evaluated expression. It is also called as control statements because it controls the flow of
execution of a program. Conditional Statements are the statements which execute a statement
or a block of statements once based on the condition. The conditions in the conditional
statements are evaluated to Boolean values i.e. True or False/ non zero value or zero value.
The Conditional statements in C are
• Simple if Statement
• if- else Statement
• Nested if Statement
• Nested if-else Statement
• Switch Statement

Simple if Statement
A simple if statement will have a condition or an expression preceded by the keyword if. It
has the following syntax:

Syntax:

if(expression)
{
statement; // block of statements
}
In the above syntax, expression evaluates to either true (non-zero value) or false (zero value).
If the expression is evaluated to true or nonzero value the statement or block of statements
followed by if gets executed. The statements inside the block may be a single statement or a
block of statements. This statement will not execute any block if the expression is evaluated
to false or zero.

Example:

int number;
if(number % 2 = = 0)
{
printf(“Given number is an even number”);
}
If number to input is 4, then “Given number is an even number” is displayed as output.
if-else Statement
An if- else statement will have a condition or an expression preceded by the keyword if. It
has the following syntax:

Syntax:

if(expression)
{
statement; // block of statements
}
else
{
Statement; //block of statements
}

In the above syntax, expression evaluates to either true (non-zero value) or false (zero value).
If the expression is evaluated to true or nonzero value the statement or statements inside the
block of if gets executed. If the expression is evaluated to false or zero, the statement or block
of statements inside the block of else executed. The statements inside the block may be a
single statement or a block of statements. This statement will not execute any block if the
expression is evaluated to false or zero.

Example:

int number;
if(number % 2 = = 0)
{
printf(“Given number is an even number”);
}
else
{
printf(“Given number is an odd number”);
}

If number to input is 4, then “Given number is an even number” is displayed as output.

If number to input is 5, then “Given number is an odd number” is displayed as output.


Nested if- else statement
When a series of decision is required, nested if-else is used. Nesting means using one if-else
construct within another one. It is also called a multi-way selection statement. When a series
of the decisions are involved in a statement, we use if else statement in nested form.

Syntax:

if( expression )
{
if( expression1 )
{
statement-block1;
}
else
{
statement-block 2;
}
}
else
{
statement-block 3;
}

Example

int a,b,c;
if(a>b)
{
if(a>c)
{
printf("%d is big",a);
}
else
{
printf("%d is big",c);
}
}
else
{
if(b>c)
{
printf("%d is big",b);
}
else
{
printf("%d is big",c);
}
}
Output:
If the input is 1 2 3, the output is 3 is big
If the input is 2 5 1, the output is 5 is big

Nested Else-if statements


Nested else-if is used when multipath decisions are required.
The general syntax of how else-if ladders are constructed in 'C' programming is as follows:

Syntax:
if (test - expression 1) {
statement1;
} else if (test - expression 2) {
Statement2;
} else if (test - expression 3) {
Statement3;
} else if (test - expression n) {
Statement n;
} else {
default;
}
Statement x;

This type of structure is known as the else-if ladder. This chain generally looks like a ladder
hence it is also called as an else-if ladder. The test-expressions are evaluated from top to
bottom. Whenever a true test-expression if found, statement associated with it is executed.
When all the n test-expressions becomes false, then the default else statement is executed.

Example:
int marks=83;
if(marks>75){
printf("First class");
}
else if(marks>65){
printf("Second class");
}
else if(marks>55){
printf("Third class");
}
else{
printf("Fourth class");
}
Switch Statement
A switch statement tests the value of a variable (integer or character) and compares it with
multiple cases. Once the case match is found, a block of statements associated with that
particular case is executed.
Each case in a block of a switch has a different name/number which is referred to as an
identifier. The value provided by the user is compared with all the cases inside the switch
block until the match is found.
If a case match is found, then the default statement is executed, and the control goes out of
the switch block.

A general syntax of how switch-case is implemented in a 'C' program is as follows:


Syntax:
switch( expression )
{
case value-1:
Block of statements;
break;
case value-2:
Block of statements;
break;
case value-n:
Block of statements;
break;
default:
Default Block of statements;
break;
}
Statement-x;

• The expression can be integer expression or a character expression.


• Value-1, 2, n are case labels which are used to identify each case individually.
Remember that case labels should not be same as it may create a problem while
executing a program. Suppose we have two cases with the same label as '1'. Then
while executing the program, the case that appears first will be executed even though
you want the program to execute a second case. This creates problems in the program
and does not provide the desired output.
• Case labels always end with a colon ( : ). Each of these cases is associated with a
block.
• A block is nothing but multiple statements which are grouped for a particular case.
• Whenever the switch is executed, the value of test-expression is compared with all the
cases which we have defined inside the switch. Suppose the test expression contains
value 4. This value is compared with all the cases until case whose label four is found
in the program. As soon as a case is found the block of statements associated with that
particular case is executed and control goes out of the switch.
• The break keyword in each case indicates the end of a particular case. If we do not put
the break in each case then even though the specific case is executed, the switch will
continue to execute all the cases until the end is reached. This should not happen;
hence we always have to put break keyword in each case. Break will terminate the
case once it is executed and the control will fall out of the switch.
• The default case is an optional one. Whenever the value of test-expression is not
matched with any of the cases inside the switch, then the default will be executed.
Otherwise, it is not necessary to write default in the switch.
• Once the switch is executed the control will go to the statement-x, and the execution
of a program will continue.
Example:
int num = 8;
switch (num) {
case 7:
printf("Value is 7");
break;
case 8:
printf("Value is 8");
break;
case 9:
printf("Value is 9");
break;
default:
printf("Out of range");
break;
}
Program-3.1: C program to check whether a given input integer
is in between two values x and y.
Aim:
The main objective of this program is to make familiar with if-else statement.

Pre-Requisite:
To solve this problem, you should have the knowledge of Relational and Logical Operators

Test Cases:

Input Format:

Provide three integer values as input in single line / multi line using keyboard.
The first two values specify the lower and upper bound values. The third value specifies the key
value to be searched between the lower and upper bounds.

Example:
10 20 15

Expected Output Format:

Key value is between the limits

S.No. Input Expected Output Actual Output Remarks


Program-3.2: C program to check whether a given character is a
vowel or a consonant or a digit or a special symbol.
Aim:
The main objective of this program is to make familiar with the different forms of if
statement.

Test Cases:

Input Format:

Provide a character as input.


Example:
a
Expected Output Format:
‘a’ is Vowel

S.No. Input Expected Output Actual Output Remarks


Program-3.3: C program to display the nature and roots of a
quadratic equation.
Aim:
The main objective of this program is to make the students use if- else in solving the problem.

Pre-Requisites:
To solve this problem, you should have the knowledge of square root function sqrt() which is
included in math.h header file.

Syntax of sqrt():

double sqrt(double);

Problem Analysis:
Let α and β be the roots of the general form of the quadratic equation ax2 + bx + c = 0. We can
write:

α = (-b-√b2-4ac)/2a

and

β = (-b+√b2-4ac)/2a

Here a, b, and c are real and rational. Hence, the nature of the roots α and β of equation ax2 + bx
+ c = 0 depends on the quantity or expression (b2 – 4ac) under the square root sign.

Hence, the expression (b2 – 4ac) is called the discriminant of the quadratic equation ax2 + bx + c
=0

Case I: b2 – 4ac > 0

When a, b, and c are real numbers, a ≠ 0 and discriminant is positive, then the roots α and β of
the quadratic equation ax2 +bx+ c = 0 are real and unequal.

Case II: b2– 4ac = 0

When a, b, and c are real numbers, a ≠ 0 and discriminant is zero, then the roots α and β of the
quadratic equation ax2+ bx + c = 0 are real and equal.

Case III: b2– 4ac < 0

When a, b, and c are real numbers, a ≠ 0 and discriminant is negative, then the roots α and β of
the quadratic equation ax2 + bx + c = 0 are unequal and not real. In this case, we say that the
roots are imaginary.
Test Cases:
Input Format:

Provide three values (integer/ floating point) as input using key board in single or multiple
lines.

Example:
156

Expected Output Format:


Nature of the Roots is real and different:
root1 = -2.00 and root2 = -3.00

S.No. Input Expected Output Actual Output Remarks


Program-3.4: C program to perform arithmetic operations using
switch statement.
Aim:
The main objective of this program to make familiar with the usage of switch statement.

Pre-Requisites: To solve this problem, you should have the knowledge of Arithmetic
Operators

Test Cases:

Input Format:

Provide the input using keyboard in a sequence of two integers (1 2) and a character(X) in
multiple lines.
Ex: 1
2
+
Expected Output Format:
Sum of 1 and 2 is : 3

Actual
S.No. Input Expected Output Remarks
Output
Program-3.5: C program to convert upper case character to lower
case and vice versa.
Aim:
The main objective of this program is to make the students use if- else in solving the problem.

Pre-Requisites:
To solve this problem, you should have the knowledge of ASCII values of alphabets (Lower
and Upper case)

Problem Analysis:
ASCII stands for American Standard Code for Information Interchange. Below is the
ASCII character table, including descriptions of the first 32 characters.
A character variable holds ASCII value (an integer number between 0 and 127) rather
than that character itself. The ASCII value of lowercase alphabets are from 97 to 122. And,
the ASCII value of uppercase alphabets are from 65 to 90.

ASCII Table
Dec = Decimal Value
Char = Character

'5' has the int value 53


if we write '5'-'0' it evaluates to 53-48, or the int 5
if we write char c = 'B'+32; then c stores 'b'

Dec Char Dec Char Dec Char Dec Char


--------- --------- --------- ----------
0 NUL (null) 32 SPACE 64 @ 96 `
1 SOH (start of heading) 33 ! 65 A 97 a
2 STX (start of text) 34 " 66 B 98 b
3 ETX (end of text) 35 # 67 C 99 c
4 EOT (end of transmission) 36 $ 68 D 100 d
5 ENQ (enquiry) 37 % 69 E 101 e
6 ACK (acknowledge) 38 & 70 F 102 f
7 BEL (bell) 39 ' 71 G 103 g
8 BS (backspace) 40 ( 72 H 104 h
9 TAB (horizontal tab) 41 ) 73 I 105 i
10 LF (NL line feed, new line) 42 * 74 J 106 j
11 VT (vertical tab) 43 + 75 K 107 k
12 FF (NP form feed, new page) 44 , 76 L 108 l
13 CR (carriage return) 45 - 77 M 109 m
14 SO (shift out) 46 . 78 N 110 n
15 SI (shift in) 47 / 79 O 111 o
16 DLE (data link escape) 48 0 80 P 112 p
17 DC1 (device control 1) 49 1 81 Q 113 q
18 DC2 (device control 2) 50 2 82 R 114 r
19 DC3 (device control 3) 51 3 83 S 115 s
20 DC4 (device control 4) 52 4 84 T 116 t
21 NAK (negative acknowledge) 53 5 85 U 117 u
22 SYN (synchronous idle) 54 6 86 V 118 v
23 ETB (end of trans. block) 55 7 87 W 119 w
24 CAN (cancel) 56 8 88 X 120 x
25 EM (end of medium) 57 9 89 Y 121 y
26 SUB (substitute) 58 : 90 Z 122 z
27 ESC (escape) 59 ; 91 [ 123 {
28 FS (file separator) 60 < 92 \ 124 |
29 GS (group separator) 61 = 93 ] 125 }
30 RS (record separator) 62 > 94 ^ 126 ~
31 US (unit separator) 63 ? 95 _ 127 DEL

Example:

ASCII Value of a is 97 (1100001)


ASCII Value of A is 65 (1000001)
Test Cases:
Input Format: Provide a character as input using key board.

Example: A
Expected Output Format:
Lower Case is a

S.No. Input Expected Output Actual Remarks


Output
Week 4
Prerequisite:
To solve Week 4 problems, you should have the knowledge of Iterative Statements.

Iterative statements or Loops:


Introduction:
Iteration is the process where a set of instructions or statements is executed repeatedly for a
specified number of times or until a condition is met. These statements also alter the control flow
of the program and thus can also be classified as control statements in C Programming
Language.

Iteration statements are most commonly known as loops. Also the repetition process in C is done
by using loop control statements. There are three types of looping statements:
• for Loop
• while Loop
• do-while loop

for loop

A for loop is a programming language statement which allows code to be repeatedly executed.
Syntax:

for (expression1; expression2; expression3 )

{
Statements;
}

expression1 is used for initializing variables which are generally used for controlling termination
condition of the loop.
expression2 is used to check for the terminating condition. If this evaluates to false, then the loop
is terminated.
expression3 is generally used to update the variables which are generally used for controlling
termination condition of the loop.

Example:
for (i = 0; i < 10; i++) {
...
}
while loop (Entry Controlled Loop)
while loop requires a single condition and continues looping as long as that condition continues
to be true. Each time the end of the loop is reached, it loops back to the top and checks if the
condition is still true. If it's true, the loop will run again; if it's false, then the program will skip
over the loop and continue executing the rest of the code.

Syntax:
expression1;
while (expression2)
{
Statements;
……
expression3;
}

expression1 is used for initializing variables which are generally used for controlling termination
condition of the loop.
expression2 is used to check for the terminating condition. If this evaluates to false, then the loop
is terminated.
expression3 is generally used to update the variables which are generally used for controlling
termination condition of the loop.

Example:
int i=0;
while( i < 10)
{
…..
i++;
}
do-while (Exit Controlled Loop):
This is a variation on the while loop where the expression evaluated to true or false is checked at
the end of the brackets. Because of this, the content between the brackets is guaranteed to always
be executed at least once:

Syntax:
do{
// this will execute once
// it will execute again each time while(expression) is true
} while(expression);
Example:
int i=0;
do
{
…..
i++;
} while( i < 10);
Program-4.1: C program to print odd numbers between specified
ranges.
Aim:
The main objective of this program is to make familiar with loop statements.

Test Cases:

Input Format:

Provide two values (integer) as input using key board in single or multiple lines.
Note: First value should be less than the second value.
Example:
1
9
Expected Output Format:
357

S.No. Input Expected Output Actual Output Remarks


Program-4.2: C program to display the factors of a given number
and check whether it is a prime or not.
Aim:
The main objective of this program is to make familiar with different loops.

Test Cases:

Input Format:
Provide an integer value as input using keyboard.
Example:

10

Expected Output Format:

Factors are
1 2 5 10
10 is not a prime number

S.No. Input Expected Output Actual Output Remarks


Program-4.3: C program to display the sum of individual digits of a
given integer raised to the power of n. Also check whether the given
integer is Armstrong or not.
Aim:
The main objective of this program is to make familiar with different loops.
Prerequisite:

To solve this problem, you should have the knowledge of Armstrong number.
Hint: double pow (double, double);
Armstrong number:
An n digit number equal to the sum of the nth powers of its digits.
Example:
a) 153 is an Armstrong number.
(1^3) + (5^3) + (3^3)= 153.
b) 1634 is also an Armstrong number.
(1^4) + (6^4) + (3^4) + (4^4)= 1634.

Test Cases:

Input Format:

Provide two integer values as input using keyboard in single line or multiple lines.
The first input number is the number for which the sum of individual digits is to be obtained.
The second input number is the power to which the individual digits are to be raised.
Example:

370
2

Expected Output Format:


Sum of individual digits raised to power of 2 is 58
370 is an Armstrong number
S.No. Input Expected Output Actual Output Remarks
Program-4.4: C Program to demonstrate the usage of unconditional
control statements.
Aim:
The main objective of this program is to make familiar with conditional and unconditional
control statements.

Prerequisite:

break Statement:
The break statement terminates the execution of the loop and the control is transferred to the
statement immediately following the loop.
• It can be used within for, while, do-while, or switch statement.
• In case of nested loops, it skips the execution of the current loop only.
Syntax:
break;

continue Statement:
• It can be used within for, while, do-while, or switch statement.
• The continue statement tells the compiler “skip the next statements and continue with
the next Iteration”.
Syntax:
continue;

goto Statement:
goto is an unconditional jumping statement, which transfer the program’s control from one
statement to another statement (where label is defined).

‘label’ Syntax:
label_name:

• label_name should be a valid identifier name.


• : (colon) should be used after the label_name.

‘goto’ Syntax:
Program’s control can be transfer following by the given syntax

goto label_name;
Note: Usage of goto and break statements in programming is not a good practice.
Problem Definition:
The program must demonstrate the usage of unconditional control statements like break,
continue and goto.
The program has to read two integer values as input. First input is to read the number of values to
be displayed and the second value is to read an integer value from which the break, continue and
goto statements are to be demonstrated.

Sample input and output descriptions:


10
5
Usage of break statement: 1 2 3 4 should be the output (when series reaches 5, skip the
remaining iterations)
Usage of continue statement: 1 2 3 4 6 7 8 9 10 should be the output (when series reaches 5, skip
the current iteration and continue with the remaining iterations)
Usage of goto statement: 1 2 3 4 should be the output (when series reaches 5, skip the remaining
iterations)

Test Cases:
S.No. Input Expected Output Actual Output Remarks
Program-4.5: C program to display the following pattern.
54321
4321
321
21
1

Aim:
The main objective of this program is to make familiar with nested loops.

Test Cases:

Input Format:
Provide an integer value as input using keyboard.

S.No. Input Expected Output Actual Output Remarks


Week 5
Pre-Requisite:
To solve Week 5 problems, you should have the knowledge of Functions.

Introduction:
Function:
A Function is a self-contained block of statements, used to perform a specific task.
Syntax:
return_type function_name(arguments/ parameters list)
{
// body of the function.
}
• The return type of the function can be int, float etc, depending upon what is to be
returned from called function to calling function. (The default return type of any user
defined function is int)
• Arguments/ Parameters list are variable names enclosed within parenthesis, separated by
a comma.
Example:
A program to find the biggest of two numbers using functions
#include<stdio.h>
int big(int, int); // Function Prototype
void main()
{
int x, y, z;
scanf("%d%d", &x, &y);
z = big(x, y); // Function Call
printf("The biggest of the two numbers is % d", z);
}
int big(int x, int y) //Function Definition
{
return (x >y ? x : y);
}

Types of Functions:
Standard Library Functions:
• The standard library functions are built-in functions in C programming.
• These functions are defined in header files. For example, The printf() is a standard
library function to send formatted output to the screen (display output on the screen).
This function is defined in the stdio.h header file.Hence, to use the printf() function,
we need to include the stdio.h header file using #include <stdio.h>.
• The sqrt() function calculates the square root of a number. The function is defined in
the math.h header file.
• Functions having no return type are called void functions.
• A main function can have either a return type of int or void, i.e., int main() or void
main()

User Defined Functions:


You can also create functions as per your need. Such functions created by the user are known
as user-defined functions.

Example:

#include <stdio.h>
void functionName()
{
... .. ...
... .. ...
}

int main()
{
... .. ...
... .. ...
functionName();
... .. ...
... .. ...
}

Categories of functions:
There are four categories of functions with respect to return type and the arguments list. They
are:
1. Functions with no arguments and no return type
Syntax :
void function(); // Function Prototype
function(); // Function call

void function() // Function Definition


{
statements;
}
2. Functions with arguments and no return type
Syntax :
void function ( int ); // Function Prototype
function( x ); // Function call

void function( int x ) // Function Definition


{
statements;
}
3. Functions with no arguments and return type
Syntax :
int function(); // Function Prototype
function(); // Function call

int function() // Function Definition


{
statements;
return x;
}
4. Functions with arguments and return type
Syntax :
int function ( int ); // Function Prototype
function( x ); // Function call

int function( int x ) // Function Definition


{
statements;
return x;
}
Program-5.1:C program to demonstrate the various categories of
functions with respect to return type and number of arguments.
Aim:
The main objective of this program is to make familiar with categories of functions with respect
to return type and number of arguments.
Problem Definition:
To demonstrate categories of functions, “Addition of two numbers” problem is considered in the
below test cases. Try to solve each test case with separate program with function name add().

Test Cases:
Input Format:
Provide two values (integer) as input using key board in single or multiple lines.
Example:
56
Expected Output Format:
The sum of num1 and num2 with no arguments and no return type is 11

S.
No Input Expected Output Actual Output Remarks
.
Program-5.2: C program to find the LCM of two numbers using
functions.
Aim:

The main objective of this program is to make familiar with usage of functions.

Problem Analysis:
LCM (Least Common Multiple) of two numbers is the smallest number which can be divided by
both numbers.
For example, LCM of 15 and 20 is 60.
Method1:
An efficient solution is based on below formula for LCM of two numbers ‘a’ and ‘b’.
a x b = LCM(a, b) * GCD (a, b)
LCM(a, b) = (a x b) / GCD(a, b)
Method2:
The LCM of two integers n1 and n2 is the smallest positive integer that is perfectly divisible by
both n1 and n2 (without a remainder).

Test Cases:
Input Format:

Provide two values (integer) as input using key board in single or multiple lines.
Example:
72 120
Expected Output Format:

The LCM of 72 and 120 is 360.

S.No. Input Expected Output Actual Output Remarks


Program-5.3: Create a header file which contains the following
prototype:
➢ int factorial (int); // non-recursive function
➢ int factorial_rec(int); //Recursive function
➢ int prime (int);
Use the above functions in a C program by including the above
header file.
Aim:
The main objective of this program is to make familiar with creating user defined header file
with user defined function prototype.

General Discussion:
Files with .h extension are called header files in C. These header files generally contain function
declarations which we can be used in our main C program, for e.g. there is need to include
math.h in our C program to use function sqrt() in the program.
Header files are simply files in which you can declare your own functions that you can use in
your main program or these can be used while writing large C programs.
NOTE:Header files generally contain definitions of data types, function prototypes and C
preprocessor commands.
Syntax:
#include<stdio.h>
or
#include”addition.h”

➢ The file name included in the double quotation’s marks, indicates that the search for the
file is made in the current directory and in the standard directories.
➢ When the file name is included within the angular brackets, the search for file is made
only in the standard directories.

Example:
Test.c
#include"Hello.h"
#include<stdio.h>
void main()
{
Display();
}

Contents of Hello.h:
Void Display()
{
printf ("Hello World!!!");
}

Test Cases:
Input Format:

Provide an integer value as input using keyboard.


Example:
3

Expected Output Format:

The factorial of 3 without recursion is 6


The factorial of 3 with recursion is 6
3 is a prime number.

S.No. Input Expected Output Actual Output Remarks


Program-5.4:C program to display Pascal’s triangle using functions.
Aim:
The main objective of this program is to make familiar with usage of functions.

Problem Analysis:
Pascal’s triangle is a triangular array of the binomial coefficients.

Number of entries in every line is equal to line number. For example, the first line has “1”, the
second line has “1 1”, the third line has “1 2 1”, and so on. Every entry in a line is value of
a Binomial Coefficient. The value of rth entry in line number “n” is C(n, i). The value can be
calculated using following formula.
C(n, r) = n! / r! * (n - r)!

Hint: A simple method is to run two loops and calculate the value of Binomial Coefficient in
inner loop.

Test Cases:
Input Format:

Provide an integer value as input using keyboard.


Example:
3
Expected Output Format:

1
11
121
S.No. Input Expected Output Actual Output Remarks
Week 6
Pre-Requisite:
To solve Week 6 problems, you should have the knowledge of Arrays.

Introduction:
Array:

An array is a type of data structure that stores elements of the same type in a contiguous block of
memory.

In an array, A, of size N, each memory location has some unique index, i (where 0≤ i <N), that
can be referenced as A[i] (you may also see it written as Ai).

• Array might be belonging to any of the data types


• Array size must be a constant value.
• Always, Contiguous (adjacent) memory locations are used to store array elements in
memory.
• It is a best practice to initialize an array to zero or null while declaring, if we don’t assign
any values to array.

Types of Arrays:

There are 2 types of C arrays. They are,

• One-dimensional array
• Multi-dimensional array
a. Two-dimensional array
b. Three-dimensional array
c. Four-dimensional array etc.…

One Dimensional Array:


Conceptually you can think of a one-dimensional array as a row, where elements are stored one
after another.

Syntax:
datatype array_name[size]; // Declaration
or
datatype array_name [size]= {value1, value2, value3,….}; // Declaration and Initialization

where
• datatype denotes the type of the elements in the array.
• array_name is the name of the array. It must be a valid identifier.
• size is the number of elements an array can hold.
• size is optional if declaration and initialization are made simultaneously.
• value1, value2, value3… are the array elements
Example:
int marks [5];
or
int marks [5] = {10,20,30,40,50};
or
int marks [ ] = {10,20,30,40,50};
or
char name [5] = {‘A’,’B’,’C’,’D’,’\0’};

10 20 30 40 50  Array Elements
0 1 2 3 4  Array indices
1000 1002 1004 1006 1008  Array addresses (System Dependent)

Note:
• Array index always starts from 0.
• Starting address of array is base address.
• The name of the array also refers to its base address

Accessing one-dimensional array elements:


Reading array values at run time:
Array elements can be read at run time using scanf ().

Example:
int a [5];
for (i=0; i<5; i++)
scanf (“%d”, &a[i]);

Displaying array values:


Array elements can be displayed using printf ().

Example:
int a [5] = {10,20,30,40,50};
for (i=0; i<5; i++)
printf (“%d”, a[i]);
Two-Dimensional Array:
Two dimensional array is nothing but array of array.

Syntax:
datatype array_name[size1] [size2]; // Declaration
or
datatype array_name [size1] [size2] = {{value1, value2…. valuesize2}, {value1, value2, .…..
valuesize2}}; // Declaration and Initialization

where
• datatype denotes the type of the elements in the array.
• array_name is the name of the array. It must be a valid identifier.
• If the two-dimensional array is considered as a matrix, then size1 denotes the number of
rows and size2 denotes the number of columns.
• size1 is optional if declaration and initialization are made simultaneously.

Example:

int a [2][3] = {{10, 20, 30}, {40, 50, 60}};

The above declaration says that marks is an array with 2rows and 3column elements.

10 20 30 40 50 60  Array Elements
a [0][0] a [0][1] a [0][2] a [1][0] a [1][1] a [1][2]  Array indices
 Array addresses (System
1000 1002 1004 1006 1008 1010
Dependent)
Row 1 Row 2

Accessing two-dimensional array elements:


Reading array values at run time:
Array elements can be read at run time using scanf ().
Example:
int a [3][3];
for (i=0; i<3; i++)
for(j=0;j<3;j++)
scanf (“%d”, &a[i][j]);

Displaying array values:


Array elements can be displayed using printf ().
Example:
int a [2][2] = {{10,20}, {30,40}};
for (i=0; i<2; i++)
for (j=0; j<2;j++)
printf (“%d”, a[i][j]);
Program-6.1: C program to read n integer values into an array and
display them.

Aim:

The main objective of this program is to make familiar with accessing array elements.

Pre-Requisite:

To solve this problem, you should have the knowledge of arrays.

Test Cases:
Input Format:

Provide single value (integer) as input using key board for array size.

In the next line, read array elements in single or multiple lines.

Example:
5
10 20 -3 -6 -1

Expected Output Format:

10 20 -3 -6 -1

SNo Input Expected Output Actual Output Remarks


Program-6.2: C program to count and display the number of positive,
negative, even and odd numbers in a given array of integers and
display their sum.

Aim:

The main objective of this program is to make familiar with accessing array elements.

Pre-Requisite:

To solve this problem, you should have the knowledge of arrays.

Test Cases:
Input Format:

Provide single value (integer) as input using key board for array size.

In the next line, read array elements in single or multiple lines.

Example:
4
-5 3 4 1
Expected Output Format:

The positive numbers are 3


The negative numbers are 1
The odd numbers are 3
The even numbers are 1
The sum is 3

SNo Input Expected Output Actual Output Remarks


Program-6.3: C program to find the smallest and largest numbers in
an array of integers.

Aim:

The main objective of this program is to make familiar with accessing array elements.

Pre-Requisite:

To solve this problem, you should have the knowledge of arrays.

Test Cases:
Input Format:

Provide single value (integer) as input using key board for array size.

In the next line, read array elements in single or multiple lines.

Example:
4
-5 3 4 1

Expected Output Format:


The smallest element is -5
The biggest element is 4

S.No Input Expected Output Actual Output Remarks


Program-6.4: C program to perform addition, multiplication,
transpose of given matrices using functions.

Aim:

The main objective of this program is to make familiar with accessing array elements.

Pre-Requisite:

To solve this problem, you should have the knowledge of arrays.

Test Cases:
Input Format:

Read row and column sizes for first matrix.


Read the values into the first matrix.
Read row and column sizes for second matrix.
Read the values into the second matrix.
Expected Output Format:

Display the addition of two matrices:


Display the multiplication of two matrices
Display the transpose of any one matrix

SNO Input Expected output Actual Output Remarks


Program-6.5: C program to check whether a given integer exists in a
list of numbers and print its index value if it is present, otherwise
print “No”.

Aim:

The main objective of this program is to make familiar with accessing array elements.

Pre-Requisite:

To solve this problem, you should have the knowledge of arrays.

Test Cases:
Input Format:

Provide single value (integer) as input using key board for array size.

In the next line, read array elements in single or multiple lines.

In the next line, read an element to search in array.

Example:
5
10 20 -5 3 9
20
Expected Output Format:
Element found at 2 position

SNo Input Expected output Actual Output Remarks


Week 7
Pre-Requisite:
To solve Week 7 and Week 8 problems, you should have the knowledge of Strings and String
handling functions.

Introduction:
Strings are defined as an array of characters. The difference between a character array and a
string is “string is terminated with a null character ‘\0’ “.
Syntax:
char array_name[size];
Example:
char str1[10];

In the above syntax str1 is any name given to the string variable and size 10 is used to define the
length of the string, i.e. the number of characters array can accommodate. There is an extra
terminating character which is the Null character (‘\0’) used to indicate termination of string
which differs strings from normal character arrays.
Initializing a String:
A string can be initialized in different ways. Below is an example to declare a string with name
as str and initialize it with “GVP Students”.
1. char str [] = "GVP Students";

2. char str [50] = "GVP Students";

3. char str [] = {'G','V','P',' ','S','t','u','d','e','n','t','s','\0'};

4. char str [13] = {'G','V','P',' ','S','t','u','d','e','n','t','s','\0'};

statements to declare and initializing a string and to print it.

// declare and initialize string


char str [] = "GVPStudents";

// print string
printf("%s",str);

The C language does not provide an inbuilt data type for strings but it has a format specifier
“%s” which can be used to access strings.
Reading a String:
Using scanf()
• It reads the input (character, string, numeric data) from the standard input (keyboard).
• It reads the input until it encounters a whitespace, newline or End Of File (EOF).

// declaring string
char str[50];

// reading string
scanf("%s",str);

In the above snippet the string can also be read using a single scanf statement. Also we have not
used the ‘&’ sign with string name ‘str’ in scanf statement. To understand this you have to recall
your knowledge of scanf. We know that the ‘&’ sign is used to provide the address of the
variable to the scanf () function to store the value read in memory. As str[] is a character array so
using str without brackets ‘[‘ and ‘]’ will give the base address of this string. That is the reason
we have not used ‘&’ in this case as we are already providing the base address of the string to
scanf.

Using gets()
• It is used to read input from the standard input(keyboard).
• It is used to read the input until it encounters newline or End Of File(EOF).

// declaring string
char str[50];

// reading string
gets(str);

Note: scanf() can read multiple values of different data types whereas gets() will only get
character string data.
Display a String:
The functions puts() and printf() are declared in stdio.h header file and are used to print the text
on the output screen. Both have different usages and syntax.

printf()
The function printf() is used to print the text along with the values of variables. The
implementation of printf() is complex, that is why it is expensive than puts().
Here is the syntax of printf() in C language,

printf(“string”);

// print string
printf("%s",str);
puts()
The function puts() is used to print the string on the output stream with the additional new line
character ‘\n’. It moves the cursor to the next line. Implementation of puts() is easier than
printf().
Here is the syntax of puts() in C language,
puts(“string”);

String Handling Functions

There are several string library functions used to manipulate string and the prototypes for these
functions are in header file “string.h”. Several string functions are
1) strlen () Function:
strlen () function is used to find the length of a character string.
Syntax:
type strlen (char * str)

Example:
int n;
char st [20] = “Bangalore”;
n = strlen(st);
• This will return the length of the string 9 and is assigned to variable n.
• Note that the null character “\0‟ available at the end of a string is not counted.

2) strcpy () Function:
strcpy () function copies contents of one string into another string.
Syntax
char * strcpy (char * destination, const char * source);
Example:
strcpy (str1, str2) – It copies contents of str2 into str1.
strcpy (str2, str1) – It copies contents of str1 into str2.
If destination string length is less than source string, entire source string value won’t be copied
into destination string.
For example, consider destination string length is 20 and source string length is 30. Then, only
20 characters from source string will be copied into destination string and remaining 10
characters won’t be copied and will be truncated.
Example:
char city [15];
strcpy (city, “BANGALORE”) ;
This will assign the string “BANGALORE” to the character variable city.
3) strcat () Function:
strcat() function in C language concatenates two given strings. It concatenates source
string at the end of destination string.
Syntax :
char * strcat (char * destination, const char * source);
Example :
strcat (str2, str1); - str1 is concatenated at the end of str2.
strcat (str1, str2); - str2 is concatenated at the end of str1.
• As you know, each string in C is ended up with null character (‘\0′).
• In strcat( ) operation, null character of destination string is overwritten by source string’s first
character and null character is added at the end of new destination string which is created after
strcat( ) operation.

4) strncat() Function :
strncat( ) function in C language concatenates (appends) portion of one string at the end
of another string.
Syntax :
char * strncat (char * destination, const char * source, int num);
Example :
strncat ( str2, str1, 3 ); – First 3 characters of str1 is concatenated at the end of str2.
strncat ( str1, str2, 3 ); - First 3 characters of str2 is concatenated at the end of str1.
As you know, each string in C is ended up with null character (‘\0′).
In strncat( ) operation, null character of destination string is overwritten by source string’s first
character and null character is added at the end of new destination string which is created after
strncat( ) operation.

5) strcmp( ) Function :
strcmp( ) function in C compares two given strings and returns zero if they are same. If
length of string1 < string2, it returns < 0 value. If length of string1 > string2, it returns > 0 value.
Syntax:
int strcmp (const char * str1, const char * str2);
strcmp( ) function is case sensitive. i.e., “A” and “a” are treated as different characters.
Example :
char city[20] = “Madras”;
char town[20] = “Mangalore”;
strcmp(city, town);

This will return an integer value “-10‟ which is the difference in the ASCII values of the first
mismatching letters “D‟ and “N‟.
Note: The integer value obtained as the difference may be assigned to an integer variable as
follows:
int n;
n = strcmp (city, town);
6) strcmpi () Function:
strcmpi () function in C is same as strcmp () function. But, strcmpi () function is not case
sensitive. i.e., “A” and “a” are treated as same characters. Whereas, strcmp () function treats “A”
and “a” as different character.
• strcmp () function is non-standard function which may not available in standard library.
• Both functions compare two given strings and returns zero if they are same.
• If length of string1 < string2, it returns < 0 value. If length of string1 > string2, it returns > 0
value.
Note: strcmp () function is case sensitive. i.e., “A” and “a” are treated as different characters.

Syntax:
int strcmpi ( const char * str1, const char * str2 );
Example :
m=strcmpi(“ DELHI ”, “ delhi ”);
Output:
m = 0.

7) strlwr() Function :
strlwr() function converts a given string into lowercase.
Syntax :
char *strlwr(char *string);

8) strupr() Function :
strupr() function converts a given string into uppercase.
Syntax :
char *strupr(char *string);

9) strrev() Function :
strrev() function reverses a given string in C language.
Syntax :
char *strrev(char *string);
Example :
char name[20]=”ftl”; then
strrev(name)= ltf

10) strchr() Function :


strchr() function returns pointer to the first occurrence of the character in a given string.
Syntax :
char *strchr(const char *str, int character);

11) strstr () Function :


strstr() function returns pointer to the first occurrence of the string in a given string.
Syntax :
char *strstr(const char *str1, const char *str2);
12) atoi() Function :
It converts string-value to numeric-value and it converts a numeric-string value to
equivalent integer-value.
Syntax :
int atoi(string);
Example :
printf(“output=%d”, atoi(“123”)+atoi(“234”));
This printf() will print 357

13) atol() Function :


converts a long int string value to equivalent long integer value.
Syntax :
long int atol(string);
Example :
printf(“output=%d”, atol(“486384”)-atol(“112233”));
This statement will print 374151

14) atof() Function :


converts a floating-point text format value to double value.
Syntax :
int atoi(string);
Example :
printf(“%1f”,atof(“3.1412”)*5*5);
This statement will print 78.530000

15) itoa (), ltoa (), ultoa() :


These functions convert a given number (int / long int / unsigned long int) to equivalent
text format based on the given numbering system radix value.
These functions take three arguments, the numeric value, target string address in which
the value to be stored and radix value. Finally returns the target string address, so that function-
call can be used as argument/expression.
Syntax :
char* itoa (int value, char *targetstringaddress, int radix);
Example :
Char temp[50];
Printf(“output=%s”, itoa(45,temp,2));
Output : 101101
Program-7.1: C program to convert upper case character to lower
case and vice versa in a given string.
Aim:
The main objective of this program is to make familiar with conversion of characters from lower case to

upper case and vice versa and ASCII values.

example: Hello Students

hELLO sTUDENTS

Test Cases:
Input Format:
Provide any text as input string using key board.
Example:
GVpCe
Expected Output Format:
gvPcE

S.No. Expected Actual


Input Remarks
Output Output
Program-7.2: C program to delete all vowels in a given string and
display the remaining string.
Aim:

The main objective of this program is to make familiar with deleting the characters from a given
string.

Test Cases:
Input Format:

Provide any text as input string using key board.

Example:
welcome
Expected Output Format:
wlcm

Actual
S.No. Input Expected Output Output Remarks
Program-7.3: C program to check whether a given string is
palindrome or not.

Aim:
The main objective of this program is to make familiar with reversing a given string, comparing
strings.

Test Cases:
Input Format:

Provide any text as input string using keyboard.


Example:
madam

Expected Output Format:


The given String is palindrome

S.No. Input Expected Output Actual Output Remarks


Program-7.4: C program that reads two integers as strings and
display their sum.
Aim:
The main objective of this program is to make familiar conversion from sting to integer and
ASCII values.

Test Cases:
Input Format:

Provide two integers as strings input using keyboard in single or multiple lines.
Example:
123 27
Expected Output Format:
The sum of two given strings 123 and 27 is 150

S.No. Input Expected Output Actual Output Remarks


Week 8
Program-8.1: C program to demonstrate the usage of at least 10 predefined
string handling functions.
Aim:
The main objective of this program is to make familiar with usage of string library functions

Test Cases:
Input Format:
Read the input through keyboard based on the string handling functions considered. The input may be a
single string or two strings or string along with an integer value (for ex: strncmp() requires two strings
and an integer as an input)

Expected Output Format:


Output depends on the type of string handling function used.
For Example:
char name[20]=”GVP”; then
strrev(name) gives PVG
Program-8.2: C program that implements the following user defined string
handling functions
• To find the length of the given string
• To copy the contents of one string to another
• To reverse the contents of a string
• To compare two strings
• To concatenate two strings

Aim:

The main objective of this program is to make familiar with user-defined string handling functions

Test Cases:
Input Format:
Read the input through keyboard based on the string handling functions considered. The input may be a
single string or two strings or string along with an integer value (for ex: strncmp() requires two strings and
an integer as an input)

Expected Output Format:


Output depends on the type of string handling function used.
For Example:
char name[20]=”GVP”; then
strrev(name) gives PVG

S.No. Input Expected Output Actual Output Remarks


Week-9
Pre-Requisite:
To solve Week 9 and Week 10 problems, you should have the knowledge of pointers and dynamic memory
allocation.

Introduction:

A Pointer is a variable that stores/points the address of another variable. A Pointer in C is used to allocate
memory dynamically i.e. at run time. The pointer variable might be belonging to any of the data type such
as void, int, float, char, double, short etc.

Syntax:
datatype *var_name;
Example:
int *p; char *p;
Where, * is used to denote that “p” is pointer variable and not a normal variable.
KEY POINTS TO REMEMBER ABOUT POINTERS IN C:
• Normal variable stores the value whereas pointer variable stores the address of the variable.
• The content of the pointer is always an unsigned integer i.e. the address of a variable it is pointing
to.
• Always pointer is initialized to null, i.e. int *p = null.
• The value of null pointer is 0.
• & symbol is used to get the address of the variable.
• * symbol is used to get the value of the variable that the pointer is pointing to.
• If a pointer is assigned to NULL, it means it is pointing to nothing.
• Two pointers can be subtracted to know how many elements are available between these two
pointers.
• But, Pointer addition, multiplication, division are not allowed.
• The size of any pointer is always the size of integer, which is compiler dependent.
Dynamic Memory Allocation
Dynamic Memory Allocation can be defined as a procedure in which the size of a data structure (like
Array) is changed during the runtime.

C provides some functions to achieve these tasks. There are 4 library functions provided by C defined
under <stdlib.h> header file to facilitate dynamic memory allocation in C programming. They are:

i. malloc()
ii. calloc()
iii. free()
iv. realloc()
i) malloc ()
“malloc” or “memory allocation” function in C is used to dynamically allocate a single large block of
memory with the specified size. It returns a pointer of type void which can be type cast into a pointer of
any form.

Syntax:
ptr = (type cast*) malloc(byte-size);

Example:
ptr = (int*) malloc (5 * sizeof(int));

Since the size of int is 4 bytes, this statement will allocate 20 bytes of memory. And, the pointer ptr holds
the address of the first byte in the allocated memory.

ii) calloc()
“calloc” or “contiguous allocation” method in C is used to dynamically allocate the specified number of
blocks of memory of the specified type. It initializes each block with a default value ‘0’.

Syntax:
ptr = (cast-type*)calloc(n, element-size);

Example:
ptr = (float*) calloc (25, sizeof(float));

This statement allocates contiguous space in memory for 25 elements each with the size of the float.
iii) realloc ()
“realloc” or “re-allocation” method in C is used to dynamically change the memory allocation of a
previously allocated memory. In other words, if the memory previously allocated with the help of malloc
or calloc is insufficient, realloc can be used to dynamically re-allocate memory.

Syntax:
ptr = realloc (ptr, newSize);
where ptr is reallocated with new size 'newSize'.

Example:
ptr= realloc (ptr, 10* sizeof(int));

iv) free()
“free” method in C is used to dynamically de-allocate the memory. The memory allocated using functions
malloc() and calloc() is not de-allocated on their own. Hence the free() method is used, whenever the
dynamic memory allocation takes place. It helps to reduce wastage of memory by freeing it.

Syntax:
free(ptr);
Pointer Arithmetic
There are four arithmetic operators that can be used on pointers: ++, --, +, and -. To understand pointer
arithmetic, let us consider that ptr is an integer pointer which points to the address 1000. Assuming 32-bit
integers, let us perform the following arithmetic operation on the pointer.

i) Incrementing a Pointer (ptr++)


After the above operation, the ptr will point to the location 1004 because each time ptr is incremented, it
will point to the next integer location which is 4 bytes next to the current location. This operation will
move the pointer to the next memory location without impacting the actual value at the memory location.
If ptr points to a character whose address is 1000, then the above operation will point to the location 1001
because the next character will be available at 1001.

ii) Decrementing a Pointer (ptr - -)


The same considerations apply to decrementing a pointer, which decreases its value by the number of
bytes of its data type as shown below.

iii) Pointer Comparisons


Pointers may be compared by using relational operators, such as ==, <, and >. If p1 and p2 point to
variables that are related to each other, such as elements of the same array, then p1 and p2 can be
meaningfully compared.
Illegal arithmetic with pointers
There are various operations which cannot be performed on pointers. Since, pointer stores address hence
we must ignore the operations which may lead to an illegal address, for example, addition, and
multiplication. A list of such operations is given below.
• Address + Address = illegal
• Address * Address = illegal
• Address % Address = illegal
• Address / Address = illegal
• Address & Address = illegal
• Address ^ Address = illegal
• Address | Address = illegal
• ~Address = illegal

Pointer to Pointer
A pointer to a pointer is a form of multiple indirection, or a chain of pointers. Normally, a pointer contains
the address of a variable. When we define a pointer to a pointer, the first pointer contains the address of the
second pointer, which points to the location that contains the actual value as shown below.

A variable that is a pointer to a pointer must be declared as such. This is done by placing an additional
asterisk in front of its name. For example, the following declaration declares a pointer to a pointer of type
int.
int **var;
When a target value is indirectly pointed to by a pointer to a pointer, accessing that value requires that the
asterisk operator be applied twice

Pointer to Array
A pointer to array is assigning the base address of the array to the pointer and accessing the array elements
with the help of the pointer instead of array index.
Example
int *p;
int arr[5];
p = arr; or p=&arr[0];

Array of Pointers
Syntax:
datatype (*var_name) [size_of_array];

Example:
int a[10]; // here a is an array of 10 integers
int (*ptr)[10]; // here ptr is an pointer array storing the address of 10 array locations

Pointers to Functions
It is possible to declare a pointer pointing to a function which can then be used as an argument in another
function. A pointer to a function is declared as follows

Syntax
type (*pointer-name) (parameter);

Example
int (*sum) (); //legal declaration of pointer to function
int *sum (); //This is not a declaration of pointer to function

A function pointer can point to a specific function when it is assigned the name of that function.
int sum(int, int);
int (*s)(int, int);
s = sum;
Here ‘s’ is a pointer to a function sum. Now sum can be called using function pointer s along with
providing the required argument values.
s (10, 20);
Program-9.1: C program to demonstrate the usage of pointers.
Aim:
The main objective of this program is to make familiar with the usage of pointers

Test Cases:

Input Format:

i. Read an input variable of any data type (ex: char, int , float etc).
ii. Declare a pointer variable pointing to the above read variable.

Expected Output Format:


Display the address and value of the variable using both input variable and pointer variable.
Program-9.2: C program that uses dynamic memory allocation
functions to add n elements and display their average.
Aim:

The main objective of this program is to make familiar with usage of dynamic memory allocating
functions.

Test Cases:
Input Format:

i. Provide an integer value ‘n’ as input using keyboard (number of elements to be read).
ii. Read ‘n’ integer values using keyboard (using malloc or calloc function)

Example:
5
10 20 30 40 50
Expected Output Format:

Average of given values is 30.000000


Program-9.3: C program that performs pointer arithmetic.
Aim:
The main objective of this program is to make familiar with pointer arithmetic

Test Cases:
Input Format:

i. Read input for a variable of any data type (ex: char, int, float etc).
ii. Declare a pointer variable pointing to the above variable.

Expected Output Format:

Display the address and value of the variable after performing pointer addition, pointer subtraction,
pointer increment, pointer decrement and pointer comparison separately.
Program-9.4: C program that implements call by reference.
Aim:
The main objective of this program is to make familiar with function call using call by reference.

Test Cases:
Input Format:

Read the input based on the problem selected to solve and pass the values to the user defined
function using call by reference method.
Example:
If addition of two number is considered, read any two values (int, float, double etc.)
Expected Output Format:
Calculate the sum of two given numbers in user defined function and display sum in main
function.
Week-10
Program-10.1: C program to demonstrate the following
• Pointers to Pointers
• Array of Pointers
• Pointer to Array
• Pointers to Functions

Aim:
The main objective of this program is to make familiar, the usage of pointers with respect to pointers,
arrays and functions
Test Cases:

Input Format:

Provide the input based on the problem statement selected that demonstrates the above-mentioned
tasks.

Expected Output Format:


Display the output in accordance with the program written for the above problem statements.
Week-11
Pre-Requisite:
To solve Week 11 programs, you should have the knowledge of Structures, pointers.

Introduction:
A structure is a derived data type in C. A structure creates a data type that can be used to
group items of possibly different types into a single type. ‘struct’ keyword is used to create a
structure.

Syntax:

Example:
struct address
{
char name[50];
char street[100];
char city[50];
char state[20];
int pin;
};

Declaration of Structure Variables:


A structure variable can either be declared with structure declaration or as a separate
declaration like basic types.
// A variable declaration with structure declaration.
struct Point
{
int x, y;
} p1; // The variable p1 is declared with 'struct Point'
// A variable declaration like basic data types
struct Point
{
int x, y;
};

int main ()
{
struct Point p1; // The variable p1 is declared like a normal variable
}

// Another way of structure variable declaration.


struct
{
int x, y;
}p1;

Initialization of Structure variables:


Structure members cannot be initialized with declaration. For example, the following C
program fails in compilation.

struct Point
{
int x = 0; // COMPILER ERROR: cannot initialize members here
int y = 0; // COMPILER ERROR: cannot initialize members here
};
The reason for above error is simple, when a datatype is declared, no memory is allocated for
it. Memory is allocated only when variables are created.
Structure members can be initialized using curly braces ‘{}’. For example, following is a
valid initialization.

struct Point
{
int x, y;
};

int main()
{
// A valid initialization. member x gets value 0 and y
// gets value 1. The order of declaration is followed.
struct Point p1 = {0, 1};
}
Accessing of Structure members:
Structure members are accessed using dot (.) operator.

Example:
printf ("x = %d, y = %d", p1.x, p1.y);
Where x and y are structure members
p1 is a structure variable

Array of structures:
Like other primitive data types, we can create an array of structures.
// structure declaration
struct Point
{
int x, y;
};

// The array variable arr is declared with 'struct Point'


struct Point arr[10];

// Accessing of structure members


printf ("%d %d", arr[0].x, arr[0].y);

Structure pointer:
Like primitive types, we can have pointer to a structure. This can be done by declaring a
pointer of datatype struct structure_name and assigning the address of the structure variable
to this structure pointer and the members are accessed using arrow ( → ) operator as
structure_pointer → structure_member.

Example:
// structure declaration
struct Point
{
int x, y;
};
struct Point p1;

// p2 is a pointer to structure p1
struct Point *p2 = &p1;

// Accessing of structure members using structure pointer


printf ("%d %d", p2→x, p2→y);

Limitations of C Structures:
In C language, Structures provide a method for packing together data of different types. A
Structure is a helpful tool to handle a group of logically related data items. However, C
structures have some limitations.
• The C structure does not allow the struct data type to be treated like built-in data
types:
• We cannot use operators like +, - etc. on Structure variables.
• No Data Hiding: C Structures do not permit data hiding. Structure members can
be accessed by any function, anywhere in the scope of the Structure.
• Functions inside Structure: C structures do not permit functions inside Structure
Program-11.1: C program to access and display the members of
the structure.

Aim:
The main objective of this program is to make familiar, with the basics of structures.

Test Cases:
Input Format:

Provide the input based on the problem statement selected that demonstrates the above-
mentioned tasks. (Use dot operator to access the structure members).

Expected Output Format:


Display the output in accordance with the program written for the above problem statements.
Program-11.2: C program that demonstrates different ways to
access the structure elements using pointers.

Aim:
The main objective of this program is to make familiar with accessing the structure members
using structure pointers

Test Cases:
Input Format:

Provide the input based on the problem statement selected that demonstrates the above-
mentioned tasks.

Expected Output Format:


Display the output in accordance with the program written for the above problem statements.
Week-12
Pre-Requisite:

To solve Week 12 programs, you should have the knowledge of Files and File handling
functions.

Introduction:
File is a collection of bytes that is stored on secondary storage devices like disk. There are two
kinds of files in a system. They are,

• Text files (ASCII)


• Binary files

Text files contain ASCII codes of digits, alphabetic and symbols.


Binary file contains collection of bytes (0’s and 1’s). Binary files are compiled version of text
files.

BASIC FILE OPERATIONS IN C PROGRAMMING:

There are 4 basic operations that can be performed on any files in C programming language.
They are,

• Opening/Creating a file
• Reading a file
• Writing in a file
• Closing a file

Opening or creating file


For opening a file, fopen() function is used with the required access modes. Some of the
commonly used file access modes are mentioned below.
File opening modes in C:
• “r” – Searches file. If the file is opened successfully fopen() loads it into memory and
sets up a pointer which points to the first character in it. If the file cannot be opened
fopen( ) returns NULL.
• “w” – Searches file. If the file exists, its contents are overwritten. If the file doesn’t
exist, a new file is created. Returns NULL, if unable to open file.
• “a” – Searches file. If the file is opened successfully fopen() loads it into memory and
sets up a pointer that points to the last character in it. If the file doesn’t exist, a new file
is created. Returns NULL, if unable to open file.
• “r+” – opens a text file in both reading and writing mode. The file must exist.
• “w+” – opens a text file in both reading and writing mode. If the file exists, it's
truncated first before overwriting. Any old data will be lost. If the file doesn't exist, a
new file will be created.
• “a+” – opens a text file in both reading and appending mode. New data is appended at
the end of the file and does not overwrite the existing content.
• “rb”- opens a binary file in reading mode.
• “wb”- opens or creates a binary file in writing mode.
• “ab”- opens a binary file in append mode.
• “rb+”- opens a binary file in both reading and writing mode, and the original content is
overwritten if the file exists.
• “wb+”- opens a binary file in both reading and writing mode and works like the w+
mode for binary files. The file content is deleted first and then new content is added.
• “ab+”- opens a binary file in both reading and appending mode and appends data at the
end of the file without overwriting the existing content.

As given above, if you want to perform operations on a binary file, then you must append ‘b’
at the last. For example, instead of “w”, you must use “wb”, instead of “a+” you have to use
“a+b”. For performing the operations on the file, a special pointer called File pointer is used
which is declared as
FILE *filePointer;
So, the file can be opened as
filePointer = fopen(“fileName.txt”, “w”)

The second parameter can be changed to contain all the attributes listed in the above table.
Reading from a file
The file read operations can be performed using functions fscanf() or fgets(). Both the
functions performed the same operations as that of printf and gets but with an additional
parameter, the file pointer. So, it depends on you if you want to read the file line by line or
character by character.
And the code snippet for reading a file is as:
FILE * filePointer;
filePointer = fopen(“fileName.txt”, “r”);
fscanf(filePointer, "%s %s %s %d", str1, str2, str3, &year);

Writing to a file
The file write operations can be perfomed by the functions fprintf() and fputs() with
similarities to read operations. The snippet for writing to a file is as :
FILE *filePointer ;
filePointer = fopen(“fileName.txt”, “w”);
fprintf(filePointer, "%s %s %s %d", "We", "are", "in", 2020);

Closing a file
After every successful fie operations, you must always close a file. For closing a file, you
have to use fclose() function. The snippet for closing a file is given as :

FILE *filePointer ;
filePointer= fopen(“fileName.txt”, “w”);
fclose(filePointer)
File
Description
handling functions

fopen () function creates a new file or opens an existing


fopen ()
file.

fclose () fclose () function closes an opened file.

getw () getw () function reads an integer from file.

putw () putw () functions writes an integer to file.

fgetc () fgetc () function reads a character from file.

fputc () fputc () functions write a character to file.

gets () gets () function reads line from keyboard.

puts () puts () function writes line to o/p screen.

fgets () function reads string from a file, one line at a


fgets ()
time.

fputs () fputs () function writes string to a file.

feof () feof () function finds end of file.

fgetchar () fgetchar () function reads a character from keyboard.

fprintf () fprintf () function writes formatted data to a file.

fscanf () fscanf () function reads formatted data from a file.

fputchar () function writes a character onto the output


fputchar ()
screen from keyboard input.

fseek () function moves file pointer position to given


fseek ()
location.

SEEK_SET moves file pointer position to the


SEEK_SET
beginning of the file.

SEEK_CUR moves file pointer position to given


SEEK_CUR
location.

SEEK_END moves file pointer position to the end of


SEEK_END
file.

ftell () ftell () function gives current position of file pointer.


rewind () function moves file pointer position to the
rewind ()
beginning of the file.

getc () getc () function reads character from file.

getch () getch () function reads character from keyboard.

getche () function reads character from keyboard and


getche ()
echoes to o/p screen.

getchar () getchar () function reads character from keyboard.

putc () putc () function writes a character to file.

putchar () putchar () function writes a character to screen.

printf () printf () function writes formatted data to screen.

sprintf () sprintf () function writes formatted output to string.

scanf () scanf () function reads formatted data from keyboard.

sscanf () sscanf () function Reads formatted input from a string.

remove () remove () function deletes a file.

fflush () fflush () function flushes a file.

Command line arguments:

Command line argument is a parameter supplied to the program when it is invoked.


Command line argument is an important concept in C programming. It is mostly used when
you need to control your program from outside. Command line arguments are passed to the
main() method.
Syntax:
int main(int argc, char *argv[])
Here argc counts the number of arguments on the command line and argv[ ] is a pointer
array which holds pointers of type char which points to the arguments passed to the program.
Program-12.1: C program to read the contents of a file and display
on to output screen.
Aim:
The main objective of this program is to make familiar, file I/O functions

Steps to perform the above task:


Step1: Create a text file with some content.
(Ex. file1.txt, file2.c etc).
Step2: Observe the absolute path of the text file created in Step1.
(Ex. D:\C_Programs\file1.txt).
Step3: Write the program for the above-mentioned task by using the path of step2 as an
argument in fopen() function.
Step4: Compile and Execute the program.

Test Cases:
Expected Output Format:
Display the content of the text file created in step1.
Program-12.2: C program to copy the contents of one file to
another.
Aim:
The main objective of this program is to make familiar, file I/O functions

Steps to perform the above task:


Step1: Create a text file with some content.
(Ex. file1.txt, file2.c etc).
Step2: Observe the absolute path of the text file created in Step1.
(Ex. D:\C_Programs\file1.txt).
Step3: Write the program for the above-mentioned task by using the path of step2 as an
argument in fopen() function in “r” mode.
Step4: Compile and Execute the program.

Test Cases:
Expected Output Format:
The contents of the file opened in “r” mode will be copied to the file opened in “w” mode.
Program-12.3: C program to count and display the number of
characters, words and lines in a file.
Aim:
The main objective of this program is to make familiar, file I/O functions

Steps to perform the above task:


Step1: Create a text file with some content.
(Ex. file1.txt, file2.c etc).
Step2: Observe the absolute path of the text file created in Step1.
(Ex. D:\C_Programs\file1.txt).
Step3: Write the program for the above-mentioned task by using the path of step2 as an
argument in fopen() function in “r” mode.
Step4: Compile and Execute the program.

Test Cases:
Expected Output Format:
Display the output in accordance with the content of the text file created in step1.

For Example:
If the text file content is
Welcome to GVP
College of Engineering
Number of characters: 32
Number of words: 6
Number of lines: 2
Program-12.4: C program to print last n characters of a file by
reading file name and n value from command line.
Aim:
The main objective of this program is to make familiar, file I/O functions

Steps to perform the above task:


Step1: Create a text file with some content.
(Ex. file1.txt, file2.c etc).
Step2: Observe the absolute path of the text file created in Step1.
(Ex. D:\C_Programs\file1.txt).
Step3: Write the program for the above-mentioned task by using the path of step2 as an
argument in fopen() function in “r” mode.
Step4: Compile and Execute the program.

Test Cases:
Input Format:
Provide two inputs to the program from command line
First input is the number of characters of integer datatype
Second input is the name of the file from which the last n values are to be displayed.
Expected Output Format:
The last n characters of the file selected will be displayed onto the output screen.
PROGRAMS TO BE COVERED
BEYOND SYLLABUS
1. C program to find the factorial of a given number using recursive and non recursive
functions.
2. C program to display the first n terms of the Fibonacci sequence.
Example: If n= 5 it has to print 0 1 1 2 3

3. Write a general-purpose function to convert any given year into its roman equivalent.
The following table shows the roman equivalents of decimal numbers:

Decimal Roman
1 I
5 V
10 X
50 L
100 C
500 D
1000 M
Example:
Roman equivalent of 1988 is MDCCCCLXXXVIII
Roman equivalent of 1525 is MDXXV

4. C program to display upper and lower triangles of a given matrix.


5. C program to add the sum of row wise elements, column wise elements and diagonal
elements of a given square matrix and display the result.
6. C program to check whether the matrix is symmetric or not.
7. Given a positive integer (<= 1000000), find the minimum number of bits required to
represent it as a binary number.
8. C program to perform left rotation of the array.
9. C program to implement binary search
10. C program to sort a given list of values using bubble sort.
11. C program to find the LCM of array of integers
12. C program to find the two’s complement of a given binary input.
13. C program to replace all the vowels in a given string with a given character
14. C program to perform arithmetic operations using command line arguments
15. C program that writes the contents to a file and reads the contents from a file using
structures.
REFERENCES

TEXT BOOKS
1. “The C Programming Language” by Brian W. Kernighan / Dennis
Ritchie, 2nd Edition, 1 January 2015, Prentice Hall PTR.
2. Ashok N Kamthane, Amit Ashok Kamthane, Programming in C,
3rd Edition, Pearson Publication 2015.
3. Harsha Priya, R. Ranjeet, Programming and Problem Solving
Through “C” Language, New Edition, Fire Wall Media 2015.
(For Unit 1)
4. Herbert Schildt, The Complete Reference, C 4th Edition, Tata
McGraw-Hill 2000.
5. Brian W. Kernighan and Dennis M. Ritchie, The C Programming
Language, 2nd Edition, Prentice-Hall, 2006.
6. Rajaraman V, The Fundamentals of Computer, 4th Edition ,
Prentice-Hall of India 2006.
7. Steve Oualline, Practical C Programming, 3rd Edition, O’Reilly
Press 2006.
8. Jeri R. Hanly, Elliot B. Koffman, Problem Solving and Program
Design in C,5th Edition, Pearson Education 2007.
9. Balagurusamy E, Programming in ANSI C, 4th Edition, Tata
Mcgraw Hill. 82, 2008.
10. Gottfried, Programming with C, 3rd Edition , Tata Mcgraw Hill,
2010. R G Dromey, How to Solve it by Computer, 1st Edition ,
Pearson Education 2006.

WEB LINKS
1. https://www.hackerrank.com
2. www.hackerearth.com
3. https://swayam.gov.in/nd1_noc20_cs06/preview

You might also like