C U1 Notes
C U1 Notes
C U1 Notes
Unit #: 1
Unit Name: Problem Solving Fundamentals
Topic: Introduction to C and C Features
Course objectives:
The objective(s) of this course is to make students
CObj1: Acquire knowledge on how to solve relevant and logical problems using computing
machine
CObj2: Map algorithmic solutions to relevant features of C programming language constructs
CObj3: Gain knowledge about C constructs and it's associated eco-system
CObj4: Appreciate and gain knowledge about the issues with C Standards and it's respective
behaviors
CObj5: Get insights about testing and debugging C Programs
Course outcomes:
At the end of the course, the student will be able to
CO1: Understand and apply algorithmic solutions to counting problems using appropriate C
Constructs
CO2: Understand, analyse and apply text processing and string manipulation methods using C
Arrays, Pointers and functions
CO3: Understand prioritized scheduling and implement the same using C structures
CO4: Understand and apply sorting techniques using advanced C contructs
CO5: Understand and evaluate portable programming techniques using preprocessor directives and
conditional compilation of C Programs
Team – PSWC,
Jan - May, 2022
Dept. of CSE,
PES University
• A CPL is an artificial language that can be used to control the behaviour of a machine,
particularly a computer.
• CPLs, like human languages, are defined through the use of syntactic and semantic rules,
to determine structure and meaning respectively.
• Middle Level
o Offers basic data structure and array definition, but the programmers should
take care of the operations
o C and C++
• High Level
o Programmer concentrates on the algorithm and programming itself
o Java , Python, Pascal
Example: C Language.
Functional (Applicative): Programming with function calls that avoid any global state
Examples: Scheme, Haskell, Miranda and JavaScript.
Function-Level (Combinator): Programming with no variables at all
Examples: Scheme, Haskell, Miranda and JavaScript.
Object-Oriented: Programming by defining objects that send messages to each other.
Objects have their own internal (encapsulated) state and public interfaces.
Class-based: Objects get state and behavior based on membership in a class.
Prototype-based: Objects get behavior from a prototype object.
Examples: Java, C++, Python
Event-Driven: Programming with emitters and listeners of asynchronous actions.
Flow-Driven: Programming processes communicating with each other over predefined
channels.
Logic (Rule-based): Programming by specifying a set of facts and rules. An engine infers the
answers to questions.
Constraint: Programming by specifying a set of constraints. An engine finds the values that
meet the constraints.
Aspect-Oriented: Programming cross-cutting concerns applied transparently.
Reflective: Programming by manipulating the program elements themselves.
Array: Programming with powerful array operators that usually make loops unnecessary.
Q7. Why should one learn C? What are the advantages of ‘C’? Is not ‘C’ an outdated
language?
We have to fill our stomach every day 3 or 4 times so that our brain and body get enough
energy to function. How about eating Vidyarthi Bhavan Dosa every day? What about Fridays when
the eatery is closed? Why not buy Dosa batter from some nearby shop? Or do you prefer to make
the batter yourself? Would you have time to do that? Would that depend on how deep your pockets
are? Would you like to decrease your medical bills?
Every language has a philosophy. The language used by poets may not be suitable for
conversation. Poets use ambiguity in meaning to their advantage, and some verses in Sanskrit have
more than one meaning. But that will not be suitable for writing a technical report. The goal of ‘C’
is efficiency. The safety is in the hands of the programmer. ‘C’ does very little apart from what the
programmer has asked for.
Example: When we index outside the bounds of a list in Python, we get an “index error” at
runtime. To support this feature, Python runtime should know the current size of a list and should
also check whether the index is valid each time we index on a list. You are all very good
programmers, and I am sure you never get an index error. You get what you deserve. If you are
lucky, the program crashes. Otherwise, something subtle may happen, which later may lead to
catastrophic failures.
• C is not very strongly typed; mixing of types may not result in errors
• C is the language of choice for software’s like operating system, compilers, linkers,
loaders, device drivers.
It was designed by Dennis Ritchie –We use ‘C’ like languages and Unix like
operating systems both have his contribution – in 70s. But the language has evolved
over a period. The latest ‘C’ was revised in 2011.
There is one more reason to learn ‘C’. ‘C’ is the second most popular language as
of now according to TIOBE index ratings. https://www.tiobe.com/tiobe-index/.
● In 1942, United States, ENIAC used electrical signals instead of physical motion
● In 1945, Von Newman developed two concepts: Shared program technique and Conditional
control transfer
6 Dept. of Computer Science and Engineering
2022
Problem Solving With C – UE23CS151B
● Cobol: 1959
● C: 1972, D Ritchie
● C++: 1983, Bjarne Stroustrup, Compile time type checking, templates are used.
● Java: 1995, J. Gosling, Rich set of APIs and portable across platform through the use of JVM
● Development of C
● Martin Richards, around 60’s developed BCPL [Basic Combined Programming
Language]
● Enhanced by Ken Thompson and Introduced B language.
● C is originally developed between 1969 and 1973 at Bell Labs by Dennis Ritchie
and Kernighan. Closely tied to the development of the Unix operating system
● Standardized by the ANSI [American National Standards Institute] since 1989 and
subsequently by ISO [International Organization for Standardization].
Introduction to C
Let us discuss the applications of C before digging into C.
Features of C Language
Simple and Efficient:
The basic syntax style of implementing C language is very simple and easy to learn. This
makes the language easily comprehensible and enables a programmer to redesign or create a new
application. C is usually used as an introductory language to introduce programming to school
students because of this feature.
Fast:
It is a well-known fact that statically typed programming languages are faster than dynamic
ones. C is a statically typed programming language, which gives it an edge over other dynamic
language. Also, unlike Java and Python, which are interpreter-based, C is a compiler-based program.
This makes the compilation and execution of codes faster. Another factor that makes C fast is the
availability of only the essential and required features. Newer programming languages come with
numerous features, which increase functionality but reduce efficiency and speed. Since C offers
limited but essential features, the headache of processing these features reduces, resulting in increased
speed.
Portability:
Another feature of the C language is portability. To put it simply, C programs are machine-
independent which means that you can run the fraction of a code created in C on various machines
with none or some machine-specific changes. Hence, it provides the functionality of using a single
code on multiple systems depending on the requirement.
Extensibility:
You can easily (and quickly) extend a C program. This means that if a code is already written,
you can add new features to it with a few alterations. Basically, it allows adding new features,
functionalities, and operations to an existing C program.
Function-Rich Libraries:
C comes with an extensive set of libraries with several built-in functions that make the life of
a programmer easy. Even a beginner can easily code using these built-in functions. You can also
create your user-defined functions and add them to C libraries. The availability of such a vast scope
of functions and operations allows a programmer to build a vast array of programs and applications.
Pointers:
With the use of pointers in C, you can directly interact with memory. As the name suggests,
pointers point to a specific location in the memory and interact directly with it. Using the C pointers,
you can operate with memory, arrays, functions, and structures.
Recursion:
C language provides the feature of recursion. Recursion means that you can create a function
that can call itself multiple times until a given condition is true, just like the loops. Recursion in C
programming provides the functionality of code reusability and backtracking.
We will start exploring C Constructs in the upcoming lecture notes by solving some of the interesting
Problems!
Happy Coding!
Unit #: 1
Unit Name: Problem Solving Fundamentals
Topic: Introduction to GCC, Program Structure, C Programming Environment,
Errors in C program
Course objectives:
The objective(s) of this course is to make students
CObj1: Acquire knowledge on how to solve relevant and logical problems using computing
machine
CObj2: Map algorithmic solutions to relevant features of C programming language constructs
CObj3: Gain knowledge about C constructs and it's associated eco-system
CObj4: Appreciate and gain knowledge about the issues with C Standards and it's respective
behaviors
CObj5: Get insights about testing and debugging C Programs
Course outcomes:
At the end of the course, the student will be able to
CO1: Understand and apply algorithmic solutions to counting problems using appropriate C
Constructs
CO2: Understand, analyse and apply text processing and string manipulation methods using C
Arrays, Pointers and functions
CO3: Understand prioritized scheduling and implement the same using C structures
CO4: Understand and apply sorting techniques using advanced C contructs
CO5: Understand and evaluate portable programming techniques using preprocessor directives and
conditional compilation of C Programs
Team – PSWC,
Jan - May, 2022
Dept. of CSE,
PES University
1 Dept. of Computer Science and Engineering
2022
Problem Solving With C – UE23CS151B
Introduction to GCC
The original author of the GNU C Compiler is Richard Stallman, the founder of the GNU
Project. GNU stands for GNU's not Unix. The GNU Project was started in 1984 to create a
complete Unix-like operating system as free software, in order to promote freedom and
cooperation among computer users and programmers. The first release of gcc was made in 1987, as
the first portable ANSI C optimizing compiler released as free software. A major revision of the
compiler came with the 2.0 series in 1992, which added the ability to compile C++. The acronym
gcc is now used to refer to the “GNU Compiler Collection”
GCC has been extended to support many additional languages, including Fortran, ADA,
Java and Objective-C. Its development is guided by the gcc Steering Committee, a group
composed of representatives from gcc user communities in industry, research and academia
Features of GCC:
● A portable compiler, it runs on most platforms available today, and can produce output for
many types of processors
● Supports microcontrollers, DSPs and 64-bit CPUs
● It is not only a native compiler, it can also cross-compile any program, producing executable
files for a different system from the one used by gcc itself.
● Allows software to be compiled for embedded systems
● Written in C with a strong focus on portability, and can compile itself, so it can be adapted
to new systems easily
● It has multiple language frontends, for parsing different languages
● It can compile or cross-compile programs in each language, for any architecture Example:
Can compile an ADA program for a microcontroller or a C program for a supercomputer
● It has a modular design, allowing support for new languages and architectures to be added.
● It is free software, distributed under the GNU General Public License (GNU GPL), which
means we have the freedom to use and to modify gcc, as with all GNU software.
● gcc users have the freedom to share any enhancements and also make use of enhancements to
gcc developed by others.
1. Editing:
We enter the program into the computer. This is called editing. We save the source
program. Let us create first.c
#include <stdio.h>
int main()
{ // This is a comment
printf(“Hello Friends”);
return 0;
3 Dept. of Computer Science and Engineering
2022
Problem Solving With C – UE23CS151B
2. Pre-Processing:
In this stage, the following tasks are done:
To understand Pre-processing better, compile the above ‘first.c’ program using flag -E, which will
print the pre-processed output to stdout.
......
# 846 "/usr/include/stdio.h" 3 4
# 886 "/usr/include/stdio.h" 3 4
......
# 916 "/usr/include/stdio.h" 3 4
# 2 "first.c"
int main()
printf("HelloFriends");
return0;
In the above output, you can see that the source file is now filled with lots of information, but
still at the end of it we can see the lines of code written by us. Some of the observations are as
below.
• Comment that we wrote in our original code is not there. This proves that all the comments
are stripped off.
• The ‘#include’ is missing and instead of that we see whole lot of code in its place. So it is
safe to conclude that stdio.h has been expanded and literally included in our source file.
3. Compiling
Compilation refers to the process of converting a program from the textual source code
into machine code, the sequence of 1’s and 0’s used to control the central processing unit (CPU)
of the computer. Machine code is then stored in a file known as an executable file. C programs can
be compiled from a single source file or from multiple source files, and may use system libraries
and header files. Compiler processes statements written in a particular programming language and
converts them into machine language or "code" that a computer's processor uses. The translation
is compiled. The output is called an object file. There may be more than one translation. So, we
may get multiple object files. When compiling with ‘-c’, the compiler automatically creates an
object file whose name is the same as the source file, but with ‘.o’ instead of the original extension
gcc -c first.c
This command does pre-processing and compiling. Output of this command is first.o ->
Object file.
4. Linking
It is a computer program that takes one or more object files generated by a compiler and
combine them into one, executable program. Computer programs are usually made up of multiple
modules that span separate object files, each being a compiled computer program. This is the stage
at which all the linking of function calls with their definitions are done. Till stage, gcc doesn’t
know about the definition of functions like printf(). Until the compiler knows exactly where all of
these functions are implemented, it simply uses a place-holder for the function call. The definition
of printf() is resolved and the actual address of the function printf() is plugged in. We put together
all these object files along with the predefined library routines by linking. The output is called as
image or a loadable image with the name a.out [linux based] or a.exe[windows]
gcc first.o // Linking to itself
// If more than one object files are created after compilation, all must be mentioned with
gcc and linked here to get one executable.
If a file with the same name[a.out/a,exe] as the executable file already exists in the current
directory it will be overwritten. This can be avoided by using the gcc option -o. This is usually
given as the last argument on the command line.
gcc first.o -o PESU // loadable image/Output file name is PESU
In windows,
The following options of gcc are a good choice for finding problems in C and C++ programs.
Characteristics of a C program
- The language is case sensitive.
- The program is immune to indentation. ‘C’ follows the free format source code concept. The
way of presentation of the program to the compiler has no effect on the logic of the program.
However, we should properly indent the program so that the program becomes readable for
humans. When you prepare a new dish, I am sure you will also consider how you present it.
- The program has a well-defined entry point. Every program has to have an entry point called
main, which is the starting point of execution.
int main() // execution begins here
{ printf(“Hello Friends”);
return 0;
}
Think: Why the main function has the return type int? Why not something else ? Can we
have something else? Is it a good practice?
- A program in ‘C’ normally has one or more pre-processor directives. These start with a symbol #.
One of the directives is “include”.
• #include <stdio.h>
The above line asks the translator to find the file whose name is stdio.h at some location in our file
system and read and expand it at that point in the ‘C’ code.
- A program in ‘C’ has to have a function called main. It is invoked(called) from some external
agency – like ourshell. It is the duty of this function to tell the caller whether it succeeded or
failed. So, by convention, main returns 0 on success and non-zero on failure. Refer to coding
example_1 for more details.
- A block contains a number of statements. Each statement ends in a semicolon. This symbol ; plays
the role of statement terminator
Program structure
Consists of different sections of which few are optional and other few are mandatory sections.
Refer to the below diagram.
Documentation Section: Optional but always good to have. Usually contains the information
about the code in terms of comments
Comments */
Link Section: Provides instructions to the compiler to link functions from the system library such
as using the #include directive. Basically Header files that are required to execute a C program are
included in the Link section.
Main function Section: Every C program must have one main function section. Contains two
parts: the declaration part and the executable part. Declaration part declares all the variables
used in the executable part. Executable part: There is at least one statement in the executable part.
These two parts must appear between the opening and closing braces. The program execution
begins at the opening brace and ends at the closing brace. The closing brace of the main function
is the logical end of the program. All statements in the declaration and executable part end with a
semicolon.
Sub program section: Optional section and contains user defined functions. We will discuss in
Unit – 2.
If someone wants to know whether the recently executed process is executed successfully or not,
this return value is very helpful.
After you get the output, use below commands to know what the return value of recently executed
process.
echo %ERRORLEVEL% // in windows
echo $? // in linux based systems
Must return 0 to represent the success[by convention 0 is success]. Modify the code as below.
int main() // this code is saved as main.c
{
printf(“welcome to main function in C”);
}
Repeat the same steps as mentioned in the first case, there is no way to get the success or failure
info about the recently executed process. Results in some random value other than 0.
Error(s) in C Code
Coding Exampe_3:
#include<stdio.h>
int main()
{
printf("hello friends); //" missing at the end
printf("%d",12/2) // ; missing at the end of statement
return 0;
}
Coding Exampe_4:
#include<stdio.h>
int main()
{ Printf("hello friends"); // P is capital
printf("%d",12/2);
return 0;
}
Errors that occur during the execution (or running) of a program are called Runtime Errors.
These errors occur after the program has been compiled and linked successfully. When the code is
compiled, object file(.o file) will be created. Then during linking, executable will be created.
When you run a loadable image, code terminates throwing an error. Generally occurs due to some
illegal operation performed in the program. Examples of some illegal operations that may produce
runtime errors are: Dividing a number by zero, trying to open a file which is not created and lack
of free memory space.
Coding Exampe_5:
#include<stdio.h>
int main()
{
printf("hello friends");
printf("%d",12/0); // Observe
12/0printf("bye friends");
return 0;
}
Logical Error:
Even though the code seems error free, the output generated is different from the expected
one. Logical error occurs when the code runs completely but the expected output is not same as the
actual output.
Coding Example_6:
#include<stdio.h>
int main ()
{
printf("%d",12/21); //By Mistake entered 21
//instead of 2
return 0;
}
Warning(s) in C:
Warnings are diagnostic messages that report constructions which are not inherently
erroneous but which are risky or suggest there may have been an error or crash in future.
The compiler distinguishes between error messages, which prevent successful compilation, and
warning messages which indicate possible problems but do not stop the program from compiling.
It is very dangerous to develop a program without checking for compiler warnings. If there are
any functions which are not used correctly they can cause the program to crash or produce
incorrect results. Turning on the compiler warning option ‘-Wall’ for safety will catch many of the
commonest errors which occur in c programming.
C and C++ compilers are notoriously bad at reporting some common programmer mistakes
by default, such as:
• arguments in printf and scanf families not matching the format string
Most compilers understand options like -Wall, -Wpedantic and -Wextra. -Wall is essential
and all the rest are recommended (note that, despite its name, -Wall only enables the most
important warnings, not all of them). These options can be used separately or all together.
Error vs warning
Errors report problems that make it impossible to compile your program. GCC reports errors
with the source file name and line number where the problem is apparent. Warnings report other
unusual conditions in your code that may indicate a problem, although compilation can
proceed.
Coding Example_7:
#include<stdio.h>
int main()
int a;
scanf("%d",a);
return 0;
Without -wall option, there is no warning or error. But results in Runtime Error when the code is
run using the executable.
The above code compilation using –Wall is as below. This creates the object file. But at runtime,
it fails to execute
Unit #: 1
Unit Name: Problem Solving Fundamentals
Topic: Simple Input functions in C
Course objectives:
The objective(s) of this course is to make students
CObj1: Acquire knowledge on how to solve relevant and logical problems using computing
machine
CObj2: Map algorithmic solutions to relevant features of C programming language constructs
CObj3: Gain knowledge about C constructs and it's associated eco-system
CObj4: Appreciate and gain knowledge about the issues with C Standards and it's respective
behaviors
CObj5: Get insights about testing and debugging C Programs
Course outcomes:
At the end of the course, the student will be able to
CO1: Understand and apply algorithmic solutions to counting problems using appropriate C
Constructs
CO2: Understand, analyse and apply text processing and string manipulation methods using C
Arrays, Pointers and functions
CO3: Understand prioritized scheduling and implement the same using C structures
CO4: Understand and apply sorting techniques using advanced C contructs
CO5: Understand and evaluate portable programming techniques using preprocessor directives and
conditional compilation of C Programs
Team – PSWC,
Jan - May, 2022
Dept. of CSE,
PES University
int main()
{
char ch = 'p'; // ch is a variable of type char and it can store only one character at a time.
//Value for a character variable must be within single quote. //
printf("Ch is %c\n",ch);// p
//char ch1 = 'pqrs';// TERRIBLE
CODEprintf("Ch is %c\n",ch);// s
/*
char x; char y;
scanf("%c", &x);
scanf("%c", &y);
printf("x:%c y:%c\n", x, y);
*/
x = getchar(); y = getchar(); putchar(x);
putchar(y); printf("%d", y);
return 0;
}
// If I enter P<newline>, x becomes P and y becomes newline
// scanf and printf : generic; not simple
// getchar and putchar : not generic; read /write a char; simple
// If I enter p<space>q, q will not be stored in y. Only space is stored. This can be avoided using
fflush(stdin) function between two getchar function calls. This function clears the key board
buffer.
// fflush(stdin) –windows
Note: While using scanf for reading character input, care should be taken to handle White
Spaces and Special Characters handling buffering problem
Unit #: 1
Unit Name: Problem Solving Fundamentals
Topic: Basic constructs in C – Identifiers, Keywords, Variables and Data types,
Range of values
Course objectives:
The objective(s) of this course is to make students
CObj1: Acquire knowledge on how to solve relevant and logical problems using computing
machine
CObj2: Map algorithmic solutions to relevant features of C programming language constructs
CObj3: Gain knowledge about C constructs and it's associated eco-system
CObj4: Appreciate and gain knowledge about the issues with C Standards and it's respective
behaviors
CObj5: Get insights about testing and debugging C Programs
Course outcomes:
At the end of the course, the student will be able to
CO1: Understand and apply algorithmic solutions to counting problems using appropriate C
Constructs
CO2: Understand, analyse and apply text processing and string manipulation methods using C
Arrays, Pointers and functions
CO3: Understand prioritized scheduling and implement the same using C structures
CO4: Understand and apply sorting techniques using advanced C contructs
CO5: Understand and evaluate portable programming techniques using preprocessor directives and
conditional compilation of C Programs
Team – PSWC
Jan-May, 2022
Dept. of CSE
PES University
1 Dept. of Computer Science and Engineering
2022
Problem Solving With C – UE23CS151B
Before we start with Problem Solving sessions, let us list few counting problems
Basic constructs in C
C program consists of various tokens and a token can be any identifier -> a keyword,
variable, constant, a string literal, or a symbol. For example, the following C statement consists
of five tokens.
printf("HelloFriends");
The individual tokens are −
printf
(
"HelloFriends"
)
;
Identifiers
An identifier is a name used to identify a variable, function, or any other user-defined
item. An identifier starts with a letter A to Z, a to z, or an underscore '_' followed by zero or
more letters, underscores and digits (0 to 9). C does not allow few punctuation characters such as
#, @ and % within identifiers. As C is a case-sensitive programming language, Manpower and
manpower are two different identifiers in C.
Here are some examples of acceptable identifiers
_sum stud_name a_123 myname50 temp j
count123
Keywords
The keywords are identifiers which have special meaning in C and hence cannot be used
as constants or variables. There are 32 keywords in C Language.
Variables
This is the most important concept in all languages. Variable is a name given to a storage
area that our programs can manipulate. It has a name, a value, a location and a type. It also
has something called life, scope, qualifiers etc. Variables are used to store information to be
referenced and manipulated in a computer program. It provides a way of labeling data with a
descriptive name, so our programs can be understood more clearly by the reader and ourselves. It
is helpful to think of Variables as containers that hold data or information. Purpose of
Variables is to label and store data in memory, which then can be used throughout the
program.
Sometimes, the runtime makes variables with no names. These are called temporary
variables. We cannot access them by name as we have no name in our vocabulary. A variable has
a type. In ‘C’, type should be specified before a variable is ever used. We declare the variable with
respect to type before using it. We cannot declare the variable more than once.
The type of a variable can never change during the program execution. The type decides
what sort of values this variable can take and what operations we can perform. Type is a compile
time mechanism. The size of a value of a type is implementation dependent and is fixed for a
particular implementation.
Variable is associated with three important terms: Declaration, Definition and Initialization.
Data Types
1) Memory allocation
2) Range of values allowed
3) Operations that are bound to this type
4) Type of data to be stored
5 Dept. of Computer Science and Engineering
2022
Problem Solving With C – UE23CS151B
Size of a type:
The size required to represent a value of that type. Can be found using an operator called
sizeof. The size of a type depends on the implementation. We should never conclude that the
size of an int is 4 bytes. Can you answer this question –How many pages a book has? What is the
radius of Dosa we get in different eateries?
The sizeof operator is the most common operator in C. It is a compile-time unary operator and
is used to compute the size of its operand. It returns the size of a variable/value/type. It can be
applied to any data type, float type, pointer type variables When sizeof() is used with the data
types, it simply returns the amount of memory allocated to that data type. The output can be
different on different machines like a 32-bit system can show different output while a 64-bit
system can show different of same data types
The size of a type is decided on an implementation based on efficiency. C standards follow the
below Rules.
sizeof(short int)<=sizeof(int)<=sizeof(long int)<=sizeof(long long int)<=
sizeof(float)<=sizeof(double)<=sizeof(long double)
Literals
Literals are the constant values assigned to the constant variables. There are four types
of literals that exist in c programming:
1. Integer literal
2. Float literal
3. Character literal
4. String literal – Will be discussed in Unit – 2
Constant is basically a named memory location in a program that holds a single value throughout
the execution of that program
Integer Literal: It is a numeric literal that represents only integer type values. Represents the value
neither in fractional nor exponential part. Can be specified in the following three ways
Decimal number (base 10): It is defined by representing the digits between 0 to 9.
Example: 1,3,65 etc
Octal number (base 8): It is defined as a number in which 0 is followed by digits such as
0,1,2,3,4,5,6,7. Example: 032, 044, 065, etc
Hexadecimal number (base 16): It is defined as a number in which 0x or 0X is followed by
the hexadecimal digits (i.e., digits from 0 to 9, alphabetical characters from (a-f) or (A-F))
Example: 0XFE, oxfe etc..
7 Dept. of Computer Science and Engineering
2022
Problem Solving With C – UE23CS151B
Float Literal: It is a literal that contains only floating-point values or real numbers. These real
numbers contain the number of parts such as integer part, real part, exponential part, and
fractional part. The floating-point literal must be specified either in decimal or in exponential
form.
Decimal form: Must contain decimal point, real part, or both. If it does not contain either
of these, then the compiler will throw an error. The decimal notation can be prefixed either by '+' or
'-' symbol that specifies the positive and negative numbers. Example: +9.5, -18.738
Exponential form: The exponential form is useful when we want to represent the number,
which is having a big magnitude. It contains two parts, i.e., mantissa and exponent. Example: the
number is 3450000000000, and it can be expressed as 3.45e12 in an exponential form
Rules for creating an exponential notation: The mantissa can be specified either in decimal or
fractional form An exponent can be written in both uppercase and lowercase, i.e., e and E.
We can use both the signs, i.e., positive and negative, before the mantissa and exponent.
Spaces are not allowed.
Character Literal: Contains a single character enclosed within single quotes. If we try to store
more than one character in a character literal, then the warning of a multi-character character
constant will be generated. A character literal can be represented in the following ways:
It can be represented by specifying a single character within single quotes.
Example: 'x', 'y', etc.
We can specify the escape sequence character within single quotes to represent a character literal.
Example, '\n', '\t', '\b'.
We can also use the ASCII in integer to represent a character literal.
Example: the ascii value of 65 is 'A'.
The octal and hexadecimal notation can be used as an escape sequence to represent a character
literal.
Example, '\043', '\0x22'.
Think! What is the maximum and minimum integer value I can store in a variable?
The limits.h header file determines various properties of the various variable types.
The macros defined in this header, limits the values of various variable types like char, int and long.
These limits specify that a variable cannot store any value beyond these limits The values indicated
in the table are implementation-specific and defined with the #define directive, but these values may
not be any lower than what is given in the table.
The float.h header file of the c Standard Library contains a set of various platform-
dependent constants related to floating point values. These constants are proposed by ANSI C.
They allow making more portable programs.
Coding Example_1:
#include<stdio.h>
#include<limits.h>
#include<float.h>
int main()
{
int a = 8;
char p = 'c';
double d = 89.7;
int e = 0113; // octal literal
/*printf("%d\n",e);
printf("%o\n",e);
printf("%X\n",e);
printf("%x\n",e);
*/
//int h = 0xRG; // error
int h = 0xA;
//printf("%d",h);
int i = 0b111;
//printf("%d",i);
//printf("%d %d %d %d\n",sizeof(int),sizeof(short int),sizeof(p),sizeof(long));
//int g = 787878787888888787;
int g = 2147483649;
/*printf("%d\n",INT_MAX);
printf("%d\n",INT_MIN);
printf("%d\n",INT_MIN);
printf("%d\n",INT_MIN);*/
printf("%d\n",CHAR_MAX);
printf("%g\n",DBL_MAX);
printf("%g\n",FLT_MAX);
printf("%d\n",g);
return 0;
}
Unit #: 1
Unit Name: Problem Solving Fundamentals
Topic: Introduction to Single character input and output
Course objectives:
The objective(s) of this course is to make students
CObj1: Acquire knowledge on how to solve relevant and logical problems using computing
machine
CObj2: Map algorithmic solutions to relevant features of C programming language constructs
CObj3: Gain knowledge about C constructs and it's associated eco-system
CObj4: Appreciate and gain knowledge about the issues with C Standards and it's respective
behaviors
CObj5: Get insights about testing and debugging C Programs
Course outcomes:
At the end of the course, the student will be able to
CO1: Understand and apply algorithmic solutions to counting problems using appropriate C
Constructs
CO2: Understand, analyse and apply text processing and string manipulation methods using C
Arrays, Pointers and functions
CO3: Understand prioritized scheduling and implement the same using C structures
CO4: Understand and apply sorting techniques using advanced C constructs
CO5: Understand and evaluate portable programming techniques using preprocessor directives and
conditional compilation of C Programs
Team – PSWC,
Jan - May, 2022
Dept. of CSE,
PES University
A Character refers to a single input . It occupies a single byte. We code English alphabets A as 65, B
as 66, Z as 90, a as 97 and so on in a coding scheme called ASCII.
Single Character Input-Output Functions
1) scanf and printf
printf(“%c”, x);
scanf(“%c”, &x);
c=getchar();
putchar(c);
3) getc and putc (will be discussed in unit 4)
4) getch , getche and putch
C programming treats all the devices as files. So devices such as the display are addressed in
the same way as files and the following three files are automatically opened when a program executes
to provide access to the keyboard and screen.
Coding Example
#include <stdio.h>
int main ()
{
3 Dept. of Computer Science and Engineering
2022
Problem Solving With C – UE23CS151B
char ch;
while((ch = getc(stdin)) != EOF)
{
putc(ch, stdout);
}
}
In the above program the getc() function reads character from the standard input file (stdin). The
putc() function displays to the standard output file(stdout). This code is just an additional information
to know how getc and putc are used. We will be looking at these functions again in detail under File
processing topic, Unit 4.
getch() , getche() and putch() functions are called as non-standard functions since they are not
part of standard library and ISO C(certified c programming language). Available in conio.h.
getch() and getche() reads a character from the keyboard and copies it into memory area which is
identified by the variable ch. No arguments are required for this function. getch and getche() function
doesn’t wait for the user to press enter/return key. In the getch() function, the typed character will not
be echoed(displayed) on the screen and in getche() function the typed character will be
echoed(displayed) on the screen.
Syntax:
ch=getch()
or
ch=getche();
putch():
putch function outputs a character stored in the memory using a variable on the output screen.
Syntax:
putch(ch);
Coding Example:
int main()
{
char ch;
ch = getch();
putch(ch);
return 0;
}
Output: When user enters the character y
Coding Example:
int main()
{
char ch;
ch = getche();
putch(ch);
return 0;
}
Output: When user enters the character y
Unit #: 1
Unit Name: Problem Solving Fundamentals
Topic: Operators in C
Course objectives:
The objective(s) of this course is to make students
CObj1: Acquire knowledge on how to solve relevant and logical problems using computing
machine
CObj2: Map algorithmic solutions to relevant features of C programming language constructs
CObj3: Gain knowledge about C constructs and it's associated eco-system
CObj4: Appreciate and gain knowledge about the issues with C Standards and it's respective
behaviors
CObj5: Get insights about testing and debugging C Programs
Course outcomes:
At the end of the course, the student will be able to
CO1: Understand and apply algorithmic solutions to counting problems using appropriate C
Constructs
CO2: Understand, analyse and apply text processing and string manipulation methods using C
Arrays, Pointers and functions
CO3: Understand prioritized scheduling and implement the same using C structures
CO4: Understand and apply sorting techniques using advanced C contructs
CO5: Understand and evaluate portable programming techniques using preprocessor directives and
conditional compilation of C Programs
Team – PSWC,
Jan - May, 2022
Dept. of CSE,
PES University
Operator
An operator is a symbol that tells the compiler to perform specific mathematical or logical
functions. Operator is a symbol used for calculations or evaluations
Classification of Operators:
Based on the number of operands.
1) Unary +, -, ++, --, size of ,&, *,
2) Binary +, -, *, /, %
3) Ternary ?:
Arithmetic Operators in c
These operators are used to perform arithmetic/mathematical operation and give us results
accordingly.
+ (Plus) – Give sum as a result. Example: 1+2=3
* (Asterisk) – Used for multiplication and given the product as a result. Example: 2*2=4
/ (Forward slash) – Used for division and give quotient as a result. Example: 10/2 = 5
+ and –can also be used as unary operators –in such case, the operator is prefixed –appears to
the left of the operand.
If the operands are int for /, the result is int quotient obtained truncation of the result. The operator
If the operands are mixed types(int and double) in operations + -* /, the result is of type double.
#include <stdio.h>
int main()
printf("%d%d%d%d",2+3,4-2,4*2,5/2); // 5,2,8,2
// mixed mode
return 0;
When ++ and --are used in stand-alone expression, pre and post increment and decrement
doesn't make difference.
#include<stdio.h>
int main()
{ int i=5;
int j=5;
++i;// i++;
j--;// --j;
return 0;
int main()
//b=++a;// First increment and then use the value in the expression
// b is 35 and a is 35
return 0;
Relational Operators
Used to check the relationship between the two operands. If the relation is true, it returns 1.
If the relation is false, it returns the value 0. Relational operators are used in decision-making and
loops constructs. Programming language like C which doesn’t support Boolean data type return
result as 1 or 0.
Greater than (>) – Returns true (1) when the left operand value is greater than the right
operand value. Example: 15 >13 is evaluated to 1.
Less than (<): Returns true(1) when the left operand value is less than the right operand value
else false(0). Example: 15 <13 is evaluated to 0.
Greater than or equal to (>=): Return true(1) when the left operand value is greater than or
equal to the right operand value. Example: 15 >=13 is evaluated to 1.
Less than or equal to (<=): Return true(1) when the left operand value is less than or equal to
the right operand. Example: 15 <= 13 is evaluated to 0.
Equal to (==): Returns true when left operand value is equal to right operand value. Example:
5 == 5 is evaluated to 1.
Not Equal to (!=): Return true when left operand value is not equal to right operand. Example:
2 != 3 is evaluated to 0
The result of relational operation is 1 or 0. 1 stands for true and 0 for false. The relational
operators should not be cascaded – not logically supported in C.
Bit-wise Operators
Used for performing bitwise operations on bit patterns or binary numerals that involve the
manipulation of individual bits. Bitwise operators always evaluate both operands. Bitwise
operators work on bits and perform bit-by-bit operations.
|(OR): Example: a | b
Few inputs about carrying out arithmetic opertion using bit wise operators
* multiply variable n by 2
n << 1
* check whether n is odd
n&1
* swap two variables a and b
a=a^b
b=a^b
a=a^b
* check whether ith bit in variable n is 1
n & (1 << i) : 0 implies not set and non 0 implies set
* set the ith bit in n
n = n | 1 << i
* clear the ith bit in n
n = n & ~(1 << i)
Assignment Operators
Used to assign a new value to a variable Assignment operators can also be used for logical
operations, bitwise logical operations or operations on integral operands and Boolean operands.
= Simple assignment operator: Assigns values from right side operands to left side operands.
Example: C = A + B will assign the value of A + B to C
+= Add AND assignment operator: It adds the right operand to the left operand and assigns the
result to the left operand.
Example: C += A is equivalent to C = C + A
-= Subtract AND assignment operator: It subtracts the right operand from the left operand and
assigns the result to the left operand.
Example: C -= A is equivalent to C = C – A
*= Multiply AND assignment operator: It multiplies the right operand with the left operand and
assigns the result to the left operand.
Example: C *= A is equivalent to C = C * A
/= Divide AND assignment operator: It divides the left operand with the right operand and assigns
the result to the left operand.
Example: C /= A is equivalent to C = C / A
%=: Modulus AND assignment operator: It takes modulus using two operands and assigns the
result to the left operand.
Example: C %= A is equivalent to C = C % A
Ternary/Conditional operator
?: Conditional Operator and it requires three operands. E1 ? E2 : E3 where E1, E2 and E3 are
expressions. The expression E1 is first evaluated. If it is true, then the value of the expression is E2
else it is E3.
Coding Example_5: Demo of ?:
int main()
{
int a= 10; int b = 20;
printf("%d\n",(a>b)?a:b); //20
(a>b)? printf("%d",a):printf("%d",b); //20
printf("%d",(a>b)?a:b); //20
return 0;
}
Logical Operators
Logical Operators are operators that determine the relation between 2 or more operands and
return a specific output as a result of that relation.
NOT (!) – Used to negate a Logical statement.
AND (&&) and OR (||) – Used to combine simple relational statements into more complex
Expressions. In ‘C’, 0 is false and any non-zero value is true. C follows short circuit evaluation.
Evaluation takes place left to right and evaluation stops as soon as the truth or falsehood of the
expression is determined.
Coding Example_6: //
#include<stdio.h>
int main()
{
int a = 11;
printf("%d",a++==12 | | a==12); // 1
10 Dept. of Computer Science and Engineering
2022
Problem Solving With C – UE23CS151B
printf("\n%d",a); // 12
return 0;
}
Expression in C
An expression in C is a combination of operands and operators. Expressions compute a
single value stored in a variable. The operator denotes the action or operation to be performed.
The operands are the items to which we apply the operation.
An expression can be defined depending on the position and number of its operator and
operands.
Infix Expression: Operator is used between the operands
a=x+y
Postfix Expression: Operator is used after the operands
xy+
Prefix Expression: Operator is used before the operands
+xy
Unary Expression: One operator and one operand
++x
Binary Expression: One operator and two operands
x+y
Arithmetic Expression: It consists of arithmetic operators ( + , - , * , and / ) and computes values of
int, float, or double type.
Relational Expression: It consists of comparison operators (> , < , >= , <= , === , and !== ) and
computes the answer in true (1) or false (0)
Logical Expression: It consists of logical operators (&&, ||, and !) and combines relational
expressions to compute answers in true (1) or false (0)
Conditional Expression: It consists of conditional statements that return true(1) if the condition is
met and else false(0)
Pointer Expression: It consists of an ampersand (&) operator and returns address values.
Bitwise Expression: It consists of bitwise operators ( >>, <<, ~, &, |, and ^ ) and performs
operations at the bit level.
2. Evaluation of operators:
This follows the rules of precedence and if more than one operator has the same level of
precedence, follows the rules of association.
Table of operator Precedence and Associativity is shown below and Link for reference:
http://web.cse.ohio-state.edu/~babic.1/COperatorPrecedenceTable.pdf
Does the first rule have any effect on our programs? Yes. If affects our programs if the expressions
we use are not pure and have side effects.
All assignments have side effects.
Let us consider an example.
a = 10;
b = a * a++;
The value of a++ is the old value of a and therefore 10. What is the value of the leftmost a? Is the
value evaluated before incrementing or after incrementing? It depends on the compiler andthe
compiler options. So value of leftmost a is undefined. So, value of b is undefined.
// 10 * 10 => 100
// 11 * 10 => 110
//undefined; depends on the order of evaluation of operands
// bad code
Unit #: 1
Unit Name : Problem Solving Fundamentals
Topic: Control Structures
Course objectives:
The objective(s) of this course is to make students
CObj1: Acquire knowledge on how to solve relevant and logical problems using computing
machine
CObj2: Map algorithmic solutions to relevant features of C programming language constructs
CObj3: Gain knowledge about C constructs and it's associated eco-system
CObj4: Appreciate and gain knowledge about the issues with C Standards and it's respective
behaviors
CObj5: Get insights about testing and debugging C Programs
Course outcomes:
At the end of the course, the student will be able to
CO1: Understand and apply algorithmic solutions to counting problems using appropriate C
Constructs
CO2: Understand, analyse and apply text processing and string manipulation methods using C
Arrays, Pointers and functions
CO3: Understand prioritized scheduling and implement the same using C structures
CO4: Understand and apply sorting techniques using advanced C contructs
CO5: Understand and evaluate portable programming techniques using preprocessor directives and
conditional compilation of C Programs
Team – PSWC,
Jan - May, 2022
Dept. of CSE,
PES University
Introduction
A program is nothing but the execution of sequence of one or more instructions. It is most of
the time desirable to alter the sequence of the statements in the program depending upon certain
circumstances or as per the logic. Involves decision making to see whether a particular condition
has been met or otherwise and direct the computer to execute certain statements accordingly. Based
on logic, it is becomes necessary to alter the flow of a program, test the logical conditions and
control the flow of execution as per the selection of these conditions that can be placed in the
program using decision-making statements
Control Structures
C programming language supports a few looping and a few selection structures. It may also
support some unconventional control structures.
1) Looping structures:
-while statement
-for statement
-do … while statement
2) Selection structures/ Decission Making/ Conditional structures:
- Simple if Statement
- if – else Statement
- Nested if-else statement
- else if Ladder
- switch statement
3) Unconditional structures:
- goto statement
- break Statement
- continue Statement
- return Statement
Looping
Let us start the discussion with the while statement. The while statement starts with the
keyword while and is followed by an expression in parentheses and is followed by a statement
or a block.
while(Expression)
{
Statement(s); // block
}
The expression of the while is evaluated. It could be non-zero or zero. If it is non-zero, the body of
the while is executed and again the control comes back to the expression of the while. If the
expression of the while is false, the loop is exited.
The loop evaluates the Test Expression inside the parentheses(). If Test Expression is TRUE,
statements inside the body of while loop are executed. For looping to continue Test Expression
has to be evaluated again as TRUE; terminated if the evaluation results in FALSE.
It is a good programming practice to always use a block even if only one statement is in the body
of the loop. The body of the while loop is executed 0 or more times as the condition to be
checked is at the top.
Version 2: Displays 5 4 3 2 1. But the program layout does not indicate the logic structure of
the program. Always indent the code to indicate the logic structure
int n = 5; while(n){
printf("%d ", n);
n = n –1;}
Version 4: Observe the value of n-- is the old value of n. When n is 1, the value of n
becomes 0but thedecrement operator returns 1.
int n = 5;
while(n)
{
printf("%d ", n--); // 5 4 3 2 1
}
Version 7:
int n = 5;
while(--n)
{
printf("%d ", n); // 4 3 2 1
}
Compare the last two versions. In the first case, the loop is executed n times and in the second
the loopis executed n –1 times. In the first case, the value of n is -1 and in the second case, it is 0.
// modification
There is clearly some initialization, some processing and some modification at the end of the
loop. In such cases, we may want to use the for statement.
// e1 : initialization
// e2 : condition
// e3 : modification
• Can you have initialization outside the for loop and modification inside the body of the loop?
{
sum += i;
}
‘C’ for statement is same as the ‘C’ while statement –we say they are isomorphic. It is a
question of choice and style while writing programs in ‘C’.
do –while loop:
The body of do...while loop is executed at least once. For loop to continue, the test expression is
evaluated for TRUE; terminated if the evaluation results in FALSE.
Selection statements
If the expression of if is true we execute the block following if, otherwise execute the else
part if any. It is always preferred to use a block even if there is a single statement in the if and else
portions.
Coding Example_4: Classify triangles given the3 sides as equilateral, isosceles or scalene. This is
one possible solution.
int count = 0;
scanf("%d%d %d", &a, &b, &c);
if(a == b) ++count;
if(b == c) +count;
if(c == a) +count;
if(count == 0) printf("scalene\n");
if(count == 3) printf("equi\n");
if(count == 1) printf("iso\n");
Compare every pair of sides and increment the count each time –initialized to 0 on start. Can the
count be 2?
The value of count is compared with case clauses. This comparison decides the entry into the
switch and not exit from there. To avoid the code fall through, we use break statement. The rule of
‘C’ is “break if switch”.
If we do not use the break statement, all statements after the matching label are also
executed. These switch statements are more efficient compared to normal if statements. But can
you include else part of if in switch case? -- Yes using default. But the default clause inside the
switch statement is optional.
Coding Example_5: Inclusion of default in switch case to have the else facility
int a,b,c;
scanf("%d%d%d",&a,&b,&c);
int count = 0;
if(a == b) count++;
if(b == c) count++;
if(c == a) count++;
switch(count)
case 1:printf("iso");break;
case 3:printf("equi");break;
case 0:printf("scalene");break;
printf("switch ended");
Coding Example_6: The count value cannot be anything other than 0,1 or 2. So change in the
default case as below.
switch(count)
{
case 1: printf("iso");break;
case 3: printf("equi");break;
default: printf("scalene");break;
}
printf("switch ended");
Example: The three digit Armstrong number is 153. The sum of cubes of digits is same as the
number. The program shows how not to write programs. We have a loop on hundredth digit, a
loop on tenth digit and a loop on unit digit. We cube the digits, find the sum, form the number
using these digits and compare the sum with thenumber formed.
#include<stdio.h>
int main()
{ int h,t,u,hc,tc,uc;
int number;
for(h = 0; h<10;h++)
{
for(t = 0; t< 10;t++)
{
for(u = 0;u< 10;u++)
{
hc = h*h*h;
tc = t*t*t;
uc = u*u*u;
int sum = hc+tc+uc;
number = h*100 + t*10 + u*1;
if(number == sum)
printf("%d\n",number);
}
}
}
return 0;
}
The above code is generating only few Armstrong numbers. Not printing all. Change the
implementation to print all Armstrong numbers between 0 and 999. Think about adding ifs to
check and count the number the digits
Also, think how many multiplications do we do for cubing? Should we repeatedly evaluate cube
of t in the inner loop when it is not changing. Rearrange the code. Put the statements in the right
blocks. You will be able to reduce the number of multiplications for cubing to approximately
1/3rd of what it is now.
Happy Coding!!
Unit #: 1
Unit Name: Problem Solving Fundamentals
Topic: Problems on basic constructs in C and control structures
Course objectives:
The objective(s) of this course is to make students
CObj1: Acquire knowledge on how to solve relevant and logical problems using computing
machine
CObj2: Map algorithmic solutions to relevant features of C programming language constructs
CObj3: Gain knowledge about C constructs and it's associated eco-system
CObj4: Appreciate and gain knowledge about the issues with C Standards and it's respective
behaviors
CObj5: Get insights about testing and debugging C Programs
Course outcomes:
At the end of the course, the student will be able to
CO1: Understand and apply algorithmic solutions to counting problems using appropriate C
Constructs
CO2: Understand, analyse and apply text processing and string manipulation methods using C
Arrays, Pointers and functions
CO3: Understand prioritized scheduling and implement the same using C structures
CO4: Understand and apply sorting techniques using advanced C contructs
CO5: Understand and evaluate portable programming techniques using preprocessor directives and
conditional compilation of C Programs
Team – PSWC,
Jan - May, 2022
Dept. of CSE,
PES University
List of problems
1. You are transporting some boxes through a tunnel whose height is only 41 feet. Given the length,
width, and height of the box, calculate the volume of those boxes and check if they pass through
the tunnel.
Ex: Input = 5, 5, 5 Output = 125
Input = 1, 2, 40 Output = 80
Input = 10, 5, 41 Output = Can’t Pass!
2. Given the number of rows, print a hollow diamond using star symbol: Ex: Input = 5
3. Check whether the given number is divisible by the sum of its digits. Display appropriate
message
4. Write a C program to find the eligibility of admission for a professional course based on the
following criteria: Eligibility Criteria : Marks in Maths >=65 and Marks in Physics >=50 and
Marks in Chemistry>=55 and Total in all three subjects >=190 or Total in Maths and Physics
>=140
5. Write a C program to print the prime numbers within the given input range. Ex. if user gives
10 and 50 as the input range, then the program must display all the prime numbers between the
range 10 and 50 (i.e. 11 13 17 19 23 29 31 37 41 43 47)
6. Construct a menu-based calculator to perform arithmetic operations (Add, Subtract,
Multiply,Divide) on complex numbers.
7. Given a number N, check whether it is a palindrome numbers or not. Ex. 121 , 3443 are
palindromes whereas 123,4531 are not plaindromes
8. Write a program to print all odd numbers between the two limits “m” and “n” (both m and n is
given as an integer inputs by the user and m<n) and print all odd numbers excluding those which
are divisible by 3 and 5.
Solution:
#include<stdio.h>
int main()
{
int h, w, l;
printf("Enter the length, width, height: ");
scanf("%d %d %d", &l, &w, &h);
if(h >= 41)
{
printf("Can't pass!");
}
else
{
int volume = l*w*h;
printf("%d", volume);
}
return 0;
}
2. Given the number of rows, print a hollow diamond using star symbol: Ex: Input = 5
Solution:
#include<stdio.h>
int main()
{
int n;
printf("Enter number of rows: ");
scanf("%d",&n);
for(int i=1; i<= n; i++)
{
for(int j=i; j<= n; j++)
printf(" ");
for(int k = 1; k <= 2*i-1; k++)
{
if(k == 1 || k == (2*i-1))
printf("*");
else
printf(" ");
}
printf("\n");
}
for(int i = n-1; i>=1; i--)
{
4 Dept. of Computer Science and Engineering
2022
Problem Solving With C – UE23CS151B
{
int r = n % 10;
sum = sum + r;
n = n / 10;
}
//check if sum of digits divides the number
if(temp%sum == 0)
printf("Divisible");
else
printf("Not Divisible");
}
return 0;
}
4. Write a C program to find the eligibility of admission for a professional course based on the
following criteria: Eligibility Criteria : Marks in Maths >=65 and Marks in Physics >=50 and
Marks in Chemistry>=55 and Total in all three subjects >=190 or Total in Maths and Physics
>=140
Solution:
#include <stdio.h>
int main()
{
int p,c,m,total,math_phy;
printf("Input the marks obtained in Physics, Chemistry, Math :");
scanf("%d %d %d",&p, &c, &m);
total = m + p + c;
math_phy = m + p;
printf("Total marks of Maths, Physics and Chemistry : %d\n",m+p+c);
printf("Total marks of Maths and Physics : %d\n",m+p);
if (m>=65)
if(p>=50)
if(c>=55)
if((total)>=190||(math_phy)>=140)
printf("The candidate is eligible for admission.\n");
else
printf("The candidate is not eligible.\n");
else
printf("The candidate is not eligible.\n");
else
printf("The candidate is not eligible.\n");
else
printf("The candidate is not eligible.\n");
return 0;
}
5. Write a C program to print the prime numbers within the given input range. Ex. if user gives 10
and 50 as the input range, then the program must display all the prime numbers between the
range 10 and 50 (i.e. 11 13 17 19 23 29 31 37 41 43 47)
#include <stdio.h>
int main()
{
int low, high, i, flag;
printf("Enter two numbers(intervals): ");
scanf("%d %d", &low, &high);
if (flag == 0)
printf("%d ", low);
++low;
}
return 0;
}
if (img >= 0)
printf("Difference = %d + %di", real, img);
else
printf("Difference = %d %di", real, img);
}
else if (choice == 3)
{
int real = a*c - b*d;
int img = b*c + a*d;
if (img >= 0)
printf("Product = %d + %di", real, img);
else
printf("Product = %d %di", real, img);
}
else if (choice == 4)
{
if (c == 0 && d == 0)
printf("Division by 0 + 0i isn't allowed.");
else
{
int x = a*c + b*d;
int y = b*c - a*d;
int z = c*c + d*d;
case 2:
real = a-c;
img = b-d;
if (img >= 0)
printf("Difference = %d + %di\n", real, img);
else
printf("Difference = %d %di\n", real, img);
break;
case 3:
real = a*c - b*d;
img = b*c + a*d;
if (img >= 0)
printf("Product = %d + %di\n", real, img);
else
else
{
if (y/z >= 0)
printf("Division = %d/%d + %d/%di",x, z, y, z);
else
printf("Division = %d/%d %d/%di", x, z, y, z);
}
}
break; Breaks come out of current loop
}
}while(choice<=4);
return 0;
}
HAPPY CODING!
Solve other problems. If any issues, please contact [email protected]
Unit #: 1
Unit Name: Problem Solving Fundamentals
Topic: Solution to the counting problem
Course objectives:
The objective(s) of this course is to make students
CObj1: Acquire knowledge on how to solve relevant and logical problems using computing
machine
CObj2: Map algorithmic solutions to relevant features of C programming language constructs
CObj3: Gain knowledge about C constructs and it's associated eco-system
CObj4: Appreciate and gain knowledge about the issues with C Standards and it's respective
behaviors
CObj5: Get insights about testing and debugging C Programs
Course outcomes:
At the end of the course, the student will be able to
CO1: Understand and apply algorithmic solutions to counting problems using appropriate C
Constructs
CO2: Understand, analyse and apply text processing and string manipulation methods using C
Arrays, Pointers and functions
CO3: Understand prioritized scheduling and implement the same using C structures
CO4: Understand and apply sorting techniques using advanced C contructs
CO5: Understand and evaluate portable programming techniques using preprocessor directives and
conditional compilation of C Programs
Team – PSWC,
Jan - May, 2022
Dept. of CSE,
PES University
Counting Problem
We are required to find the number of characters, number of words and number of
lines in an user input. (Similar to wc – word count command in unix)
We have not learnt yet how to play with files in our programs. It is a bit too early in this
course. But we do know how to read from the keyboard.
{ char ch;
while((ch = getchar()) != '\n')
{
putchar(ch);
}
return 0;
}
Coding Example_4: Solution to find the number of characters, number of words and
number of lines in an user input and in a given file
Every character read is considered for character count. Word count is incremented if it encounters
a space or a tab(\t) or new line(\n). Line count is incremented when it encounters a new line(\n)
#include<stdio.h>
int main()
{
char ch;
int nl = 0;
int nw = 0;
int nc = 0;
while((ch = getchar()) != EOF)
{
nc++;
if(ch == '\n')
nl++;
The problem with the above is if the data contains multiple spaces and multiple new lines, the
respective counts will be incremented.
Coding Example_5: The above issue can be avoided by using a boolean variable to indicate
whether we are in a word or not. If we are in a word and we reach a space, the word ends and we
count. If we are not in a word and we encounter a space, we ignore it. We set inword when we
4 Dept. of Computer Science and Engineering
2022
Problem Solving With C – UE23CS151B
encounter a non-white-space.
#include<stdio.h>
int main()
{
int nl,nw,nc,inword = 0;
char ch;
while((ch = getchar()) != EOF)
{
//putchar(ch);
nc++;
if(ch == '\n')
nl++;
Unit #: 1
Unit Name: Problem Solving Fundamentals
Topic: Language Specifications - Behaviors
Course objectives:
The objective(s) of this course is to make students
CObj1: Acquire knowledge on how to solve relevant and logical problems using computing
machine
CObj2: Map algorithmic solutions to relevant features of C programming language constructs
CObj3: Gain knowledge about C constructs and it's associated eco-system
CObj4: Appreciate and gain knowledge about the issues with C Standards and it's respective
behaviors
CObj5: Get insights about testing and debugging C Programs
Course outcomes:
At the end of the course, the student will be able to
CO1: Understand and apply algorithmic solutions to counting problems using appropriate C
Constructs
CO2: Understand, analyse and apply text processing and string manipulation methods using C
Arrays, Pointers and functions
CO3: Understand prioritized scheduling and implement the same using C structures
CO4: Understand and apply sorting techniques using advanced C contructs
CO5: Understand and evaluate portable programming techniques using preprocessor directives and
conditional compilation of C Programs
Team – PSWC,
Jan - May, 2022
Dept. of CSE,
PES University
Language Specifications
A Programming language specification is a document in human language describing how a
system is supposed to work. It is a documentation that defines a programming language so that
users and implementers can agree on what programs in that language mean. In case of a
programming language, it describes how the compiler or interpreter is to react to various
inputs - which are valid/invalid, and what happens when they are executed. Typically detailed
and formal, and primarily used by implementers referring to them in case of ambiguity
Locale-specific behavior - The behavior that are dependent on the implementation of the
C library, and are not defined by gcc itself
Undefined Behavior
that the program must not meet. Standard imposes no requirements: May fail to compile, may
crash, may generate incorrect results, may fortunately do what exactly programmer intended
int d = 10;
printf("%d %d %d\n", d++, d++ - --d,--d); // Unspecified behavior
return 0;
}
Semester: 2
Course Code: UE23CS151B
Course Anchor: Prof. C N Rajeswari
Lab Anchors: Prof. Sowmya Shree P, Prof. Chaitra S
Session: Feb 2024 – June 2024
Department of CSE, PES University
UE23CS151B – Problem Solving with C
Laboratory-Week 2
1. Editing
$gedit filename.c
2. Compile
$ gcc -c filename.c
3. Linking
$ gcc filename.o
4. Loading - Execute
$ ./a.out (Linux Operating System)
$ a.exe (Windows Operating System)
UE23CS151B 2024 1
Department of CSE, PES University
UE23CS151B – Problem Solving with C
Laboratory-Week 2
1. Write a program that takes two integer inputs, representing the length and
width of a rectangle, and calculates its area. Then, print the calculated area
as output.
Solution:
#include<stdio.h>
int main()
{
int l, b, area;
printf("Enter length and breadth\n");
scanf("%d%d",&l,&b);
area = l*b;
printf("Area=%d",area);
return 0;
}
UE23CS151B 2024 2
Department of CSE, PES University
UE23CS151B – Problem Solving with C
Laboratory-Week 2
2. Take an integer (say A) and a long long integer(say B) as input and perform
following operations -
• Subtract A from max value of INT allowed in 'C'.
• Subtract B from max value of LONG LONG INT allowed in 'C'.
Solution:
#include <stdio.h>
#include <limits.h>
int main()
{
int A;
long long B;
scanf("%d", &A);
scanf("%lld", &B);
printf("INT_MAX = %d\n",INT_MAX);
printf("LLONG_MAX = %lld\n",LLONG_MAX);
return 0;
}
UE23CS151B 2024 3
Department of CSE, PES University
UE23CS151B – Problem Solving with C
Laboratory-Week 2
3. Write a program that calculates the simple interest (SI) based on the given
principal amount (P), interest rate (R), and time period (T). Use the formula
SI = (P * R * T) / 100. Print the calculated simple interest as the output.
Solution:
#include <stdio.h>
#include <limits.h>
int main()
{
float p, t, r, SI;
printf("Enter the Principal amount, rate of interest and time period in years\n");
scanf("%f %f %f", &p, &r, &t);
SI = (p * r * t) /100;
return 0;
}
UE23CS151B 2024 4
Department of CSE, PES University
UE23CS151B – Problem Solving with C
Laboratory-Week 2
4. Write a program that takes three integer values as input from the user. The
program should then decrease each of the input integers by 1 and print the
results with a star hash (#) in between them.
Solution:
#include<stdio.h>
int main()
{
int a, b, c;
printf("Enter three integers\n");
scanf("%d%d%d",&a,&b,&c);
a = a-1;
b = b-1;
c = c-1;
printf("%d#%d#%d", a, b, c);
return 0;
}
UE23CS151B 2024 5
Department of CSE, PES University
UE23CS151B – Problem Solving with C
Laboratory-Week 2
5. Create a program that prompts the user to input the radius of a circle. The
program should then compute and display the area of the circle using the
formula: Area = π * (radius^2), use the math.h header file for π (M_PI).
Solution:
#include<stdio.h>
#include<math.h>
int main()
{
float radius, area;
printf("Enter the radius\n");
scanf("%f", &radius);
area = M_PI * radius * radius;
return 0;
}
UE23CS151B 2024 6
Department of CSE, PES University
UE23CS151B – Problem Solving with C
Laboratory-Week 2
#include<stdio.h>
int main()
{
float price, total_cost;
int quantity;
return 0;
}
UE23CS151B 2024 7
Department of CSE, PES University
UE23CS151B – Problem Solving with C
Laboratory-Week 2
7. Write a C program to read and print an integer. Also, print the return value
of the Input and Output function used.
Solution:
#include <stdio.h>
int main() {
int n;
int scanfReturnValue = scanf("%d", &n);
printf("Return value of Input function:%d\n", scanfReturnValue);
int printfReturnValue = printf("Number=%d", n);
printf("Return value of Output function:%d\n", printfReturnValue);
return 0;
}
UE23CS151B 2024 8
Department of CSE, PES University
UE23CS151B – Problem Solving with C
Laboratory-Week 2
8. Write a C Program to read a lower-case letter from the user and print the
uppercase without using formatted IO functions.
Solution:
#include <stdio.h>
int main()
{
char ch;
ch = getchar();
putchar(ch - 'a' + 'A' );
return 0;
}
UE23CS151B 2024 9
Department of CSE, PES University
UE23CS151B – Problem Solving with C
Laboratory-Week 2
#include <stdio.h>
int main() {
int a;
scanf("%d", &a);
printf("Hexadecimal:%#X\n", a);
printf("Octal:%#o", a);
return 0;
}
UE23CS151B 2024 10
Department of CSE, PES University
UE23CS151B – Problem Solving with C
Laboratory-Week 2
10. write a program that takes a floating-point number as input and prints its
exponential form.
Solution:
#include <stdio.h>
int main() {
float a;
scanf("%f", &a);
printf("%E\n", a);
return 0;
}
UE23CS151B 2024 11
Department of CSE, PES University
UE23CS151B – Problem Solving with C
Laboratory-Week 2
11. Program to read two inputs: a floating-point number ‘n’ and an integer ‘k’.
Display the floating-point value in three different ways:
a) rounded off to nearest integer,
b) scientific notation, and
c) round off the precision up to k decimal places
Note: Don’t use built-in functions. Use only printf function.
Solution:
#include<stdio.h>
int main()
{
float n;
int k;
scanf("%f", &n);
scanf("%d", &k);
printf("%.0f\n", n);
printf("%e\n", n);
printf("%.*f\n", k, n);
return 0;
}
UE23CS151B 2024 12
Department of CSE, PES University
UE23CS151B – Problem Solving with C
Laboratory-Week 2
12. Write a program that takes the number of days as input from the user and
displays the corresponding number of years.
Solution:
#include<stdio.h>
int main()
{
int days;
float years;
printf("Enter the number of days:\t");
scanf("%d",&days);
years = days/365.0;
UE23CS151B 2024 13
Department of CSE, PES University
UE23CS151B – Problem Solving with C
Laboratory-Week 2
13. Write a program that takes three integer values as input from the user. The
program should then increase each of the input integers by 1 and print the
results with a backward slash (\) in between them.
Solution:
#include<stdio.h>
int main()
{
int a, b, c;
scanf("%d%d%d",&a,&b,&c);
a = a+1;
b = b+1;
c = c+1;
printf("%d\\%d\\%d", a, b, c);
return 0;
}
UE23CS151B 2024 14
Problem Solving with C
LABORATORY MANUAL
Week 3
Semester: 2
Course Code: UE23CS151B
Course Anchor: Prof. C N Rajeswari
Lab Anchors: Prof. Sowmya Shree P, Prof. Chaitra S
Session: Feb 2024 – June 2024
Department of CSE, PES University
UE23CS151B – Problem Solving with C
Laboratory-Week 3
1. Write a program that takes a student's score as input and prints their
corresponding letter grade according to the following scale: A (90-100),
B (80-89), C (70-79), D (60-69), F (0-59).
Solution:
#include <stdio.h>
int main()
{
int score;
scanf("%d",&score);
if(score>=90)
printf("%c",'A');
else if(score>=80)
printf("%c",'B');
else if(score>=70)
printf("%c",'C');
else if(score>=60)
printf("%c",'D');
else
printf("%c",'F');
return 0;
}
UE23CS151B 2024 1
Department of CSE, PES University
UE23CS151B – Problem Solving with C
Laboratory-Week 3
2. Write a program that prints the number of days in the given month as input
for the year 2024. Input should be the month’s number. For example, for
“January,” the input is 1 and program should display 31.
Solution:
#include <stdio.h>
int main()
{
int month;
scanf("%d",&month);
switch(month)
{
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12: printf("%d",31);
break;
case 2: printf("%d",29);
break;
case 4:
case 6:
case 9:
case 11:printf("%d",30);
break;
return 0;
}
UE23CS151B 2024 2
Department of CSE, PES University
UE23CS151B – Problem Solving with C
Laboratory-Week 3
3. Competitive Challenge: Sam has given a task of listing Leap years from 1000 AD
to till date. Write a C program that takes a year as input and prints if it is a Leap Year
or Not.
Solution:
#include<stdio.h>
int main()
{
int year;
scanf("%d", &year);
return 0;
}
UE23CS151B 2024 3
Department of CSE, PES University
UE23CS151B – Problem Solving with C
Laboratory-Week 3
4. Write a program that takes a positive number as input and pairwise prints
all the factors of the number.
Solution:
#include<stdio.h>
#include<math.h>
int main()
{
int n;
scanf("%d", &n);
for(int i=1;i<sqrt(n);i++)
if(n%i==0)
printf("%d %d\n", i, n/i);
return 0;
}
UE23CS151B 2024 4
Department of CSE, PES University
UE23CS151B – Problem Solving with C
Laboratory-Week 3
5. Write a program that accepts the length of three sides of a triangle and
checks if it is an equilateral, isosceles or scalene triangle.
Side of the triangle should be a positive integer. If 0 or negative input is given
program should print “Invalid input.”.
Solution:
#include<stdio.h>
int main()
{
int a,b,c;
scanf("%d %d %d", &a, &b, &c);
if (a>0 && b>0 && c>0)
{
if(a==b && b==c)
printf("Equilateral Triangle");
else if(a==b || b==c || c==a)
printf("Isosceles Triangle");
else
printf("Scalene Triangle");
}
else
{
printf("Invalid input.");
}
return 0;
}
UE23CS151B 2024 5
Department of CSE, PES University
UE23CS151B – Problem Solving with C
Laboratory-Week 3
Solution:
#include<stdio.h>
int main()
{
int age;
char permit;
scanf("%d", &age);
scanf(" %c", &permit);
if(age >= 18 && (permit == 'Y' || permit == 'y'))
printf("Eligible");
else
printf("Not eligible");
return 0;
}
UE23CS151B 2024 6
Department of CSE, PES University
UE23CS151B – Problem Solving with C
Laboratory-Week 3
7. Write a program that reads a character and prints whether it’s a vowel or
consonant. For any input except alphabets, program should print “Invalid
input.”
Solution:
#include<stdio.h>
int main()
{
char ch;
scanf("%c",&ch);
if((ch>='a' && ch<='z') || (ch>='A' && ch<='Z'))
{
if(ch=='a'||ch=='A'||ch=='e'||ch=='E'||ch=='i'||ch=='I'
||ch=='o'||ch=='O'||ch=='u'||ch=='U')
printf("%c is Vowel.",ch);
else
printf("%c is Consonant.", ch);
}
else
printf("Invalid input.");
return 0;
}
UE23CS151B 2024 7
Department of CSE, PES University
UE23CS151B – Problem Solving with C
Laboratory-Week 3
8. Write a program that reads an integer n and computes the sum of natural
numbers from 1 to n and prints it. Also, compute the average of these
numbers and print the average rounded up to one decimal place.
Solution:
#include<stdio.h>
int main()
{
int n, sum = 0;
scanf("%d", &n);
for (int i = 1; i <= n; i++)
sum += i;
printf("%d\n", sum);
printf("%.1f", (float)sum / n);
return 0;
}
UE23CS151B 2024 8
Department of CSE, PES University
UE23CS151B – Problem Solving with C
Laboratory-Week 3
Solution:
#include<stdio.h>
int main()
{
int units;
scanf("%d",&units);
if(units<=10)
printf("No Charge\n");
else if(units<=25)
printf("%f",(float)(units-10)*10);
else
printf("%f",(float)((15*10) + (units-25)*25));
return 0;
}
UE23CS151B 2024 9
Department of CSE, PES University
UE23CS151B – Problem Solving with C
Laboratory-Week 3
10. Write a program to print the count of digits in a given positive number.
Solution:
#include<stdio.h>
int main()
{
int n,count;
scanf("%d",&n);
count = 0;
while(n>0)
{
count++;
n = n/10;
}
printf("Count=%d",count);
return 0;
}
UE23CS151B 2024 10
Department of CSE, PES University
UE23CS151B – Problem Solving with C
Laboratory-Week 3
11. Write a program to print the count of even numbers in a given range. The
lower and upper value in the range will be given as input.
Solution:
#include<stdio.h>
int main()
{
int lower,upper,count=0;
scanf("%d%d",&lower,&upper);
for(int i=lower;i<=upper;i++)
if(i%2==0)
count+=1;
printf("%d",count);
return 0;
}
UE23CS151B 2024 11
Department of CSE, PES University
UE23CS151B – Problem Solving with C
Laboratory-Week 3
#include<stdio.h>
int main()
{
int assignment, quiz, midterm_exam, final_exam;
float final_grade;
scanf("%d", &assignment);
scanf("%d", &quiz);
scanf("%d", &midterm_exam);
scanf("%d", &final_exam);
final_grade = 0.25 * assignment + 0.20 * quiz + 0.25 * midterm_exam
+ 0.30 * final_exam;
return 0;
}
UE23CS151B 2024 12
Department of CSE, PES University
UE23CS151B – Problem Solving with C
Laboratory-Week 3
13. Write a program in C to calculate the electricity bill for a household based on
the units consumed. The rate of electricity per unit varies as follows:
For the first 100 units, the rate is Rs. 2.50 per unit.
For the next 200 units, the rate is Rs. 4.00 per unit.
For any additional units, the rate is Rs. 6.00 per unit.
The program should read the number of units consumed. Then, calculate and
display the total bill amount.
Solution:
#include<stdio.h>
int main()
{
int units;
float bill = 0.0;
scanf("%d", &units);
if(units <= 100)
bill = units * 2.50;
else if (units <= 300)
bill = 100 * 2.50 + (units - 100) * 4.00;
else
bill = 100 * 2.50 + 200 * 4.00 + (units - 300) * 6.00;
printf("Rs.%.2f", bill);
return 0;
}
UE23CS151B 2024 13
Department of CSE, PES University
UE23CS151B – Problem Solving with C
Laboratory-Week 3
Solution:
#include<stdio.h>
int main()
{
int n,temp,digit,rev=0;
scanf("%d",&n);
temp = n;
while(n>0)
{
digit = n%10;
rev = rev*10 + digit;
n = n/10;
}
if(temp==rev)
printf("Palindrome.");
else
printf("Not a Palindrome.");
return 0;
}
UE23CS151B 2024 14
Department of CSE, PES University
UE23CS151B – Problem Solving with C
Laboratory-Week 3
15. Competitive Challenge: Write a program that prints all the numbers from 1
to n that are either multiples of 2 or multiples of 3.
Solution:
#include<stdio.h>
int main()
{
int n;
scanf("%d",&n);
for(int i=1;i<=n;i++)
if(i%2==0 || i%3==0)
printf("%d ",i);
return 0;
}
UE23CS151B 2024 15
Problem Solving with C
LABORATORY MANUAL
Week 4
Semester: 2
Course Code: UE23CS151B
Course Anchor: Prof. C N Rajeswari
Lab Anchors: Prof. Sowmya Shree P, Prof. Chaitra S
Session: Feb 2024 – June 2024
Department of CSE, PES University
UE23CS151B – Problem Solving with C
Laboratory-Week 4
1) Write a C program that takes a long long integer as input. The program should print the
hexadecimal representation of the absolute value of the input along with the counts of
vowels, consonants, and digits in its hexadecimal form. Use if-else statements and logical
operators in your code.
Solution:
#include <stdio.h>
int main()
{
long long int number;
scanf("%lld", &number);
int vowels = 0, consonants = 0, digits = 0;
long long int temp = (number < 0) ? -number : number;
printf("%llx\n", temp);
while (temp != 0)
{
int digit = temp % 16;
temp /= 16;
2) Create a pattern printer (using switch case and loops). Take user input for the choice of
pattern to be printed. Only valid choice is 1. If the user's choice is 1, print Floyd’s
triangle with numbers. Also take the number of rows as input from the user. For any
other number for the user's choice print Invalid.
UE23CS151B 2024 2
Department of CSE, PES University
UE23CS151B – Problem Solving with C
Laboratory-Week 4
Solution:
#include<stdio.h>
int main()
{
int choice;
scanf("%d", &choice);
switch (choice)
{
case 1:
{
int rows, i, j, number = 1;
scanf("%d", &rows);
for (i = 1; i <= rows; i++)
{
for (j = 1; j <= i; ++j)
{
printf("%d ", number);
++number;
}
printf("\n");
}
break;
}
default:
printf("Invalid");
}
return 0;
}
Competitive Challenge:
3) In a class of 11 students with 6 benches in the exam hall. A maximum of 2 students can
sit on a bench during the test. While paper correction it was found that all students
sitting on the same bench have the exact same answer. Given marks of all students in a
shuffled manner, find out the sum of marks obtained by non-cheating students. Write a C
code to achieve the same. Don’t use array or sorting methods.
Solution:
#include <stdio.h>
int main()
{
int marks,answer=0;
for(int i=0;i<11;i++)
{
scanf("%d",&marks);
UE23CS151B 2024 3
Department of CSE, PES University
UE23CS151B – Problem Solving with C
Laboratory-Week 4
answer^=marks;
}
printf("%d",answer);
return 0;
}
4) Write a C program to perform simple tasks based on operators. Use switch case
statements.
- If $ - Take next 3 floating point numbers input as P, R and T respectively and
calculate simple interest
- If ! - Take next 2 integers and perform arithmetic operations, that is, +, -, *, /. Take
the operator also as input.
- If ? - Take next 2 integers and perform bitwise operations, that is, &, |, Left shift (<)
and Right shift(>). Take operator also as input.
Solution:
#include <stdio.h>
int main()
{
char choice;
scanf(" %c", &choice);
switch(choice)
{
case '$':
{
float P, R, T;
scanf("%f %f %f", &P, &R, &T);
case '!':
{
int num1, num2;
char operator;
scanf("%d %d %c", &num1, &num2, &operator);
int result;
switch(operator)
{
case '+':
result = num1 + num2;
printf("%d\n", result);
break;
case '-':
UE23CS151B 2024 4
Department of CSE, PES University
UE23CS151B – Problem Solving with C
Laboratory-Week 4
}
break;
case '?':
{
int num1, num2;
char operator;
scanf("%d %d %c", &num1, &num2, &operator);
int result;
switch(operator)
{
case '&':
result = num1 & num2;
break;
case '|':
result = num1 | num2;
break;
case '<':
result = num1 << num2;
break;
case '>':
result = num1 >> num2;
break;
default:
printf("Invalid operator\n");
return 0;
}
UE23CS151B 2024 5
Department of CSE, PES University
UE23CS151B – Problem Solving with C
Laboratory-Week 4
printf("%d\n", result);
}
break;
default:
printf("Invalid choice\n");
return 0;
}
return 0;
}
5) Find the smallest and second largest number from the given set of 5 integers
using control structures.
Solution:
#include <stdio.h>
int main()
{
int num, largest, secondLargest, smallest;
scanf("%d", &num);
return 0;
}
Competitive Challenge:
UE23CS151B 2024 6
Department of CSE, PES University
UE23CS151B – Problem Solving with C
Laboratory-Week 4
6) Print reverse pascal’s Triangle in pyramid shape. Take the number of rows as input from
the user. Accept only positive input, handle non-positive input cases.
Solution:
#include <stdio.h>
int main()
{
int numRows;
scanf("%d", &numRows);
if (numRows <= 0)
{
printf("Invalid input\n");
return 0;
}
7) Write a C program to find the sum of all digits present in a number. The sum should be
modulo the last digit of the number and print the same. If the input is empty, return 0.
The input contains only a number.
Solution:
#include <stdio.h>
int main() {
char ch;
UE23CS151B 2024 7
Department of CSE, PES University
UE23CS151B – Problem Solving with C
Laboratory-Week 4
int num = 0;
} else {
printf("Invalid input\n");
return 0;
if (num == 0) {
printf("ZeroError\n");
return 0;
int sum = 0;
while (temp != 0) {
temp /= 10;
printf("%d\n", result);
return 0;
UE23CS151B 2024 8
Department of CSE, PES University
UE23CS151B – Problem Solving with C
Laboratory-Week 4
8) Write a program that checks if a given number is a number where the sum of the cube of
each digit is equal to the original number. Use loops and mathematical operations to
achieve this.
Solution:
#include <stdio.h>
#include <ctype.h>
int main() {
int ch;
int num = 0;
if (isdigit(ch)) {
} else {
return 0;
if (num <= 0) {
return 0;
UE23CS151B 2024 9
Department of CSE, PES University
UE23CS151B – Problem Solving with C
Laboratory-Week 4
int sum = 0;
while (num != 0) {
num /= 10;
if (sum == original) {
printf("Armstrong Number!\n");
} else {
return 0;
Competitive Challenge:
9) Write a C program using loops to print the sum of Fibonacci prime number series up to a
given number.
Solution:
#include <stdio.h>
int main() {
int limit;
printf("Wrong input\n");
UE23CS151B 2024 10
Department of CSE, PES University
UE23CS151B – Problem Solving with C
Laboratory-Week 4
return 0;
int is_prime = 1;
if (curr == 1) {
is_prime = 0;
} else {
if (curr % i == 0) {
is_prime = 0;
break;
if (is_prime)
sum += curr;
prev = curr;
curr = next;
printf("%d\n", sum);
return 0;
UE23CS151B 2024 11
Department of CSE, PES University
UE23CS151B – Problem Solving with C
Laboratory-Week 4
10) Write a C program using loops to print the Fibonacci even number series up to a given
number.
Solution:
#include <stdio.h>
int main()
{
int n, first=0, second=1, next;
scanf("%d", &n);
while(first<=n)
{
if (first % 2 == 0)
{
printf("%d ", first);
}
next = first + second;
first = second;
second = next;
}
return 0;
}
11) Write a C program that takes an integer as input, counts the number of digits in it and
displays the same, and then checks if the (sum of its digits + the product of its digits) is
equal to the original number. If the conditions are met, print the number; otherwise,
display zero.
Solution:
#include<stdio.h>
int main()
{
int num, originalNum, digit, sum = 0, product = 1, count = 0;
scanf(“%d”, &num);
originalNum = num;
while(num != 0)
{
digit = num % 10;
sum += digit;
product *= digit;
num /= 10;
count++;
}
printf(“%d\n”, count);
if ((sum + product) == originalNum)
{
UE23CS151B 2024 12
Department of CSE, PES University
UE23CS151B – Problem Solving with C
Laboratory-Week 4
printf(“%d\n”, originalNum);
}
else
printf(“0\n”);
return 0;
}
Competitive Challenge:
12) Write a C program using bitwise operators for the following :
Input a number and the bit position (starting from 0th position)
i) check whether specified bit is set or not
If the bit is set, print "BIT IS SET"
Else, "BIT IS NOT SET"
ii) set the specified bit (if it is not set) and print the result in new line
iii) clear the specified bit (if it is set) and print the result in new line
Solution:
#include <stdio.h>
int main()
{
int number, bitPosition;
scanf("%d", &number);
scanf("%d", &bitPosition);
13) Develop a C program to implement a versatile unit converter for length measurements.
The program should prompt the user to input the type of conversion and the value to be
converted. The supported conversion types and their respective conversion values are
as follows:
a) Feet to Meters: 1 foot = 0.3048 meters
UE23CS151B 2024 13
Department of CSE, PES University
UE23CS151B – Problem Solving with C
Laboratory-Week 4
Solution:
#include <stdio.h>
int main() {
int choice;
double inputValue, result;
UE23CS151B 2024 14
Department of CSE, PES University
UE23CS151B – Problem Solving with C
Laboratory-Week 4
default:
printf("Invalid choice.\n");
return 1;
}
return 0;
}
Solution:
#include <stdio.h>
#include <math.h>
int main() {
int number,check, sum = 0, temp, digitCount = 0;
// Prompt the user to enter a number
scanf("%d", &number);
temp = number;
// Calculate the sum of the cubes of the digits
while (temp > 0) {
int digit = temp % 10;
digitCount++;
sum += digit;
temp /= 10;
}
check=sum*sum*sum;
// Check if the entered number is a Dudeney number
if (check == number) {
printf("Dudeney number\n");
} else {
printf("Not a Dudeney number\n");
}
return 0;
}
Competitive Challenge:
UE23CS151B 2024 15
Department of CSE, PES University
UE23CS151B – Problem Solving with C
Laboratory-Week 4
15) Design a C program to print a pyramid pattern of numbers based on user input. The
program should take the number of rows as input and generate a pyramid as follows:
1
121
12321
1234321
Solution:
#include <stdio.h>
int main() {
int rows, spaces, j;
if(rows <= 0)
{
printf("Invalid input");
return 1;
}
// Loop to iterate over each row
for (int i = 1; i <= rows; i++) {
16) Write a C program to find the sum of all prime numbers within a given range [L, R],
where L and R are the lower and upper bounds of the given range.
Solution:
UE23CS151B 2024 16
Department of CSE, PES University
UE23CS151B – Problem Solving with C
Laboratory-Week 4
#include<stdio.h>
int main() {
int L, R, sum = 0;
scanf("%d %d", &L, &R);
printf("%d\n", sum);
return 0;
}
17) Write a C program to find the sum of all even numbers and the product of all odd
numbers in a given group of n numbers.
Solution:
#include <stdio.h>
UE23CS151B 2024 17
Department of CSE, PES University
UE23CS151B – Problem Solving with C
Laboratory-Week 4
int main() {
int N, sumEven = 0, productOdd = 1;
scanf("%d", &N);
int num;
for (int i = 0; i < N; i++) {
scanf("%d", &num);
if (num % 2 == 0) {
sumEven += num;
} else {
productOdd *= num;
}
}
printf("%d %d\n", sumEven, productOdd);
return 0;
}
Competitive Challenge:
18) Write a C program to print hollow sandglass star pattern using for loop.
Solution:
#include <stdio.h>
int main() {
int rows, i, j, k;
scanf("%d", &rows);
for (i = 1; i <= rows; i++)
{
for (j = 1; j < i; j++)
{
printf(" ");
}
for (k = i; k <= rows; k++)
{
if (i == 1 || k == i || k == rows)
{
UE23CS151B 2024 18
Department of CSE, PES University
UE23CS151B – Problem Solving with C
Laboratory-Week 4
printf("* ");
}
else
{
printf(" ");
}
}
printf("\n");
}
19) Given a complex number convert the given complex numbers into polar form and
exponential form and print them in their respective formats.
Solution:
#include <stdio.h>
#include <math.h>
int main()
{
int a,b;
scanf("%d+%di", &a, &b);
printf("%.2f(cos(%.2f)+isin(%.2f))\n", r, t, t);
printf("%.2fe^(%.2fi)", r, t);
UE23CS151B 2024 19
Department of CSE, PES University
UE23CS151B – Problem Solving with C
Laboratory-Week 4
return 0;
}
20) Given all three sides and angles of a triangle print whether the triangle is Equilateral,
Isosceles, Scalene by checking the sides and Acute, Right, Obtuse Triangle by checking
the angles.
Solution:
#include<stdio.h>
int main()
{
float s1, s2, s3;
int a1, a2, a3;
UE23CS151B 2024 20
Department of CSE, PES University
UE23CS151B – Problem Solving with C
Laboratory-Week 4
Competitive Challenge:
21) Write a Program in C that prints a hollow diamond of the user inputted size n. Below is
how the output should look like.
*
* *
* *
* *
*
Solution:
#include <stdio.h>
int main() {
int n;
scanf("%d", &n);
for (int i=1; i<=n+1; i+=2){
for (int j=0; j<(n-i)/2; j++){
printf(" ");
}
for (int k=0; k<i; k++){
if (k==0 || k==i-1){
printf("*");
}
else{
printf(" ");
}
}
printf("\n");
}
for (int i=n-2; i>=1; i-=2){
for (int j=0; j<(n-i)/2; j++){
printf(" ");
}
for (int k=0; k<i; k++){
if (k==0 || k==i-1){
printf("*");
}
else{
printf(" ");
}
}
printf("\n");
}
return 0;
}
UE23CS151B 2024 21
Department of CSE, PES University
UE23CS151B – Problem Solving with C
Laboratory-Week 4
22) You are given an integer n, calculate the sum of prime digits present in the given integer
n.
Solution:
#i#include <stdio.h>
int main() {
int num;
// Taking input for num
scanf("%d", &num);
23) Write a program that takes two integers as input and checks if they form an amicable
pair.A pair of numbers are called amicable pairs if the sum of the proper divisors of each
number is equal to the other number. Print True if they are amicable pairs otherwise
False.
Solution:
#include <stdio.h>
int main() {
int num1, num2;
int sumDivisors1 = 1, sumDivisors2 = 1;
UE23CS151B 2024 22
Department of CSE, PES University
UE23CS151B – Problem Solving with C
Laboratory-Week 4
sumDivisors2 += i;
}
}
printf("%s", areAmicable1==1?"True":"False");
return 0;
}
Competitive Challenge:
24) You are given an integer n. Count the number of bits which are set in the binary
representation of the given integer n. You must use bitwise operators and loops to solve
this challenge. A bit is set if its value is 1.
Solution:
#include <stdio.h>
int main() {
int n;
scanf("%d", &n);
int count=0;
for (int i=0; i<16; i++){
if (n & (1<<i))
count++;
}
printf("%d", count);
return 0;
}
25) Write a C program to analyse a given line of text and determine the following statistics:
• Number of words in the line.
• Number of characters in the line.
• Number of vowels in the line.
Your program should utilise the getchar function to read each character in the line until
a newline character ('\n') or end-of-file (EOF) is encountered. Additionally, identify and
count the vowels in the given line. Vowels include 'a', 'e', 'i', 'o', and 'u', both in lowercase
and uppercase.
Solution:
#include <stdio.h>
int main() {
UE23CS151B 2024 23
Department of CSE, PES University
UE23CS151B – Problem Solving with C
Laboratory-Week 4
int ch;
int words = 0, characters = 0, vowels = 0;
int wordflag = 1 ;
while ((ch = getchar()) != '\n' && ch != EOF) {
characters++;
if (characters > 0) {
words++;
}
printf("Words:%d\n", words);
printf("Characters:%d\n", characters);
printf("Vowels:%d\n", vowels);
return 0;
}
26) Write a C program to determine the number of digits in a given integer that are divisible
by 3.
Your program should:
• Prompt the user to enter an integer.
• Analyse each digit in the given integer.
• Count and display the number of digits in the integer that are divisible by 3.
Solution:
#include <stdio.h>
int main() {
int number, digit, count = 0;
scanf("%d", &number);
while (number != 0) {
digit = number % 10;
if (digit % 3 == 0) {
count++;
UE23CS151B 2024 24
Department of CSE, PES University
UE23CS151B – Problem Solving with C
Laboratory-Week 4
}
number /= 10;
}
printf("%d", count);
return 0;
}
Competitive Challenge:
27) Write a C program to generate and display palindromic numbers within a given range [a,
b], where a < b and b < 1000.
Your program should:
• Prompt the user to enter two integers a and b.
• Verify that the input satisfies the conditions a < b and b < 1000. If not, display an
error message and terminate the program.
• Identify and print all palindromic numbers within the range [a, b].
A palindromic number is a number that remains the same when its digits are reversed.
Solution:
#include <stdio.h>
int main() {
int a, b;
scanf("%d %d", &a, &b);
if (original == reversed) {
printf("%d\n", original);
}
}
return 0;
}
28) Write a program in C that takes a number as input and reverse the number as output.
Also print the reversed number in words
UE23CS151B 2024 25
Department of CSE, PES University
UE23CS151B – Problem Solving with C
Laboratory-Week 4
Solution:
#include <stdio.h>
int main()
{
int n, digit, temp, rem, rev = 0;
scanf("%d", &n);
temp = n;
while (temp != 0)
{
UE23CS151B 2024 26
Department of CSE, PES University
UE23CS151B – Problem Solving with C
Laboratory-Week 4
printf("eight ");
break;
case 9:
printf("nine ");
break;
case 0:
printf("zero ");
break;
}
}
return 0;
}
29) Write a program to print the sum of the series 1/12 + 1/22 + ....... + 1/n2.Take n as input.
Your program should:
• Prompt the user to enter a number n.
• 0<n<100
• Print the sum of the series
Solution:
#include <stdio.h>
#include <math.h>
int main()
{
int n;
float sum = 0.0, a;
scanf("%d", &n);
for (int i = 1; i <= n; i++)
{
a = 1 / pow(i, 2);
sum = sum + a;
}
printf("%.3f", sum);
return 0;
}
Competitive Challenge:
30) Take two 3-digit numbers as input which are separated by 100 and print the armstrong
numbers between them.
Your program should:
• Read two numbers.
• Make sure that the two numbers differ by 100 and that they have 3 digits.
Otherwise print the message “error”
• Print the armstrong numbers between them.
UE23CS151B 2024 27
Department of CSE, PES University
UE23CS151B – Problem Solving with C
Laboratory-Week 4
Armstrong number the number in any number base that forms the same number when
each of its digits is raised to the power of the number of digits in the number.
Solution:
#include <stdio.h>
int main()
{
int i, a, b, c, d, num1, num2;
scanf("%d%d", &num1, &num2);
if((num2-num1)!=100)
{
printf("error");
return 0;
}
if(num1<100 ||num2<100)
{
printf("error");
return 0;
}
for (i = num1; i < num2; i++)
{
a = i % 10;
d = i / 10;
b = d / 10;
c = d % 10;
if (a * a * a + b * b * b + c * c * c == i)
{
printf("%d\n", i);
}
}
return 0;
}
31) Alice and four other family members (total 5) are stuck in a shopping mall. Fortunately,
the place where they are stuck has frozen buns which they can eat and survive. There
are N buns in the mall, and each member needs to eat X buns every day to survive. After
the food supply runs out, the family can survive for another D days. How many days can
Alice and family survive?
Note: If there aren't enough buns to feed the whole family, nobody will eat anything.
Solution:
#include<stdio.h>
int main()
{
UE23CS151B 2024 28
Department of CSE, PES University
UE23CS151B – Problem Solving with C
Laboratory-Week 4
buns = x * 5;
days = n / buns;
ans = days + d;
printf("%d", ans);
return 0;
}
32) A Pronic Number is a number which is a product of two consecutive positive integers.
Write a C program to input a number and check whether the number is a Pronic number
if not. The program should also print the consecutive integers in descending order if the
product is a Pronic number.
Solution:
#include <stdio.h>
int main()
{
int n, flag = 0;
scanf("%d", &n);
for(int i=1; i*(i+1)<=n; i++)
{
if(i * (i+1) == n)
{
flag = 1;
printf("YES\n%d %d", i+1, i);
break;
}
}
if(flag == 0)
printf("NO");
return 0;
}
Competitive Challenge:
33) Alice and Bob want to compare their ages. Write a C program that takes their birth dates
(DD/MM/YYYY) as input and prints who is older among them. The program should also
check and display if either, neither or both of them were born in a leap year.
Solution:
#include <stdio.h>
int main()
{
UE23CS151B 2024 29
Department of CSE, PES University
UE23CS151B – Problem Solving with C
Laboratory-Week 4
34) Write a menu driven C program to create a simple calculator that performs the following
operations: Addition [+], Subtraction [-], Multiplication[*], Division [/], Exponent[^],
Modulus [%], Exit[E]
Solution:
#include<stdio.h>
#include<math.h>
int main()
UE23CS151B 2024 30
Department of CSE, PES University
UE23CS151B – Problem Solving with C
Laboratory-Week 4
{
while(1)
{
char op;
int o1,o2;
int flag=0;
scanf(" %c",&op);
scanf("%d",&o1);
scanf("%d",&o2);
switch (op)
{
case '+':
printf("Ans: %f\n",(float)(o1+o2));
break;
case '-':
printf("Ans: %f\n",(float)(o1-o2));
break;
case '/':
printf("Ans: %f\n",((float)(o1)/(float)(o2)));
break;
case '*':
printf("Ans: %f\n",(float)(o1*o2));
break;
case '^':
printf("Ans: %f\n",(float)(pow(o1,o2)));
break;
case '%':
printf("Ans: %f\n",(float)(o1 %o2));
break;
case 'E':
flag=1;
break;
}
if(flag==1)
{
break;
}
}
return 0;
}
35) Write a C program that takes in a given number n as its input and finds the closest
number in the Fibonacci sequence to n. If there exist two numbers that are equally close,
the program must output both numbers.
Solution:
UE23CS151B 2024 31
Department of CSE, PES University
UE23CS151B – Problem Solving with C
Laboratory-Week 4
#include<stdio.h>
int main() {
int n;
scanf("%d",&n);
int i = 0;
int j = 1;
while(1)
{
if(i==n || j==n)
{
printf("%d",n);
break;
}
if(n>i && n<j)
{
if(n-i<j-n)
{
printf("%d",i);
}
else if(n-i>j-n)
{
printf("%d",j);
}
else
{
printf("%d %d",i,j);
}
break;
}
int temp = i;
i=j;
j =j+temp;
}
return 0;
Competitive Challenge:
36) Given the input n and 'consecutive bits', write a C program to generate numbers in
binary form in the range of 1 to n(both inclusive) such that:
a) When the consecutive bits input is 0, numbers having no consecutive 0s are
generated. An example of such a number is 6 since its binary form is 110
b) When the consecutive bits input is 1, numbers having no consecutive 1s are
generated. An example of such a number is 4 since its binary form is 100
c) When the consecutive bits input is 10, numbers having no consecutive 0s and 1s are
generated. An example of such a number is 5 since its binary form is 101
Solution:
UE23CS151B 2024 32
Department of CSE, PES University
UE23CS151B – Problem Solving with C
Laboratory-Week 4
#include<stdio.h>
int main(){
int n;
int bit;
scanf("%d",&n);
scanf("%d",&bit);
for(int i=1;i<=n;i++)
{
int temp = i;
int v = temp & 1;
int successive = 1;
temp = temp >> 1;
while(temp>0){
if(bit==10){
if((temp & 1) == v){
successive = 0;
break;
}
}
else {
if((temp & 1) == v&& v==bit)
{
successive = 0;
break;
}
}
v = temp & 1;
temp = temp >> 1;
}
if(successive == 1){
int decimal_num=i, binary_num = 0, j = 1, remainder;
while (decimal_num != 0) {
remainder = decimal_num % 2;
decimal_num /= 2;
binary_num += remainder * j;
j *= 10;
}
printf("%d\n", binary_num);
}
}
return 0;
}
UE23CS151B 2024 33
Department of CSE, PES University
UE23CS151B – Problem Solving with C
Laboratory-Week 4
37) You are tasked with implementing a program that performs character rotations to
decipher encoded messages. The program takes a single character as input and rotates it
according to a specific algorithm. If the input character is lowercase, it rotates within the
lowercase alphabet, and if it's uppercase, it rotates within the uppercase alphabet. The
rotation involves shifting the character by one position to the right, wrapping around to
the beginning of the alphabet if necessary. After the rotation, the program prints the next
four characters obtained from the rotation. Ensure that your program correctly handles
both lowercase and uppercase characters.
Solution:
#include <stdio.h>
int main() {
char inputChar;
UE23CS151B 2024 34
Department of CSE, PES University
UE23CS151B – Problem Solving with C
Laboratory-Week 4
printf("\n");
return 0;
38) You are tasked with developing a simple C program that prints a pyramid pattern. The
program takes input as number of rows for the pyramid. After receiving the input, the
program constructs a pyramid pattern using asterisks (*) such that each row has an
increasing number of asterisks, forming a pyramid shape.
Solution:
#include <stdio.h>
int main() {
scanf("%d", &rows);
printf(" ");
printf("*");
printf("\n");
return 0;
UE23CS151B 2024 35
Department of CSE, PES University
UE23CS151B – Problem Solving with C
Laboratory-Week 4
Competitive Challenge:
39) Imagine you have a sequence of numbers generated using a set of rules. The rules for
generating the sequence are as follows:
If the current number is even, divide it by 2.
If the current number is odd, multiply it by 3 and add 1.
You are given a starting number, and your task is to apply these rules iteratively to
generate the sequence. Your goal is to find the maximum value encountered during the
process.
Challenge Instructions:
i. Read a positive integer start from the user, representing the starting number of
the sequence.
ii. Use a while loop to generate the sequence based on the rules until you reach the
number 1.
iii. Print the maximum value encountered in the sequence.
Solution:
#include <stdio.h>
int main() {
int start;
// Input
scanf("%d", &start);
int length = 0;
while (start != 1) {
if (start % 2 == 0) {
start /= 2;
} else {
UE23CS151B 2024 36
Department of CSE, PES University
UE23CS151B – Problem Solving with C
Laboratory-Week 4
start = 3 * start + 1;
length++;
max_value = start;
// Output
return 0;
40) Rahul is supposed to write an essay of N words but since he doesn’t have pages, he will
have to manage with the available L number of lines. If he writes W number of words on
average, every line except may be the last line, calculate the number of words he writes
in the last line.
Solution:
#include <stdio.h>
int main() {
int n, l, w;
scanf("%d", &n);
scanf("%d", &l);
scanf("%d", &w);
if (w * l > n) {
printf("%d", n % w);
UE23CS151B 2024 37
Department of CSE, PES University
UE23CS151B – Problem Solving with C
Laboratory-Week 4
else if (w * l == n) {
printf("%d", w);
else {
printf("%d", n - (w * (l - 1)));
return 0;
41) Write a program to accept a number and count the number of prime digits in it.
Solution:
#include <stdio.h>
int main() {
int n;
scanf("%d", &n);
int ans = 0;
while (n != 0) {
int x = n % 10;
switch (x) {
case 2:
case 3:
case 5:
case 7:
ans++;
UE23CS151B 2024 38
Department of CSE, PES University
UE23CS151B – Problem Solving with C
Laboratory-Week 4
break;
n /= 10;
printf("%d", ans);
return 0;
Competitive Challenge:
42) Write a program to accept an integer n and print n rows of asterisks following the
Fibonacci series. Do not print spaces between asterisks. Since first number in Fibonacci
series is 0, leave the first line (row) blank.
Solution:
#include <stdio.h>
int main() {
int n;
scanf("%d", &n);
int zero = 0, one = 1;
if (n == 1) {
return 0;
}
printf("*\n");
for (int i = 2; i < n; i++) {
int temp = zero + one;
zero = one;
one = temp;
for (int j = 0; j < one; j++) {
printf("*");
}
printf("\n");
}
return 0;
UE23CS151B 2024 39