PSLUC Lab Manual Without Test Cases
PSLUC Lab Manual Without Test Cases
College of Engineering
(Autonomous)
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
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.
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.
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
CO 3: Demonstrate the usage of functions and related functions with respect to arrays and strings.
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
• 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
• 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 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.
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;
}
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.
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.
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.
The printf function calls are expressions, so statements such as printf ("Hello World!\n"); are expression
statements.
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 (\”).
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
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);
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
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
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
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
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 – –;
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++;
Test Cases:
Input Format:
Provide two values (integer/floating point) as input in single line / multi line using keyboard.
Example:
1 2
Note: Apply Post increment on 1st value and Pre Increment on 2nd value
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
0 0 0 0 0 1
0 1 0 1 1 1
1 0 0 1 1 0
1 1 1 1 0 0
#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
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
NOTE: When we are using division (/) operator the result will completely depend upon the
data type it belongs to.
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:
Example:
123
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
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.
Test Cases:
Input Format:
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”);
}
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
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.
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
Test Cases:
Input Format:
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
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.
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.
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
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
Example:
Example: A
Expected Output Format:
Lower Case is a
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:
{
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
Test Cases:
Input Format:
Provide an integer value as input using keyboard.
Example:
10
Factors are
1 2 5 10
10 is not a prime number
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
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:
‘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.
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.
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()
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
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:
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:
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:
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).
Types of Arrays:
• One-dimensional array
• Multi-dimensional array
a. Two-dimensional array
b. Three-dimensional array
c. Four-dimensional array etc.…
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
Example:
int a [5];
for (i=0; i<5; i++)
scanf (“%d”, &a[i]);
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:
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
Aim:
The main objective of this program is to make familiar with accessing array elements.
Pre-Requisite:
Test Cases:
Input Format:
Provide single value (integer) as input using key board for array size.
Example:
5
10 20 -3 -6 -1
10 20 -3 -6 -1
Aim:
The main objective of this program is to make familiar with accessing array elements.
Pre-Requisite:
Test Cases:
Input Format:
Provide single value (integer) as input using key board for array size.
Example:
4
-5 3 4 1
Expected Output Format:
Aim:
The main objective of this program is to make familiar with accessing array elements.
Pre-Requisite:
Test Cases:
Input Format:
Provide single value (integer) as input using key board for array size.
Example:
4
-5 3 4 1
Aim:
The main objective of this program is to make familiar with accessing array elements.
Pre-Requisite:
Test Cases:
Input Format:
Aim:
The main objective of this program is to make familiar with accessing array elements.
Pre-Requisite:
Test Cases:
Input Format:
Provide single value (integer) as input using key board for array size.
Example:
5
10 20 -5 3 9
20
Expected Output Format:
Element found at 2 position
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";
// 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”);
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
hELLO sTUDENTS
Test Cases:
Input Format:
Provide any text as input string using key board.
Example:
GVpCe
Expected Output Format:
gvPcE
The main objective of this program is to make familiar with deleting the characters from a given
string.
Test Cases:
Input Format:
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:
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
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)
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)
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.
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.
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:
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.
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.
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;
};
int main ()
{
struct Point p1; // The variable p1 is declared like a normal variable
}
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;
};
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;
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).
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.
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,
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
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
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
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
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
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
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