Nothing Special   »   [go: up one dir, main page]

C Programming Language

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 339

1) How do you construct an increment statement or

decrement statement in C?
There are actually two ways you can do this. One is to use the increment
operator ++ and decrement operator –. For example, the statement “x++”
means to increment the value of x by 1. Likewise, the statement “x –”
means to decrement the value of x by 1. Another way of writing increment
statements is to use the conventional + plus sign or – minus sign. In the
case of “x++”, another way to write it is “x = x +1”.

2) What is the difference between Call by Value and Call by


Reference?
When using Call by Value, you are sending the value of a variable as
parameter to a function, whereas Call by Reference sends the address of
the variable. Also, under Call by Value, the value in the parameter is not
affected by whatever operation that takes place, while in the case of Call
by Reference, values can be affected by the process within the function.

3) Some coders debug their programs by placing comment


symbols on some codes instead of deleting it. How does
this aid in debugging?
Placing comment symbols /* */ around a code, also referred to as
“commenting out”, is a way of isolating some codes that you think maybe
causing errors in the program, without deleting the code. The idea is that if
the code is in fact correct, you simply remove the comment symbols and
continue on. It also saves you time and effort on having to retype the codes
if you have deleted it in the first place.

4) What is the equivalent code of the following statement


in WHILE LOOP format?
for (a=1; a<=100; a++)

printf ("%d\n", a * a);


Answer:
a=1;

while (a<=100) {

printf ("%d\n", a * a);

a++;

5) What is a stack?
A stack is one form of a data structure. Data is stored in stacks using the
FILO (First In Last Out) approach. At any particular instance, only the top of
the stack is accessible, which means that in order to retrieve data that is
stored inside the stack, those on the upper part should be extracted first.
Storing data in a stack is also referred to as a PUSH, while data retrieval is
referred to as a POP.

6) What is a sequential access file?


When writing programs that will store and retrieve data in a file, it is
possible to designate that file into different forms. A sequential access file
is such that data are saved in sequential order: one data is placed into the
file after another. To access a particular data within the sequential access
file, data has to be read one data at a time, until the right one is reached.

7) What is variable initialization and why is it important?


This refers to the process wherein a variable is assigned an initial value
before it is used in the program. Without initialization, a variable would
have an unknown value, which can lead to unpredictable outputs when
used in computations or other operations.

8 What is spaghetti programming?


Spaghetti programming refers to codes that tend to get tangled and
overlapped throughout the program. This unstructured approach to
coding is usually attributed to lack of experience on the part of the
programmer. Spaghetti programing makes a program complex and
analyzing the codes difficult, and so must be avoided as much as possible.

9) Differentiate Source Codes from Object Codes


Source codes are codes that were written by the programmer. It is made
up of the commands and other English-like keywords that are supposed to
instruct the computer what to do. However, computers would not be able
to understand source codes. Therefore, source codes are compiled using a
compiler. The resulting outputs are object codes, which are in a format
that can be understood by the computer processor. In C programming,
source codes are saved with the file extension .C, while object codes are
saved with the file extension .OBJ

10) In C programming, how do you insert quote characters


(‘ and “) into the output screen?
This is a common problem for beginners because quotes are normally part
of a printf statement. To insert the quote character as part of the output,
use the format specifiers \’ (for single quote), and \” (for double quote).

11) What is the use of a ‘\0’ character?


It is referred to as a terminating null character, and is used primarily to
show the end of a string value.

12) What is the difference between the = symbol and ==


symbol?
The = symbol is often used in mathematical operations. It is used to assign
a value to a given variable. On the other hand, the == symbol, also known
as “equal to” or “equivalent to”, is a relational operator that is used to
compare two values.
13) What is the modulus operator?
The modulus operator outputs the remainder of a division. It makes use of
the percentage (%) symbol. For example: 10 % 3 = 1, meaning when you
divide 10 by 3, the remainder is 1.

14) What is a nested loop?


A nested loop is a loop that runs within another loop. Put it in another
sense, you have an inner loop that is inside an outer loop. In this scenario,
the inner loop is performed a number of times as specified by the outer
loop. For each turn on the outer loop, the inner loop is first performed.

15) Which of the following operators is incorrect and why?


( >=, <=, <>, ==)
<> is incorrect. While this operator is correctly interpreted as “not equal to”
in writing conditional statements, it is not the proper operator to be used
in C programming. Instead, the operator != must be used to indicate “not
equal to” condition.

16) Compare and contrast compilers from interpreters.


Compilers and interpreters often deal with how program codes are
executed. Interpreters execute program codes one line at a time, while
compilers take the program as a whole and convert it into object code,
before executing it. The key difference here is that in the case of
interpreters, a program may encounter syntax errors in the middle of
execution, and will stop from there. On the other hand, compilers check
the syntax of the entire program and will only proceed to execution when
no syntax errors are found.

17) How do you declare a variable that will hold string


values?
The char keyword can only hold 1 character value at a time. By creating an
array of characters, you can store string values in it. Example: “char
MyName[50]; ” declares a string variable named MyName that can hold a
maximum of 50 characters.

18) Can the curly brackets { } be used to enclose a single


line of code?
While curly brackets are mainly used to group several lines of codes, it will
still work without error if you used it for a single line. Some programmers
prefer this method as a way of organizing codes to make it look clearer,
especially in conditional statements.

19) What are header files and what are its uses in C
programming?
Header files are also known as library files. They contain two essential
things: the definitions and prototypes of functions being used in a
program. Simply put, commands that you use in C programming are
actually functions that are defined from within each header files. Each
header file contains a set of functions. For example: stdio.h is a header file
that contains definition and prototypes of commands like printf and scanf.

20) What is syntax error?


Syntax errors are associated with mistakes in the use of a programming
language. It maybe a command that was misspelled or a command that
must was entered in lowercase mode but was instead entered with an
upper case character. A misplaced symbol, or lack of symbol, somewhere
within a line of code can also lead to syntax error.

21) What are variables and it what way is it different from


constants?
Variables and constants may at first look similar in a sense that both are
identifiers made up of one character or more characters (letters, numbers
and a few allowable symbols). Both will also hold a particular value. Values
held by a variable can be altered throughout the program, and can be used
in most operations and computations. Constants are given values at one
time only, placed at the beginning of a program. This value is not altered in
the program. For example, you can assigned a constant named PI and give
it a value 3.1415 . You can then use it as PI in the program, instead of
having to write 3.1415 each time you need it.

22) How do you access the values within an array?


Arrays contain a number of elements, depending on the size you gave it
during variable declaration. Each element is assigned a number from 0 to
number of elements-1. To assign or retrieve the value of a particular
element, refer to the element number. For example: if you have a
declaration that says “intscores[5];”, then you have 5 accessible elements,
namely: scores[0], scores[1], scores[2], scores[3] and scores[4].

23) Can I use “int” data type to store the value 32768?
Why?
No. “int” data type is capable of storing values from -32768 to 32767. To
store 32768, you can use “long int” instead. You can also use “unsigned
int”, assuming you don’t intend to store negative values.

24) Can two or more operators such as \n and \t be


combined in a single line of program code?
Yes, it’s perfectly valid to combine operators, especially if the need arises.
For example: you can have a code like printf (“Hello\n\n\’World\'”) to output
the text “Hello” on the first line and “World” enclosed in single quotes to
appear on the next two lines.

25) Why is it that not all header files are declared in every C
program?
The choice of declaring a header file at the top of each C program would
depend on what commands/functions you will be using in that program.
Since each header file contains different function definitions and
prototype, you would be using only those header files that would contain
the functions you will need. Declaring all header files in every program
would only increase the overall file size and load of the program, and is not
considered a good programming style.

26) When is the “void” keyword used in a function?


When declaring functions, you will decide whether that function would be
returning a value or not. If that function will not return a value, such as
when the purpose of a function is to display some outputs on the screen,
then “void” is to be placed at the leftmost part of the function header.
When a return value is expected after the function execution, the data type
of the return value is placed instead of “void”.

27) What are compound statements?


Compound statements are made up of two or more program statements
that are executed together. This usually occurs while handling conditions
wherein a series of statements are executed when a TRUE or FALSE is
evaluated. Compound statements can also be executed within a loop.
Curly brackets { } are placed before and after compound statements.

28) What is the significance of an algorithm to C


programming?
Before a program can be written, an algorithm has to be created first. An
algorithm provides a step by step procedure on how a solution can be
derived. It also acts as a blueprint on how a program will start and end,
including what process and computations are involved.

29) What is the advantage of an array over individual


variables?
When storing multiple related data, it is a good idea to use arrays. This is
because arrays are named using only 1 word followed by an element
number. For example: to store the 10 test results of 1 student, one can use
10 different variable names (grade1, grade2, grade3… grade10). With
arrays, only 1 name is used, the rest are accessible through the index name
(grade[0], grade[1], grade[2]… grade[9]).

30) Write a loop statement that will show the following


output:
1

12

123

1234

12345

Answer:
for (a=1; a<=5; i++) {

for (b=1; b<=a; b++)

printf("%d",b);

printf("\n");

}
31) What is wrong in this statement?
scanf(“%d”,whatnumber);
An ampersand & symbol must be placed before the variable name
whatnumber. Placing & means whatever integer value is entered by the
user is stored at the “address” of the variable name. This is a common
mistake for programmers, often leading to logical errors.

32) How do you generate random numbers in C?


Random numbers are generated in C using the rand() command. For
example: anyNum = rand() will generate any integer number beginning from 0,
assuming that anyNum is a variable of type integer.

33) What could possibly be the problem if a valid function


name such as tolower() is being reported by the C compiler
as undefined?
The most probable reason behind this error is that the header file for that
function was not indicated at the top of the program. Header files contain
the definition and prototype for functions and commands used in a C
program. In the case of “tolower()”, the code “#include <ctype.h>” must be
present at the beginning of the program.

34) What are comments and how do you insert it in a C


program?
Comments are a great way to put some remarks or description in a
program. It can serves as a reminder on what the program is all about, or a
description on why a certain code or function was placed there in the first
place. Comments begin with /* and ended by */ characters. Comments can
be a single line, or can even span several lines. It can be placed anywhere
in the program.

35) What is debugging?


Debugging is the process of identifying errors within a program. During
program compilation, errors that are found will stop the program from
executing completely. At this state, the programmer would look into the
possible portions where the error occurred. Debugging ensures the
removal of errors, and plays an important role in ensuring that the
expected program output is met.

36) What does the && operator do in a program code?


The && is also referred to as AND operator. When using this operator, all
conditions specified must be TRUE before the next action can be
performed. If you have 10 conditions and all but 1 fails to evaluate as
TRUE, the entire condition statement is already evaluated as FALSE

37) In C programming, what command or code can be used


to determine if a number of odd or even?
There is no single command or function in C that can check if a number is
odd or even. However, this can be accomplished by dividing that number
by 2, then checking the remainder. If the remainder is 0, then that number
is even, otherwise, it is odd. You can write it in code as:
if (num % 2 == 0)

printf("EVEN");

else

printf("ODD");
38) What does the format %10.2 mean when included in a
printf statement?
This format is used for two things: to set the number of spaces allotted for
the output number and to set the number of decimal places. The number
before the decimal point is for the allotted space, in this case it would allot
10 spaces for the output number. If the number of space occupied by the
output number is less than 10, addition space characters will be inserted
before the actual output number. The number after the decimal point sets
the number of decimal places, in this case, it’s 2 decimal spaces.

39) What are logical errors and how does it differ from
syntax errors?
Program that contains logical errors tend to pass the compilation process,
but the resulting output may not be the expected one. This happens when
a wrong formula was inserted into the code, or a wrong sequence of
commands was performed. Syntax errors, on the other hand, deal with
incorrect commands that are misspelled or not recognized by the
compiler.

40) What are the different types of control structures in


programming?
There are 3 main control structures in programming: Sequence, Selection
and Repetition. Sequential control follows a top to bottom flow in
executing a program, such that step 1 is first perform, followed by step 2,
all the way until the last step is performed. Selection deals with
conditional statements, which mean codes are executed depending on the
evaluation of conditions as being TRUE or FALSE. This also means that not
all codes may be executed, and there are alternative flows within.
Repetitions are also known as loop structures, and will repeat one or two
program statements set by a counter.

41) What is || operator and how does it function in a


program?
The || is also known as the OR operator in C programming. When using || to
evaluate logical conditions, any condition that evaluates to TRUE will
render the entire condition statement as TRUE.

42) Can the “if” function be used in comparing strings?


No. “if” command can only be used to compare numerical values and
single character values. For comparing string values, there is another
function called strcmp that deals specifically with strings.

43) What are preprocessor directives?


Preprocessor directives are placed at the beginning of every C program.
This is where library files are specified, which would depend on what
functions are to be used in the program. Another use of preprocessor
directives is the declaration of constants.Preprocessor directives begin
with the # symbol.
44) What will be the outcome of the following conditional
statement if the value of variable s is 10?
s >=10 && s < 25 && s!=12

The outcome will be TRUE. Since the value of s is 10, s >= 10 evaluates to
TRUE because s is not greater than 10 but is still equal to 10. s< 25 is also
TRUE since 10 is less then 25. Just the same, s!=12, which means s is not
equal to 12, evaluates to TRUE. The && is the AND operator, and follows
the rule that if all individual conditions are TRUE, the entire statement is
TRUE.

45) Describe the order of precedence with regards to


operators in C.
Order of precedence determines which operation must first take place in
an operation statement or conditional statement. On the top most level of
precedence are the unary operators !, +, – and &. It is followed by the
regular mathematical operators (*, / and modulus % first, followed by +
and -). Next in line are the relational operators <, <=, >= and >. This is then
followed by the two equality operators == and !=. The logical operators &&
and || are next evaluated. On the last level is the assignment operator =.

46) What is wrong with this statement? myName =


“Robin”;
You cannot use the = sign to assign values to a string variable. Instead, use
the strcpy function. The correct statement would be: strcpy(myName,
“Robin”);

47) How do you determine the length of a string value that


was stored in a variable?
To get the length of a string value, use the function strlen(). For example, if
you have a variable named FullName, you can get the length of the stored
string value by using this statement: I = strlen(FullName); the variable I will
now have the character length of the string value.

48) Is it possible to initialize a variable at the time it was


declared?
Yes, you don’t have to write a separate assignment statement after the
variable declaration, unless you plan to change it later on. For example:
char planet[15] = “Earth”; does two things: it declares a string variable
named planet, then initializes it with the value “Earth”.

49) Why is C language being considered a middle level


language?
This is because C language is rich in features that make it behave like a
high level language while at the same time can interact with hardware
using low level methods. The use of a well structured approach to
programming, coupled with English-like words used in functions, makes it
act as a high level language. On the other hand, C can directly access
memory structures similar to assembly language routines.

50) What are the different file extensions involved when


programming in C?
Source codes in C are saved with .C file extension. Header files or library
files have the .H file extension. Every time a program source code is
successfully compiled, it creates an .OBJ object file, and an
executable .EXE file.

51) What are reserved words?


Reserved words are words that are part of the standard C language library.
This means that reserved words have special meaning and therefore
cannot be used for purposes other than what it is originally intended for.
Examples of reserved words are int, void, and return.
52) What are linked list?
A linked list is composed of nodes that are connected with another. In C
programming, linked lists are created using pointers. Using linked lists is
one efficient way of utilizing memory for storage.

53) What is FIFO?


In C programming, there is a data structure known as queue. In this
structure, data is stored and accessed using FIFO format, or First-In-First-
Out. A queue represents a line wherein the first data that was stored will be
the first one that is accessible as well.

54) What are binary trees?


Binary trees are actually an extension of the concept of linked lists. A
binary tree has two pointers, a left one and a right one. Each side can
further branch to form additional nodes, which each node having two
pointers as well. Learn more about Binary Tree in Data Structure if you are
interested.

55) Not all reserved words are written in lowercase. TRUE


or FALSE?
FALSE. All reserved words must be written in lowercase; otherwise the C
compiler would interpret this as unidentified and invalid.

56) What is the difference between the expression “++a”


and “a++”?
In the first expression, the increment would happen first on variable a, and
the resulting value will be the one to be used. This is also known as a prefix
increment. In the second expression, the current value of variable a would
the one to be used in an operation, before the value of a itself is
incremented. This is also known as postfix increment.
57) What would happen to X in this expression: X += 15;
(assuming the value of X is 5)
X +=15 is a short method of writing X = X + 15, so if the initial value of X is 5,
then 5 + 15 = 20.

58) In C language, the variables NAME, name, and Name


are all the same. TRUE or FALSE?
FALSE. C language is a case sensitive language. Therefore, NAME, name
and Name are three uniquely different variables.

59) What is an endless loop?


An endless loop can mean two things. One is that it was designed to loop
continuously until the condition within the loop is met, after which a break
function would cause the program to step out of the loop. Another idea of
an endless loop is when an incorrect loop condition was written, causing
the loop to run erroneously forever. Endless loops are oftentimes referred
to as infinite loops.

60) What is a program flowchart and how does it help in


writing a program?
A flowchart provides a visual representation of the step by step procedure
towards solving a given problem. Flowcharts are made of symbols, with
each symbol in the form of different shapes. Each shape may represent a
particular entity within the entire program structure, such as a process, a
condition, or even an input/output phase.

61) What is wrong with this program statement? void = 10;


The word void is a reserved word in C language. You cannot use reserved
words as a user-defined variable.

62) Is this program statement valid? INT = 10.50;


Assuming that INT is a variable of type float, this statement is valid. One
may think that INT is a reserved word and must not be used for other
purposes. However, recall that reserved words are express in lowercase, so
the C compiler will not interpret this as a reserved word.

63) What are actual arguments?


When you create and use functions that need to perform an action on
some given values, you need to pass these given values to that function.
The values that are being passed into the called function are referred to as
actual arguments.

64) What is a newline escape sequence?


A newline escape sequence is represented by the \n character. This is used
to insert a new line when displaying data in the output screen. More spaces
can be added by inserting more \n characters. For example, \n\n would
insert two spaces. A newline escape sequence can be placed before the
actual output expression or after.

65) What is output redirection?


It is the process of transferring data to an alternative output source other
than the display screen. Output redirection allows a program to have its
output saved to a file. For example, if you have a program named
COMPUTE, typing this on the command line as COMPUTE >DATA can
accept input from the user, perform certain computations, then have the
output redirected to a file named DATA, instead of showing it on the screen

66) What are run-time errors?


These are errors that occur while the program is being executed. One
common instance wherein run-time errors can happen is when you are
trying to divide a number by zero. When run-time errors occur, program
execution will pause, showing which program line caused the error.
67) What is the difference between functions abs() and
fabs()?
These 2 functions basically perform the same action, which is to get the
absolute value of the given value. Abs() is used for integer values, while
fabs() is used for floating type numbers. Also, the prototype for abs() is
under <stdlib.h>, while fabs() is under <math.h>.

68) What are formal parameters?


In using functions in a C program, formal parameters contain the values
that were passed by the calling function. The values are substituted in
these formal parameters and used in whatever operations as indicated
within the main body of the called function.

69) What are control structures?


Control structures take charge at which instructions are to be performed in
a program. This means that program flow may not necessarily move from
one statement to the next one, but rather some alternative portions may
need to be pass into or bypassed from, depending on the outcome of the
conditional statements.

70) Write a simple code fragment that will check if a


number is positive or negative
If (num>=0)

printf("number is positive");

else

printf ("number is negative");


71) When is a “switch” statement preferable over an “if”
statement?
The switch statement is best used when dealing with selections based on a
single variable or expression. However, switch statements can only
evaluate integer and character data types.
72) What are global variables and how do you declare
them?
Global variables are variables that can be accessed and manipulated
anywhere in the program. To make a variable global, place the variable
declaration on the upper portion of the program, just after the
preprocessor directives section.

73) What are enumerated types?


Enumerated types allow the programmer to use more meaningful words
as values to a variable. Each item in the enumerated type variable is
actually associated with a numeric code. For example, one can create an
enumerated type variable named DAYS whose values are Monday,
Tuesday… Sunday.

74) What does the function toupper() do?


It is used to convert any letter to its upper case mode. Toupper() function
prototype is declared in <ctype.h>. Note that this function will only convert
a single character, and not an entire string.

75) Is it possible to have a function as a parameter in


another function?
Yes, that is allowed in C programming. You just need to include the entire
function prototype into the parameter field of the other function where it
is to be used.

76) What are multidimensional arrays?


Multidimensional arrays are capable of storing data in a two or more
dimensional structure. For example, you can use a 2 dimensional array to
store the current position of pieces in a chess game, or position of players
in a tic-tac-toe program.
77) Which function in C can be used to append a string to
another string?
The strcat function. It takes two parameters, the source string and the
string value to be appended to the source string.

78) What is the difference between functions getch() and


getche()?
Both functions will accept a character input value from the user. When
using getch(), the key that was pressed will not appear on the screen, and
is automatically captured and assigned to a variable. When using getche(),
the key that was pressed by the user will appear on the screen, while at the
same time being assigned to a variable.

79) Dothese two program statements perform the same


output? 1) scanf(“%c”, &letter); 2) letter=getchar()
Yes, they both do the exact same thing, which is to accept the next key
pressed by the user and assign it to variable named letter.

80) What are structure types in C?


Structure types are primarily used to store records. A record is made up of
related fields. This makes it easier to organize a group of related data.

81) What does the characters “r” and “w” mean when
writing programs that will make use of files?
“r” means “read” and will open a file as input wherein data is to be
retrieved. “w” means “write”, and will open a file for output. Previous data
that was stored on that file will be erased.
82) What is the difference between text files and binary
files?
Text files contain data that can easily be understood by humans. It
includes letters, numbers and other characters. On the other hand, binary
files contain 1s and 0s that only computers can interpret.

83) is it possible to create your own header files?


Yes, it is possible to create a customized header file. Just include in it the
function prototypes that you want to use in your program, and use the
#include directive followed by the name of your header file.

84) What is dynamic data structure?


Dynamic data structure provides a means for storing data more efficiently
into memory. Using Using dynamic memory allocation, your program will
access memory spaces as needed. This is in contrast to static data
structure, wherein the programmer has to indicate a fix number of
memory space to be used in the program.

85) What are the different data types in C?


The basic data types in C are int, char, and float. Int is used to declare
variables that will be storing integer values. Float is used to store real
numbers. Char can store individual character values.

86) What is the general form of a C program?


A C program begins with the preprocessor directives, in which the
programmer would specify which header file and what constants (if any) to
be used. This is followed by the main function heading. Within the main
function lies the variable declaration and program statement.
87) What is the advantage of a random access file?
If the amount of data stored in a file is fairly large, the use of random
access will allow you to search through it quicker. If it had been a
sequential access file, you would have to go through one record at a time
until you reach the target data. A random access file lets you jump directly
to the target address where data is located.

88) In a switch statement, what will happen if a break


statement is omitted?
If a break statement was not placed at the end of a particular case portion?
It will move on to the next case portion, possibly causing incorrect output.

89) Describe how arrays can be passed to a user defined


function
One thing to note is that you cannot pass the entire array to a function.
Instead, you pass to it a pointer that will point to the array first element in
memory. To do this, you indicate the name of the array without the
brackets.

90) What are pointers?


Pointers point to specific areas in the memory. Pointers contain the
address of a variable, which in turn may contain a value or even an address
to another memory.

91) Can you pass an entire structure to functions?


Yes, it is possible to pass an entire structure to a function in a call by
method style. However, some programmers prefer declaring the structure
globally, then pass a variable of that structure type to a function. This
method helps maintain consistency and uniformity in terms of argument
type.

92) What is gets() function?


The gets() function allows a full line data entry from the user. When the user
presses the enter key to end the input, the entire line of characters is
stored to a string variable. Note that the enter key is not included in the
variable, but instead a null terminator \0 is placed after the last character.

93) The % symbol has a special use in a printf statement.


How would you place this character as part of the output
on the screen?
You can do this by using %% in the printf statement. For example, you can
write printf(“10%%”) to have the output appear as 10% on the screen.

94) How do you search data in a data file using random


access method?
Use the fseek() function to perform random access input/ouput on a file.
After the file was opened by the fopen() function, the fseek would require
three parameters to work: a file pointer to the file, the number of bytes to
search, and the point of origin in the file.

95) Are comments included during the compilation stage


and placed in the EXE file as well?
No, comments that were encountered by the compiler are disregarded.
Comments are mostly for the guidance of the programmer only and do not
have any other significant use in the program functionality.
96) Is there a built-in function in C that can be used for
sorting data?
Yes, use the qsort() function. It is also possible to create user defined
functions for sorting, such as those based on the balloon sort and bubble
sort algorithm.

97) What are the advantages and disadvantages of a heap?


Storing data on the heap is slower than it would take when using the stack.
However, the main advantage of using the heap is its flexibility. That’s
because memory in this structure can be allocated and remove in any
particular order. Slowness in the heap can be compensated if an algorithm
was well designed and implemented.

98) How do you convert strings to numbers in C?


You can write you own functions to do string to number conversions, or
instead use C’s built in functions. You can use atof to convert to a floating
point value, atoi to convert to an integer value, and atol to convert to a
long integer value.

99) Create a simple code fragment that will swap the


values of two variables num1 and num2.
int temp;

temp = num1;

num1 = num2;

num2 = temp;
100) What is the use of a semicolon (;) at the end of every
program statement?
It has to do with the parsing process and compilation of the code. A
semicolon acts as a delimiter, so that the compiler knows where each
statement ends, and can proceed to divide the statement into smaller
elements for syntax checking.

These interview questions will also help in your viva(orals)

1. Write a C program to print your name, date of birth, and mobile


number.
Expected Output:
Name : Alexandra Abramov
DOB : July 14, 1975
Mobile : 99-9999999999

Write a C program to print your name, date of birth, and mobile


number.
#include <stdio.h>

int main()
{
// Print Name
printf("Name : Alexandra Abramov\n");

// Print Date of Birth


printf("DOB : July 14, 1975\n");

// Print Mobile Number


printf("Mobile : 99-9999999999\n");

// Indicate successful execution


return(0);
}

Explanation:

In the exercise above -


 #include <stdio.h>: This line includes the standard input-output
library, which contains functions for reading and writing data to
and from the console.

 int main(): This is the main function of the program, where


execution begins. It returns an integer value, typically 0, to
indicate successful execution.

 Inside the "main()" function, there are three printf statements.


The "printf()" function is used to print formatted text to the
console. Each printf statement prints a line of text with specific
information:

o printf("Name : Alexandra Abramov\n"); prints "Name :


Alexandra Abramov" followed by a newline character,
which moves the cursor to the next line.

o printf("DOB : July 14, 1975\n"); prints "DOB : July 14, 1975"


followed by a newline character.

o printf("Mobile : 99-9999999999\n"); prints "Mobile : 99-


9999999999" followed by a newline character.

 return(0);: This line indicates the end of the main function and
returns 0.

Sample Output:
Name : Alexandra Abramov
DOB : July 14, 1975
Mobile : 99-9999999999

2. Write a C program to get the C version you are using.


Expected Output:
We are using C18!

Write a C program to get the C version you are using.

#include <stdio.h>
int main(int argc, char** argv) {
// Check for C standard version
#if __STDC_VERSION__ >= 201710L
printf("We are using C18!\n");
#elif __STDC_VERSION__ >= 201112L
printf("We are using C11!\n");
#elif __STDC_VERSION__ >= 199901L
printf("We are using C99!\n");
#else
printf("We are using C89/C90!\n");
#endif

Explanation:

In the exercise above -

 #include : This line includes the standard input-output library,


which is necessary for using "printf".

 int main(int argc, char** argv): This is the main function with
command-line arguments argc and argv. However, in this code,
these arguments are not used.

 The code uses preprocessor directives (#if, #elif, #else, and


#endif) to conditionally compile different print statements based
on the version of the C standard detected by the compiler:

o #if __STDC_VERSION__ >= 201710L checks if the C standard


version is greater than or equal to C18 (2017). If true, it
prints "We are using C18!".

o #elif __STDC_VERSION__ >= 201112L checks if the C


standard version is greater than or equal to C11 (2011). If
true, it prints "We are using C11!".

o #elif __STDC_VERSION__ >= 199901L checks if the C


standard version is greater than or equal to C99 (1999). If
true, it prints "We are using C99!".
o #else is a fallback condition that triggers if none of the
above conditions are met. It prints "We are using C89/C90!".

 return 0;: This line indicates the end of the main function and
returns 0 to the operating system, indicating a successful
program execution.

Sample Output:
We are using C18!

3. Write a C program to print a block F using the hash (#), where


the F has a height of six characters and width of five and four
characters. And also print a very large 'C'.
Expected Output:
######
#
#
#####
#
#
#
######
## ##
#
#
#
#
#
## ##
######
Write a C program to print a block F using the hash (#), where the
F has a height of six characters and width of five and four
characters. And also print a very large 'C'.

Block of 'F':

C Code:

#include <stdio.h>

int main()
{
// Print a line of hashes
printf("######\n");

// Print a single hash


printf("#\n");

// Print a single hash


printf("#\n");

// Print a line of hashes


printf("#####\n");

// Print a single hash


printf("#\n");

4. Write a C program to print the following characters in reverse.


Test Characters: 'X', 'M', 'L'
Expected Output:
The reverse of XML is LMX

Write a C program to print the following characters in reverse.

Pictorial Presentation:

Test Characters : 'X', 'M', 'L'


C Code:

#include <stdio.h>

int main()
{
// Declare and initialize character variables
char char1 = 'X';
char char2 = 'M';
char char3 = 'L';

// Print the original and reversed characters


printf("The reverse of %c%c%c is %c%c%c\n",
char1, char2, char3,
char3, char2, char1);
return(0);
}Explanation:

In the exercise above -

#include <stdio.h> - This code includes the standard input/output


library <stdio.h>.

 In the "main()" function, it declares three character variables:


'char1', 'char2', and 'char3', and assigns them the values 'X', 'M',
and 'L' respectively.

 It uses the "printf()" function to display a formatted message.


The message contains placeholders specified by %c, which
represent characters.

 Inside the "printf()" function, it provides the values to substitute


for the placeholders. In this case, it provides 'char1', 'char2', and
'char3' followed by their reverse order: 'char3', 'char2', and
'char1'.

 The program will print: "The reverse of XML is LMX" because it


swaps characters in reverse order.

 Finally, the main function returns 0 to indicate successful


program execution.

Sample Output:
The reverse of XML is LMX

5. Write a C program to compute the perimeter and area of a


rectangle with a height of 7 inches and width of 5 inches.
Expected Output:
Perimeter of the rectangle = 24 inches
Area of the rectangle = 35 square inches

Write a C program to compute the perimeter and area of a


rectangle with a height of 7 inches and width of 5 inches.
C programming: Perimeter of a rectangle

A perimeter is a path that surrounds a two-dimensional shape.


The word comes from the Greek peri (around) and meter
(measure). The perimeter can be used to calculate the length of
fence required to surround a yard or garden. For rectangles or
kites which have only two different side lengths, say x and y, the
perimeter is equal to 2x + 2y

C programming: Area of a rectangle

The area of a two-dimensional figure describes the amount of


surface the shape covers. You measure area in square units of a
fixed size, square units of measure are square inches, square
centimeters, or square miles etc. The formula for the area of a
rectangle uses multiplication: length • width = area. A
rectangle with four sides of equal length is a square.

C Code:
#include <stdio.h>

/*
Variables to store the width and height of a rectangle in inches
*/
int width;
int height;

int area; /* Variable to store the area of the rectangle */


int perimeter; /* Variable to store the perimeter of the
rectangle */

int main() {
/* Assigning values to height and width */
height = 7;
width = 5;

/* Calculating the perimeter of the rectangle */


perimeter = 2*(height + width);
printf("Perimeter of the rectangle = %d inches\n", perimeter);

/* Calculating the area of the rectangle */


area = height * width;
printf("Area of the rectangle = %d square inches\n", area);

return(0);
}

Explanation:

In the exercise above -

 The program includes the standard input/output library <stdio.h>.

 It declares several integer variables:

o width: Represents the rectangle width in inches.

o height: Represents the height of the rectangle in inches.

o area: Will store the calculated rectangle area.

o perimeter: Will store the calculated rectangle perimeter.

 In the "main()" function:

o It assigns the values 7 to the 'height' variable and 5 to the


'width' variable, representing the rectangle's dimensions.

 The program then calculates the rectangle's perimeter and area:

o Perimeter: It uses the formula 2 * (height + width) to


calculate the perimeter of the rectangle and stores the
result in the 'perimeter' variable.

o Area: It calculates the area using the formula height * width


and stores the result in the 'area' variable.

 Finally, the program uses the "printf()" function to display the


calculated values:

o It prints the calculated perimeter with a message:


"Perimeter of the rectangle = [perimeter] inches."

o It prints the calculated area with a message: "Area of the


rectangle = [area] square inches."
 The program returns 0 to indicate successful execution.

Sample Output:
Perimeter of the rectangle = 24 inches
Area of the rectangle = 35 square inches

6. Write a C program to compute the perimeter and area of a


circle with a given radius.
Expected Output:
Perimeter of the Circle = 37.680000 inches
Area of the Circle = 113.040001 square inches

Write a C program to compute the perimeter and area of a circle


with a given radius.

C programming: Area and circumference of a circle

In geometry, the area enclosed by a circle of radius r is πr2. Here


the Greek letter π represents a constant, approximately equal to
3.14159, which is equal to the ratio of the circumference of any
circle to its diameter.

The circumference of a circle is the linear distance around


its edge.

C Code:
#include <stdio.h>

int main() {
int radius; /* Variable to store the radius of the circle */
float area, perimeter; /* Variables to store the area and
perimeter of the circle */
radius = 6; /* Assigning a value to the radius */

/* Calculating the perimeter of the circle */


perimeter = 2 * 3.14 * radius;
printf("Perimeter of the Circle = %f inches\n", perimeter);
/* Calculating the area of the circle */
area = 3.14 * radius * radius;
printf("Area of the Circle = %f square inches\n", area);

return(0);
}

Explanation:

In the exercise above -

 The program includes the standard input/output library <stdio.h>.

 It declares several variables:

o int radius: Represents the circle radius.

o float area and float perimeter: Will store the calculated area
and perimeter of the circle.

 In the "main()" function:

o It assigns the value 6 to the 'radius' variable, representing


the circle radius.

 The program then calculates the circle's perimeter and area:

o Perimeter: It uses the formula 2*3.14* radius to calculate


the circle perimeter and stores the result in the 'perimeter'
variable. Here, 3.14 is an approximation of the
mathematical constant π (pi).

o Area: It calculates the area using the formula


3.14*radius*radius (π * r^2) and stores the result in the
'area' variable.

 Finally, the program uses the "printf()" function to display the


calculated values:

o It prints the calculated perimeter with a message:


"Perimeter of the Circle = [perimeter] inches."

o It prints the calculated area with a message: "Area of the


Circle = [area] square inches."
 The program returns 0 to indicate successful execution.

Sample Output:
Perimeter of the Circle = 37.680000 inches
Area of the Circle = 113.040001 square inches

7. Write a C program to display multiple variables.


Sample Variables :
a+ c, x + c,dx + x, ((int) dx) + ax, a + x, s + b, ax + b, s + c, ax + c,
ax + ux
Declaration :
int a = 125, b = 12345;
long ax = 1234567890;
short s = 4043;
float x = 2.13459;
double dx = 1.1415927;
char c = 'W';
unsigned long ux = 2541567890;

C Code:
#include <stdio.h>

int main()

int a = 125, b = 12345; /* Declare and initialize integer


variables */

long ax = 1234567890; /* Declare and initialize long


integer variable */

short s = 4043; /* Declare and initialize short


integer variable */

float x = 2.13459; /* Declare and initialize floating-


point variable */
double dx = 1.1415927; /* Declare and initialize double
precision variable */

char c = 'W'; /* Declare and initialize character


variable */

unsigned long ux = 2541567890; /* Declare and initialize unsigned


long integer variable */

/* Various arithmetic operations and type conversions */

printf("a + c = %d\n", a + c);

printf("x + c = %f\n", x + c);

printf("dx + x = %f\n", dx + x);

printf("((int) dx) + ax = %ld\n", ((int) dx) + ax);

printf("a + x = %f\n", a + x);

printf("s + b = %d\n", s + b);

printf("ax + b = %ld\n", ax + b);

printf("s + c = %hd\n", s + c);

printf("ax + c = %ld\n", ax + c);

printf("ax + ux = %lu\n", ax + ux);

return 0;

Copy
Sample Output:
a + c = 212
x + c = 89.134590
dx + x = 3.276183
((int) dx) + ax = 1234567891
a + x = 127.134590
s + b = 16388
ax + b = 1234580235
s + c = 4130
ax + c = 1234567977
ax + ux = 3776135780

8. Write a C program to convert specified days into years, weeks


and days.
Note: Ignore leap year.

Test Data :
Number of days : 1329
Expected Output :
Years: 3
Weeks: 33
Days: 3

Write a C program to convert specified days into years, weeks


and days.
Note: Ignore leap year.
Test Data :
Number of days : 1329
C Code:

#include <stdio.h>

int main()

int days, years, weeks;

days = 1329; // Total number of days

// Converts days to years, weeks and days

years = days/365; // Calculate years


weeks = (days % 365)/7; // Calculate weeks

days = days - ((years*365) + (weeks*7)); // Calculate remaining


days

// Print the results

printf("Years: %d\n", years);

printf("Weeks: %d\n", weeks);

printf("Days: %d \n", days);

return 0;

Explanation:

In the exercise above -

 The program includes the standard input/output library <stdio.h>.

 It declares three integer variables:

o int days: This variable stores the total number of days to be


converted.

o int years: It stores the calculated number of years.

o int weeks: It stores the calculated number of weeks.

 The program initializes the 'days' variable with 1329.

 It then converts:

o years = days / 365: This division calculates the number of


years in the given number of days. Since there are
approximately 365 days in a year, this division gives an
estimate of the number of years.
o weeks = (days % 365) / 7: After calculating the years, the
program uses the modulo operator % to find the remaining
days that couldn't be represented in full years. It then
divides this remainder by 7 to calculate the number of
weeks.

o Finally, it subtracts the days accounted for by years and


weeks to get the remaining days.

 The program uses printf statements to display the calculated


values:

o It prints the number of years with the message: "Years:


[years]."

o It prints the number of weeks with the message: "Weeks:


[weeks]."

o It prints the remaining days with the message: "Days:


[days]."

 The program returns 0 to indicate successful execution.

Sample Output:
Years: 3
Weeks: 33
Days: 3

9. Write a C program that accepts two integers from the user


and calculates the sum of the two integers.
Test Data :
Input the first integer: 25
Input the second integer: 38
Expected Output:
Sum of the above two integers = 63

Write a C program that accepts two integers from the user and
calculates the sum of the two integers.

C Code:
#include <stdio.h>

int main()

int x, y, sum; // Declare variables for two integers and their sum

// Prompt user for input and store in 'x'

printf("\nInput the first integer: ");

scanf("%d", &x);

// Prompt user for input and store in 'y'

printf("\nInput the second integer: ");

scanf("%d", &y);

sum = x + y; // Calculate the sum of 'x' and 'y'

// Print the sum

printf("\nSum of the above two integers = %d\n", sum);

return 0; // Indicate successful execution

Copy
Sample Output:
Input the first integer: 25
Input the second integer: 38

Sum of the above two integers = 63

10. Write a C program that accepts two integers from the user
and calculates the product of the two integers.
Test Data :
Input the first integer: 25
Input the second integer: 15
Expected Output:
Product of the above two integers = 375

C Code:

#include <stdio.h>

int main()

int x, y, result; // Declare variables for two integers and their


product

// Prompt user for input and store in 'x'

printf("\nInput the first integer: ");

scanf("%d", &x);

// Prompt user for input and store in 'y'

printf("\nInput the second integer: ");

scanf("%d", &y);
result = x * y; // Calculate the product of 'x' and 'y'

// Print the product

printf("Product of the above two integers = %d\n", result);

Copy
Sample Output:
Input the first integer: 25

Input the second integer: 15


Product of the above two integers = 375
11. Write a C program that accepts two item's weight and
number of purchases (floating point values) and calculates their
average value.
Test Data :
Weight - Item1: 15
No. of item1: 5
Weight - Item2: 25
No. of item2: 4
Expected Output:
Average Value = 19.444444

C Code:

#include <stdio.h>

int main()

double wi1, ci1, wi2, ci2, result; // Declare variables for


weights and counts

// Prompt user for weight and count of item 1

printf("Weight - Item1: ");

scanf("%lf", &wi1);
// Prompt user for count of item 1

printf("No. of item1: ");

scanf("%lf", &ci1);

// Prompt user for weight and count of item 2

printf("Weight - Item2: ");

scanf("%lf", &wi2);

// Prompt user for count of item 2

printf("No. of item2: ");

scanf("%lf", &ci2);

// Calculate average value

result = ((wi1 * ci1) + (wi2 * ci2)) / (ci1 + ci2);

// Print the average value

printf("Average Value = %f\n", result);

return 0;

Sample Output:
Weight - Item1: 15
No. of item1: 5
Weight - Item2: 25
No. of item2: 4
Average Value = 19.444444
12. Write a C program that accepts an employee's ID, total
worked hours in a month and the amount he received per hour.
Print the ID and salary (with two decimal places) of the employee
for a particular month.
Test Data :
Input the Employees ID(Max. 10 chars): 0342
Input the working hrs: 8
Salary amount/hr: 15000
Expected Output:
Employees ID = 0342
Salary = U$ 120000.00

C Code:

#include <stdio.h>

int main() {

char id[10]; // Variable to store employee ID (up to 10


characters)

int hour; // Variable to store working hours

double value, salary; // Variables for hourly salary and total


salary

// Prompt user for employee ID

printf("Input the Employees ID(Max. 10 chars): ");

scanf("%s", &id);

// Prompt user for working hours

printf("\nInput the working hrs: ");

scanf("%d", &hour);
// Prompt user for hourly salary

printf("\nSalary amount/hr: ");

scanf("%lf", &value);

// Calculate total salary

salary = value * hour;

// Print employee ID and salary

printf("\nEmployees ID = %s\nSalary = U$ %.2lf\n", id, salary);

return 0;

Copy
Sample Output:
Input the Employees ID(Max. 10 chars): 0342

Input the working hrs: 8

Salary amount/hr: 15000

Employees ID = 0342
Salary = U$ 120000.00

13. Write a C program that accepts three integers and finds the
maximum of three.
Test Data :
Input the first integer: 25
Input the second integer: 35
Input the third integer: 15
Expected Output:
Maximum value of three integers: 35
C Code:

#include <stdio.h>

#include <stdlib.h>

int main()

int x, y, z, result, max; // Declare variables

// Prompt user for the first integer and store in 'x'

printf("\nInput the first integer: ");

scanf("%d", &x);

// Prompt user for the second integer and store in 'y'

printf("\nInput the second integer: ");

scanf("%d", &y);

// Prompt user for the third integer and store in 'z'

printf("\nInput the third integer: ");

scanf("%d", &z);

// Calculate the result

result = (x + y + abs(x - y)) / 2;

// Calculate the maximum value

max = (result + z + abs(result - z)) / 2;


// Print the maximum value

printf("\nMaximum value of three integers: %d", max);

printf("\n");

return 0;

Copy
Sample Output:
Input the first integer: 25

Input the second integer: 35

Input the third integer: 15

Maximum value of three integers: 35

14. Write a C program to calculate a bike’s average consumption


from the given total distance (integer value) travelled (in km) and
spent fuel (in litters, float number – 2 decimal points).
Test Data :
Input total distance in km: 350
Input total fuel spent in liters: 5
Expected Output:
Average consumption (km/lt) 70.000

C Code:

#include <stdio.h>

int main()

int x; // Variable to store total distance in km

float y; // Variable to store total fuel spent in liters


// Prompt user for total distance and store in 'x'

printf("Input total distance in km: ");

scanf("%d",&x);

// Prompt user for total fuel spent and store in 'y'

printf("Input total fuel spent in liters: ");

scanf("%f", &y);

// Calculate and print average consumption

printf("Average consumption (km/lt) %.3f ",x/y);

printf("\n");

return 0;

Copy
Sample Output:
Input total distance in km: 350
Input total fuel spent in liters: 5
Average consumption (km/lt) 70.000

15. Write a C program to calculate the distance between two


points.
Test Data :
Input x1: 25
Input y1: 15
Input x2: 35
Input y2: 10
Expected Output:
Distance between the said points: 11.1803
Write a C program to calculate the distance between two points.
Note: x1, y1, x2, y2 are all double values.

Formula:

C Code:

#include <stdio.h>

#include <math.h>

int main() {

float x1, y1, x2, y2, gdistance; // Declare variables for


coordinates and distance

// Prompt user for coordinates (x1, y1) and store them

printf("Input x1: ");

scanf("%f", &x1);

printf("Input y1: ");

scanf("%f", &y1);

// Prompt user for coordinates (x2, y2) and store them

printf("Input x2: ");

scanf("%f", &x2);

printf("Input y2: ");

scanf("%f", &y2);
// Calculate squared distance between points

gdistance = ((x2-x1)*(x2-x1))+((y2-y1)*(y2-y1));

// Calculate and print the distance between the points

printf("Distance between the said points: %.4f", sqrt(gdistance));

printf("\n");

return 0;

Copy
Explanation:

In the exercise above -

 First, the program includes two standard libraries: <stdio.h> for


input/output functions and <math.h> to use the sqrt() function for
calculating the square root.

 It declares the following variables:

o float x1, y1, x2, y2: These variables will store the
coordinates of two points in the form (x, y) where (x1, y1)
are the coordinates of the first point, and (x2, y2) are the
coordinates of the second point.

o float gdistance: This variable stores the squared distance


between the two points.

 The program prompts the user to input the coordinates of the


first point:

o It uses "printf()" function to display "Input x1:" to instruct


the user to input the x-coordinate of the first point.

o It uses "scanf()" function to read the user's input and store


it in the variable 'x1'.
o It repeats the same process for the y-coordinate of the first
point ('y1') and then for the coordinates of the second point
('x2' and 'y2').

 It calculates the squared distance between the two points using


the distance formula for two points (x1, y1) and (x2, y2):

o gdistance = ((x2 - x1)*(x2 - x1)) + ((y2 - y1)*(y2 - y1)): This


formula computes the square of the distance between the
points.

 The program uses the "printf()" function to display the result:

o It prints "Distance between the said points: " along with the
calculated square root of 'gdistance' using sqrt(gdistance).

o The %.4f format specifier displays the result with four


decimal places.

 Finally, the program returns 0 to indicate successful execution.

Sample Output:
Input x1: 25
Input y1: 15
Input x2: 35
Input y2: 10
Distance between the said points: 11.1803

16. Write a C program to read an amount (integer value) and


break the amount into the smallest possible number of bank
notes.
Test Data :
Input the amount: 375
Expected Output:
There are:
3 Note(s) of 100.00
1 Note(s) of 50.00
1 Note(s) of 20.00
0 Note(s) of 10.00
1 Note(s) of 5.00
0 Note(s) of 2.00
0 Note(s) of 1.00

C Code:

#include <stdio.h>

int main() {

int amt, total; // Declare variables for amount and total

// Prompt user for the amount and store it in 'amt'

printf("Input the amount: ");

scanf("%d",&amt);

// Calculate and print the number of each denomination

total = (int)amt/100;

printf("There are:\n");

printf("%d Note(s) of 100.00\n", total);

amt = amt-(total*100);

total = (int)amt/50;

printf("%d Note(s) of 50.00\n", total);

amt = amt-(total*50);

total = (int)amt/20;

printf("%d Note(s) of 20.00\n", total);

amt = amt-(total*20);
total = (int)amt/10;

printf("%d Note(s) of 10.00\n", total);

amt = amt-(total*10);

total = (int)amt/5;

printf("%d Note(s) of 5.00\n", total);

amt = amt-(total*5);

total = (int)amt/2;

printf("%d Note(s) of 2.00\n", total);

amt = amt-(total*2);

total = (int)amt/1;

printf("%d Note(s) of 1.00\n", total);

return 0;

Copy
Explanation:

In the exercise above -

 First, the program includes the standard library for input/output


functions.

 It declares the following variables:

o int amt: This variable stores the input amount.


o int total: This variable will be used to calculate the number
of each denomination of currency notes.

 The program prompts the user to input the amount:

o It uses "printf()" function to display "Input the amount: " to


instruct the user to input the amount.

o It uses "scanf()" function to read the user's input and store


it in the variable amt.

 The program calculates the number of each denomination of


currency notes:

o Starting with the largest denomination and moving to the


smallest, it calculates the number of notes needed for each
denomination.

o For each denomination (e.g., 100, 50, 20, etc.), it calculates


the number of notes and updates the 'total' variable
accordingly.

o After calculating the number of notes for each


denomination, it subtracts the total value of those notes
from the remaining amount (amt) to continue with the next
denomination.

 The program uses "printf()" function to display the number of


notes for each denomination:

o It prints the number of notes for each denomination, using


the 'total' variable.

o The format is "X Note(s) of Y.YY" where X is the number of


notes, and Y.YY is the denomination.

 Finally, the program returns 0 to indicate successful execution.

Sample Output:
Input the amount: 375
There are:
3 Note(s) of 100.00
1 Note(s) of 50.00
1 Note(s) of 20.00
0 Note(s) of 10.00
1 Note(s) of 5.00
0 Note(s) of 2.00
0 Note(s) of 1.00

17. Write a C program to convert a given integer (in seconds) to


hours, minutes and seconds.
Test Data :
Input seconds: 25300
Expected Output:
There are:
H:M:S - 7:1:40

C Code:

#include <stdio.h>

int main() {

int sec, h, m, s; // Declare variables for seconds, hours,


minutes, and seconds

// Prompt user for input seconds and store in 'sec'

printf("Input seconds: ");

scanf("%d", &sec);

// Calculate hours, minutes, and remaining seconds

h = (sec/3600);

m = (sec -(3600*h))/60;

s = (sec -(3600*h)-(m*60));

// Print the time in format H:M:S

printf("H:M:S - %d:%d:%d\n",h,m,s);
return 0;

Copy
Sample Output:
Input seconds: 25300
H:M:S - 7:1:40

18. Write a C program to convert a given integer (in days) to


years, months and days, assuming that all months have 30 days
and all years have 365 days.
Test Data :
Input no. of days: 2535
Expected Output:
6 Year(s)
11 Month(s)
15 Day(s)

C Code:

#include <stdio.h>

int main() {

int ndays, y, m, d; // Declare variables for number of days,


years, months, and days

// Prompt user for input number of days and store in 'ndays'

printf("Input no. of days: ");

scanf("%d", &ndays);

// Calculate years, months, and remaining days

y = (int) ndays/365;
ndays = ndays-(365*y);

m = (int)ndays/30;

d = (int)ndays-(m*30);

// Print the result

printf(" %d Year(s) \n %d Month(s) \n %d Day(s)", y, m, d);

return 0;

Copy
Sample Output:
Input no. of days: 2535
6 Year(s)
11 Month(s)
15 Day(s)

19. Write a C program that accepts 4 integers p, q, r, s from the


user where q, r and s are positive and p is even. If q is greater
than r and s is greater than p and if the sum of r and s is greater
than the sum of p and q print "Correct values", otherwise print
"Wrong values".
Test Data :
Input the second integer: 35
Input the third integer: 15
Input the fourth integer: 46
Expected Output:
Wrong values

Test Data :
Input the second integer: 35
Input the third integer: 15
Input the fourth integer: 46
Expected Output:
Wrong values

C Code:

#include <stdio.h>

int main() {

int p, q, r, s; // Declare variables for four integers

// Prompt user for the first integer and store in 'p'

printf("\nInput the first integer: ");

scanf("%d", &p);

// Prompt user for the second integer and store in 'q'

printf("\nInput the second integer: ");

scanf("%d", &q);

// Prompt user for the third integer and store in 'r'

printf("\nInput the third integer: ");

scanf("%d", &r);

// Prompt user for the fourth integer and store in 's'

printf("\nInput the fourth integer: ");

scanf("%d", &s);

// Check conditions for correctness

if((q > r) && (s > p) && ((r+s) > (p+q)) && (r > 0) && (s > 0) &&
(p%2 == 0))
{

printf("\nCorrect values\n");

else {

printf("\nWrong values\n");

return 0;

Sample Output:
Input the first integer: 25

Input the second integer: 35

Input the third integer: 15

Input the fourth integer: 46

Wrong values

20. Write a C program to print the roots of Bhaskara’s formula


from the given three floating numbers. Display a message if it is
not possible to find the roots.
Test Data :
Input the first number(a): 25
Input the second number(b): 35
Input the third number(c): 12
Expected Output:
Root1 = -0.60000
Root2 = -0.80000

C Code:

#include <stdio.h>
#include <math.h>

// Include math.h header file for mathematical functions

int main() {

double a, b, c, pr1; // Declare variables for coefficients and


discriminant

// Prompt user for coefficients 'a', 'b', and 'c'

printf("\nInput the first number(a): ");

scanf("%lf", &a);

printf("\nInput the second number(b): ");

scanf("%lf", &b);

printf("\nInput the third number(c): ");

scanf("%lf", &c);

pr1 = (b*b) - (4*(a)*(c)); // Calculate discriminant

if(pr1 > 0 && a != 0) { // Check conditions for real roots

double x, y;

pr1 = sqrt(pr1); // Calculate square root of discriminant

x = (-b + pr1)/(2*a); // Calculate first root

y = (-b - pr1)/(2*a); // Calculate second root

printf("Root1 = %.5lf\n", x); // Print first root

printf("Root2 = %.5lf\n", y); // Print second root

}
else {

printf("\nImpossible to find the roots.\n"); // Print message


for no real roots

return 0;

Copy
Sample Output:
Input the first number(a): 25

Input the second number(b): 35

Input the third number(c): 12


Root1 = -0.60000
Root2 = -0.80000

21. Write a C program that reads an integer and checks the


specified range to which it belongs. Print an error message if the
number is negative and greater than 80.
Test Data :
Input an integer: 15
Expected Output:
Range [0, 20]

C Code:

#include <stdio.h>

int main() {

int x; // Declare variable to store an integer

// Prompt user for an integer and store in 'x'


printf("\nInput an integer: ");

scanf("%d", &x);

if(x >=0 && x <= 20) // Check if 'x' is in the range [0, 20]

printf("Range [0, 20]\n"); // Print message for the first


range

else if(x >=21 && x <= 40) // Check if 'x' is in the range (21,40]

printf("Range (21,40]\n"); // Print message for the second


range

else if(x >=41 && x <= 60) // Check if 'x' is in the range (41,60]

printf("Range (41,60]\n"); // Print message for the third


range

else if(x >61 && x <= 80) // Check if 'x' is in the range (61,80]

printf("Range (61,80]\n"); // Print message for the fourth


range

else

printf("Outside the range\n"); // Print message for values


outside of all ranges
}

return 0;

Copy
Sample Output:
Input an integer: 15
Range [0, 20]

22. Write a C program that reads 5 numbers and sums all odd
values between them.
Test Data :
Input the first number: 11
Input the second number: 17
Input the third number: 13
Input the fourth number: 12
Input the fifth number: 5
Expected Output:
Sum of all odd values: 46

C Code:

#include <stdio.h>

int main() {

int j, numbers[5], total=0; // Declare variables for loop counter,


an array of numbers, and total

// Prompt user for five numbers and store them in the array

printf("\nInput the first number: ");

scanf("%d", &numbers[0]);
printf("\nInput the second number: ");

scanf("%d", &numbers[1]);

printf("\nInput the third number: ");

scanf("%d", &numbers[2]);

printf("\nInput the fourth number: ");

scanf("%d", &numbers[3]);

printf("\nInput the fifth number: ");

scanf("%d", &numbers[4]);

// Loop through the numbers to find and sum the odd ones

for(j = 0; j < 5; j++) {

if((numbers[j]%2) != 0)

total += numbers[j];

// Print the sum of odd values

printf("\nSum of all odd values: %d", total);

printf("\n");

return 0;

Copy
Sample Output:
Input the first number: 11

Input the second number: 17

Input the third number: 13

Input the fourth number: 12

Input the fifth number: 5

Sum of all odd values: 46

23. Write a C program that reads three floating-point values and


checks if it is possible to make a triangle with them. Determine
the perimeter of the triangle if the given values are valid.
Test Data :
Input the first number: 25
Input the second number: 15
Input the third number: 35
Expected Output:
Perimeter = 75.0

C Code:

#include <stdio.h>

int main() {

float x, y, z, P, A; // Declare variables for side lengths and


perimeter

// Prompt user for the side lengths and store in 'x', 'y', and 'z'

printf("\nInput the first number: ");

scanf("%f", &x);

printf("\nInput the second number: ");

scanf("%f", &y);

printf("\nInput the third number: ");


scanf("%f", &z);

if(x < (y+z) && y < (x+z) && z < (y+x)) // Check if the sides can
form a triangle

P = x+y+z; // Calculate perimeter

printf("\nPerimeter = %.1f\n", P); // Print perimeter

else

printf("Not possible to create a triangle..!"); // Print


message if it's not possible to form a triangle

return 0;

Copy
Sample Output:
Input the first number: 25

Input the second number: 15

Input the third number: 35

Perimeter = 75.0

24. Write a C program that reads two integers and checks


whether they are multiplied or not.
Test Data :
Input the first number: 5
Input the second number: 15
Expected Output:
Multiplied!

C Code:

#include <stdio.h>

int main() {

int x, y; // Declare variables for two integers

// Prompt user for the first number and store in 'x'

printf("\nInput the first number: ");

scanf("%d", &x);

// Prompt user for the second number and store in 'y'

printf("\nInput the second number: ");

scanf("%d", &y);

if(x > y)

int temp;

temp = x; // Swap the values of 'x' and 'y'

x = y;

y = temp;

if((y % x)== 0) // Check if 'x' is a factor of 'y'

{
printf("\nMultiplied!\n"); // Print message if 'x' is a factor
of 'y'

else

printf("\nNot Multiplied!\n"); // Print message if 'x' is not


a factor of 'y'

return 0;

Copy
Sample Output:
Input the first number: 5

Input the second number: 15

Multiplied!

25. Write a C program that reads an integer between 1 and 12


and prints the month of the year in English.
Test Data :
Input a number between 1 to 12 to get the month name: 8
Expected Output:
August

C Code:

#include <stdio.h>

int main() {

int mno; // Declare variable for month number


// Prompt user for a number between 1 to 12

printf("\nInput a number between 1 to 12 to get the month name:


");

scanf("%d", &mno);

switch(mno) {

case 1 : printf("January\n"); break; // Print the name of the


month for each case

case 2 : printf("February\n"); break;

case 3 : printf("March\n"); break;

case 4 : printf("April\n"); break;

case 5 : printf("May\n"); break;

case 6 : printf("June\n"); break;

case 7 : printf("July\n"); break;

case 8 : printf("August\n"); break;

case 9 : printf("September\n"); break;

case 10 : printf("October\n"); break;

case 11 : printf("November\n"); break;

case 12 : printf("December\n"); break;

default : printf("Input a number between 1 to 12."); // Print


a message for an invalid input

return 0;

Copy
Sample Output:
Input a number between 1 to 12 to get the month name: 8
August

26. Write a C program that prints all even numbers between 1


and 50 (inclusive).
Test Data :
Even numbers between 1 to 50 (inclusive):
Expected Output:
2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46
48 50

C Code:

#include <stdio.h>

int main() {

int i; // Declare variable for loop counter

printf("Even numbers between 1 to 50 (inclusive):\n");

for (i = 1; i <= 50; i++)

if(i%2 == 0) // Check if 'i' is even

printf("%d ", i); // Print 'i' if it's even

return 0;

}
Sample Output:
Even numbers between 1 to 50 (inclusive):
2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46
48 50

27. Write a C program that reads 5 numbers and counts the


number of positive numbers and negative numbers.
Test Data :
Input the first number: 5
Input the second number: -4
Input the third number: 10
Input the fourth number: 15
Input the fifth number: -1
Expected Output:
Number of positive numbers: 3
Number of negative numbers: 2

C Code:

#include <stdio.h>

int main() {

float numbers[5]; // Declare an array to store 5 numbers

int j, pctr=0, nctr=0; // Declare variables for loop counter,


positive count, and negative count

// Prompt user for five numbers and store them in the array

printf("\nInput the first number: ");

scanf("%f", &numbers[0]);

printf("\nInput the second number: ");

scanf("%f", &numbers[1]);

printf("\nInput the third number: ");


scanf("%f", &numbers[2]);

printf("\nInput the fourth number: ");

scanf("%f", &numbers[3]);

printf("\nInput the fifth number: ");

scanf("%f", &numbers[4]);

for(j = 0; j < 5; j++) {

if(numbers[j] > 0) // Check if the number is positive

pctr++; // Increment positive count

else if(numbers[j] < 0) // Check if the number is negative

nctr++; // Increment negative count

// Print the counts of positive and negative numbers

printf("\nNumber of positive numbers: %d", pctr);

printf("\nNumber of negative numbers: %d", nctr);

printf("\n");

return 0;

}
Copy
Sample Output:
Input the first number: 5

Input the second number: -4

Input the third number: 10

Input the fourth number: 15

Input the fifth number: -1

Number of positive numbers: 3


Number of negative numbers: 2

28. Write a C program that reads 5 numbers, counts the number


of positive numbers, and prints out the average of all positive
values.
Test Data :
Input the first number: 5
Input the second number: 8
Input the third number: 10
Input the fourth number: -5
Input the fifth number: 25
Expected Output:
Number of positive numbers: 4
Average value of the said positive numbers: 12.00

C Code:

#include <stdio.h>

int main() {

float numbers[5], total=0, avg; // Declare an array to store 5


numbers, and variables for total and average

int j, pctr=0; // Declare variables for loop counter and positive


count
// Prompt user for five numbers and store them in the array

printf("\nInput the first number: ");

scanf("%f", &numbers[0]);

printf("\nInput the second number: ");

scanf("%f", &numbers[1]);

printf("\nInput the third number: ");

scanf("%f", &numbers[2]);

printf("\nInput the fourth number: ");

scanf("%f", &numbers[3]);

printf("\nInput the fifth number: ");

scanf("%f", &numbers[4]);

for(j = 0; j < 5; j++) {

if(numbers[j] > 0) // Check if the number is positive

pctr++; // Increment positive count

total += numbers[j]; // Add positive number to total

avg = total/pctr; // Calculate average of positive numbers

// Print the counts of positive numbers and the average

printf("\nNumber of positive numbers: %d", pctr);

printf("\nAverage value of the said positive numbers: %.2f", avg);


printf("\n");

return 0;

Copy
Sample Output:
Input the first number: 5

Input the second number: 8

Input the third number: 10

Input the fourth number: -5

Input the fifth number: 25

Number of positive numbers: 4


Average value of the said positive numbers: 12.00

29. Write a C program that read 5 numbers and sum of all odd
values between them.
Test Data :
Input the first number: 5
Input the second number: 7
Input the third number: 9
Input the fourth number: 10
Input the fifth number: 13
Expected Output:
Sum of all odd values: 34

C Code:

#include <stdio.h>

int main() {
int j, numbers[5], total=0; // Declare array to store 5 numbers
and variable for total

printf("\nInput the first number: ");

scanf("%d", &numbers[0]);

printf("\nInput the second number: ");

scanf("%d", &numbers[1]);

printf("\nInput the third number: ");

scanf("%d", &numbers[2]);

printf("\nInput the fourth number: ");

scanf("%d", &numbers[3]);

printf("\nInput the fifth number: ");

scanf("%d", &numbers[4]);

for(j = 0; j < 5; j++) {

if((numbers[j]%2) != 0) // Check if the number is odd

total += numbers[j]; // Add odd number to total

printf("\nSum of all odd values: %d", total); // Print the sum of


odd numbers

return 0;

Copy
Sample Output:
Input the first number: 5

Input the second number: 7

Input the third number: 9

Input the fourth number: 10

Input the fifth number: 13

Sum of all odd values: 34

30. Write a C program to find and print the square of all the even
values from 1 to a specified value.
Test Data :
List of square of each one of the even values from 1 to a 4 :
Expected Output:
2^2 = 4
4^2 = 16

C Code:

#include <stdio.h>

int main() {

int x, i; // Declare variables for user input and loop counter

printf("Input an integer: ");

scanf("%d", &x); // Prompt user for an integer

printf("List of square of each one of the even values from 1 to a


%d :\n", x);

for(i = 2; i <= x; i++) { // Loop through numbers from 2 to x

if((i%2) == 0) { // Check if the number is even


printf("%d^2 = %d\n", i, i*i); // Print the square of the
even number

return 0;

Copy
Sample Output:
List of square of each one of the even values from 1 to a 4 :
2^2 = 4
4^2 = 16

31. Write a C program to check whether a given integer is


positive even, negative even, positive odd or negative odd. Print
even if the number is 0.
Test Data :
Input an integer: 13
Expected Output:
Positive Odd

C Code:

#include <stdio.h>

int main() {

int x; // Declare a variable to store user input

printf("Input an integer: ");

scanf("%d", &x); // Prompt user for an integer

// Check different conditions based on the value of x

if(x == 0){
printf("Positive\n");

else if(x < 0 && (x%2) != 0) // Check if x is negative and odd

printf("Negative Odd\n");

else if(x < 0 && (x%2) == 0) // Check if x is negative and even

printf("Negative Even\n");

else if(x > 0 && (x%2) != 0) // Check if x is positive and odd

printf("Positive Odd\n");

else if(x > 0 && (x%2) == 0) // Check if x is positive and even

printf("Positive Even\n");

return 0;

Copy
Sample Output:
Input an integer: 13
Positive Odd
32. Write a C program to print all numbers between 1 and 100
which are divided by a specified number and the remainder will
be 3.
Test Data :
Input an integer: 25
Expected Output:
3
28
53
78

C Code:

#include <stdio.h>

int main() {

int x, i; // Declare variables for user input and loop counter

printf("Input an integer: ");

scanf("%d", &x); // Prompt user for an integer

for(i = 1; i <= 100; i++) // Loop through numbers from 1 to 100

if((i%x) == 3) { // Check if the remainder of i divided by x


is 3

printf("%d\n", i); // Print i if the condition is met

return 0;

}
Copy
Input data: 25

Sample Output:
Input an integer: 3
28
53
78

33. Write a C program that accepts some integers from the user
and finds the highest value and the input position.
Test Data :
Input 5 integers:
5
7
15
23
45
Expected Output:
Highest value: 45
Position: 5

C Code:

#include <stdio.h>

#define MAX 5

int main()

int number[MAX], i, j, max=0, num_pos=0; // Declare an array to


store 5 numbers, and variables for loop counters and maximum value

printf("Input 5 integers: \n");

for(i = 0; i < MAX; i++) {

scanf(" %d", &number[i]); // Read 5 integers from the user


}

for(j = 0; j < MAX; j++)

if(number[j] > max) { // Check if current number is greater


than current maximum

max = number[j]; // Update maximum if needed

num_pos = j; // Record the position of maximum

printf("Highest value: %d\nPosition: %d\n", max, num_pos+1); //


Print the maximum value and its position

return 0;

Copy
Sample Output:
Input 5 integers:
5
7
15
23
45
Highest value: 45
Position: 5

34. Write a C program to compute the sum of consecutive odd


numbers from a given pair of integers.
Test Data :
Input a pair of numbers (for example 10,2):
Input first number of the pair: 10
Input second number of the pair: 2
Expected Output:
List of odd numbers: 3
5
7
9
Sum=24

C Code:

#include <stdio.h>

int main() {

int x, y, i, total = 0; // Declare variables for user input and


calculations

printf("\nInput a pair of numbers (for example 10,2):");

printf("\nInput first number of the pair: ");

scanf("%d", &x); // Read the first number

printf("\nInput second number of the pair: ");

scanf("%d", &y); // Read the second number

if (x < y) {

return 0; // If x is less than y, exit the program

printf("\nList of odd numbers: ");

for (i = y; i <= x; i++) {

if ((i % 2) != 0) {

printf("%d\n", i); // Print odd numbers within the range

total += i; // Add odd numbers to the total

}
}

printf("Sum=%d\n", total); // Print the total sum

return 0;

Copy
Sample Output:
Input a pair of numbers (for example 10,2):
Input first number of the pair: 10

Input second number of the pair: 2

List of odd numbers: 3


5
7
9
Sum=24

35. Write a C program to check if two numbers in a pair are in


ascending order or descending order.
Test Data :
Input a pair of numbers (for example 10,2 : 2,10):
Input first number of the pair: 10
Expected Output:
Input second number of the pair: 2
The pair is in descending order!

C Code:

#include <stdio.h>

int main() {

int x, y, i, total = 0; // Declare variables for user input and


calculations

printf("\nInput a pair of numbers (for example 10,2 : 2,10):");


printf("\nInput first number of the pair: ");

scanf("%d", &x); // Read the first number

printf("\nInput second number of the pair: ");

scanf("%d", &y); // Read the second number

if (x > y) {

printf("The pair is in descending order!"); // If x is greater


than y, print message for descending order

} else {

printf("The pair is in ascending order!"); // Otherwise, print


message for ascending order

printf("\n");

return 0;

Copy
Sample Output:
Input a pair of numbers (for example 10,2 : 2,10):
Input first number of the pair: 10

Input second number of the pair: 2


The pair is in descending order!

36. Write a C program to read a password until it is valid. For


wrong password print "Incorrect password" and for correct
password print, "Correct password" and quit the program. The
correct password is 1234.
Test Data :
Input the password: 1234
Expected Output:
Correct password

C Code:

#include <stdio.h>

int main() {

int pass, x = 10; // Initialize variables for password and loop


control

while (x != 0) {

printf("\nInput the password: ");

scanf("%d", &pass); // Read the password input

if (pass == 1234) {

printf("Correct password"); // If the password is correct,


print a success message

x = 0; // Set x to 0 to exit the loop

} else {

printf("Wrong password, try another"); // If the password


is incorrect, prompt for another attempt

printf("\n");

return 0;

}
Copy
Sample Output:
Input the password: 1234
Correct password

37. Write a C program to read the coordinates (x, y) (in the


Cartesian system) and find the quadrant to which it belongs
(Quadrant -I, Quadrant -II, Quadrant -III, Quadrant -IV).
Note: A Cartesian coordinate system is a coordinate system that
specifies each point uniquely in a plane by a pair of numerical
coordinates.
These are often numbered from 1st to 4th and denoted by Roman
numerals: I (where the signs of the (x,y) coordinates are I(+,+), II
(−,+), III (−,−), and IV (+,−).
Test Data :
Input the Coordinate(x,y):
x: 25
y: 15
Expected Output:
Quadrant-I(+,+)

Note: A Cartesian coordinate system is a coordinate system that


specifies each point uniquely in a plane by a pair of numerical
coordinates.
These are often numbered from 1st to 4th and denoted by Roman
numerals: I (where the signs of the (x,y) coordinates are I(+,+), II
(−,+), III (−,−), and IV (+,−).

Sample Solution:

C Code:

#include <stdio.h>

int main() {

int x, y;
// Prompt for user input

printf("Input the Coordinate(x,y): ");

printf("\nx: ");

scanf("%d", &x);

printf("y: ");

scanf("%d", &y);

// Check which quadrant the point lies in

if(x > 0 && y > 0) {

printf("Quadrant-I(+,+)\n");

else if(x > 0 && y < 0) {

printf("Quadrant-II(+,-)\n");

else if(x < 0 && y < 0) {

printf("Quadrant-III(-,-)\n");

else if(x < 0 && y > 0) {

printf("Quadrant-IV(-,+)\n");

return 0;

Copy
Sample Output:
Input the Coordinate(x,y):
x: 25
y: 15
Quadrant-I(+,+)

38. Write a program that reads two numbers and divides the first
number by the second number. If division is not possible print
"Division is not possible".
Test Data :
Input two numbers:
x: 25
y: 5
Expected Output: 5.0

C Code:

#include <stdio.h>

int main() {

int x, y;

float div_result;

// Prompt for user input

printf("Input two numbers: ");

printf("\nx: ");

scanf("%d", &x);

printf("y: ");

scanf("%d", &y);

// Check if division is possible

if(y != 0) {

div_result = x/y;
printf("%.1f\n", div_result);

} else {

printf("Division not possible.\n");

return 0;

Copy
Sample Output:
Input two numbers:
x: 25
y: 5
5.0

39. Write a C program to calculate the sum of all numbers not


divisible by 17 between two given integer numbers.
Test Data :
Input the first integer: 50 Input the second integer: 99
Expected Output:
Sum: 3521

C Code:

#include <stdio.h>

int main() {

int x, y, temp, i, sum=0;

// Prompt for user input

printf("\nInput the first integer: ");

scanf("%d", &x);

printf("\nInput the second integer: ");


scanf("%d", &y);

// Swap values if x is greater than y

if(x > y) {

temp = y;

y = x;

x = temp;

// Calculate the sum of numbers not divisible by 17

for(i = x; i <= y; i++) {

if((i % 17) != 0) {

sum += i;

// Display the sum

printf("\nSum: %d\n", sum);

return 0;

Copy
Sample Output:
Input the first integer: 50

Input the second integer: 99


Sum: 3521

40. Write a C program that finds all integer numbers that divide
by 7 and have a remainder of 2 or 3 between two given integers.
Test Data :
Input the first integer: 25
Input the second integer: 45
Expected Output:
30
31
37
38
44

C Code:

#include <stdio.h>

int main() {

int x, y, temp, i, sum=0;

// Prompt for user input

printf("\nInput the first integer: ");

scanf("%d", &x);

printf("\nInput the second integer: ");

scanf("%d", &y);

// Swap values if x is greater than y

if(x > y) {

temp = y;

y = x;

x = temp;
}

// Iterate through numbers between x and y (exclusive)

for(i = x+1; i < y; i++) {

// Check if the number modulo 7 is 2 or 3

if((i%7) == 2 || (i%7) == 3) {

printf("%d\n", i);

return 0;

Copy
Sample Output:
Input the first integer: 25

Input the second integer: 45


30
31
37
38
44

41. Write a C program to print 3 numbers on a line, starting with


1 and printing n lines. Accept the number of lines (n, integer)
from the user.
Test Data :
Input number of lines: 5
Expected Output:
123
456
789
10 11 12
13 14 15

C Code:

#include <stdio.h>

int main() {

int a, i, j = 1, x = 0;

// Prompt for user input

printf("Input number of lines: ");

scanf("%d", &a);

// Loop for each line

for(i = 1; i <= a; i++) {

// Loop to print numbers

while(x < 3) {

printf("%d ", j++);

x++;

x = 0; // Reset the counter

printf("\n");

return 0;

}
Copy
Sample Output:
Input number of lines: 5
1 2 3
4 5 6
7 8 9
10 11 12
13 14 15

42. Write a C program to print a number, its square and cube,


starting with 1 and printing n lines. Accept the number of lines (n,
integer) from the user.
Test Data :
Input number of lines: 5
Expected Output:
111
248
3 9 27
4 16 64
5 25 125

C Code:

#include <stdio.h>

int main() {

int a, i, j = 1, x = 0;

// Prompt for user input

printf("Input number of lines: ");

scanf("%d", &a);

// Loop for each line

for(i = 1; i <= a; i++) {


// Print i, i squared, and i cubed

printf("%d %d %d\n", i, i*i, i*i*i);

return 0;

Copy
Sample Output:
Input number of lines: 5
1 1 1
2 4 8
3 9 27
4 16 64
5 25 125

43. Write a C program that reads two integers p and q, prints p


number of lines in a sequence of 1 to b in a line.
Test Data :
Input number of lines: 5
Number of characters in a line: 6
Expected Output:
123456
7 8 9 10 11 12
13 14 15 16 17 18
19 20 21 22 23 24
25 26 27 28 29 30

C Code:

#include <stdio.h>

int main() {

int x, y, i, j, l;
// Prompt for user input

printf("Input number of lines: ");

scanf("%d", &x);

printf("Number of numbers in a line: ");

scanf("%d", &y);

// Loop to generate the pattern

for(i = 1, l=1; i <= x; i++) {

for(j = 1; j <= y; j++) {

printf("%d ", l);

l++;

printf("\n");

return 0;

Copy
Sample Output:
Input number of lines: 5
Number of numbers in a line: 6
1 2 3 4 5 6
7 8 9 10 11 12
13 14 15 16 17 18
19 20 21 22 23 24
25 26 27 28 29 30
44. Write a C program to calculate the average mathematics
marks of some students. Input 0 (excluding to calculate the
average) or a negative value to terminate the input process.
Test Data :
Input Mathematics marks (0 to terminate): 10
15
20
25
0
Expected Output:
Average marks in Mathematics: 17.50

C Code:

#include <stdio.h>

int main() {

int marks[99], m, i, a=0, total=0;

float f;

// Prompt for user input

printf("Input Mathematics marks (0 to terminate): ");

// Loop to get input marks

for(i = 0; ; i++) {

scanf("%d", &marks[i]);

if(marks[i] <= 0) {

break;

a++;

total += marks[i];
}

// Calculate and print average

f = (float)total/(float)a;

printf("Average marks in Mathematics: %.2f\n", f);

return 0;

Copy
Sample Output:
Input Mathematics marks (0 to terminate): 10
15
20
25
0
Average marks in Mathematics: 17.50
45. Write a C program to calculate the value of S where S = 1 +
1/2 + 1/3 + … + 1/50.
Expected Output:
Value of S: 4.50

C Code:

#include <stdio.h>

int main() {

float S = 0;

int i;

// Loop to calculate the sum

for(i=1; i<=50; i++) {

S += (float)1/i;
}

// Print the result

printf("Value of S: %.2f\n", S);

return 0;

Copy
Sample Output:
Value of S: 4.50

46. Write a C program to calculate the value of S where S = 1 +


3/2 + 5/4 + 7/8.
Expected Output:
Value of series: 4.62

C Code:

#include <stdio.h>

int main() {

double s=0, j=1, d, i;

// Loop to calculate the series

for(i=1; i<=7; i+=2){

d = (i/j);

s += d;

j = j*2;

}
// Print the result

printf("Value of series: %.2lf\n", s);

return 0;

Copy
Sample Output:
Value of series: 4.62

47. Write a C program that finds all the divisors of an integer.


Test Data:
Input an integer: 45
Expected Output:
All the divisor of 45 are:
1
3
5
9
15
45

C Code:

#include <stdio.h>

int main() {

int x, i;

// Get an integer input from the user

printf("\nInput an integer: ");

scanf("%d", &x);
// Print all the divisors of x

printf("All the divisors of %d are: ", x);

for(i = 1; i <= x; i++) {

if((x%i) == 0){

printf("\n%d", i);

printf("\n");

return 0;

Copy
Sample Output:
Input an integer: 45
All the divisor of 45 are:
1

15

45

48. Write a C program that reads and prints the elements of an


array of length 7. Before printing, replace every negative number,
zero, with 100.
Test Data:
Input the 5 members of the array:
25
45
35
65
15

Expected Output:
Array values are:
n[0] = 25
n[1] = 45
n[2] = 35
n[3] = 65
n[4] = 15

C Code:

#include <stdio.h>

int main() {

int n[5], i, x;

// Input the 5 members of the array

printf("Input the 5 members of the array:\n");

for(i = 0; i < 5; i++) {

scanf("%d", &x);

if(x > 0) {

n[i] = x;

} else {

n[i] = 100;

// Print the array values


printf("Array values are: \n");

for(i = 0; i < 5; i++) {

printf("n[%d] = %d\n", i, n[i]);

return 0;

Copy
Sample Output:
Input the 5 members of the array:
25
45
35
65
15
Array values are:
n[0] = 25
n[1] = 45
n[2] = 35
n[3] = 65
n[4] = 15

49. Write a C program to read and print the elements of an array


with length 7. Before printing, insert the triple of the previous
position, starting from the second position.
For example, if the first number is 2, the array numbers must be
2, 6, 18, 54 and 162
Test Data:
Input the first number of the array: 5
Expected Output:
n[0] = 5
n[1] = 15
n[2] = 45
n[3] = 135
n[4] = 405
C Code:

#include <stdio.h>

int main() {

int n[5], i, x;

// Input the first number of the array

printf("Input the first number of the array:\n");

scanf("%d", &x);

// Fill the array with values based on the input

for(i = 0; i < 5; i++) {

n[i] = x;

x = 3 * x;

// Print the array values

for(i = 0; i < 5; i++) {

printf("n[%d] = %d\n", i, n[i]);

return 0;

Copy
Sample Output:
Input the first number of the array:
5
n[0] = 5
n[1] = 15
n[2] = 45
n[3] = 135
n[4] = 405

50. Write a C program to read an array of length 5 and print the


position and value of the array elements of value less than 5.
Test Data:
Input the 5 members of the array:
15
25
4
35
40
Expected Output:
A[2] = 4.0

C Code:

#include <stdio.h>

#define AL 5 // Define the size of the array as 5

#define MAX 5 // Define a maximum value for comparison

int main() {

float N[AL]; // Declare an array of size 5 to hold floating-point


numbers

int i;

// Prompt for user input

printf("Input the 5 members of the array:\n");


// Read and store user input into the array

for(i = 0; i < AL; i++) {

scanf("%f", &N[i]);

// Iterate through the array and print elements less than MAX

for(i = 0; i < AL; i++) {

if(N[i] < MAX) {

printf("A[%d] = %.1f\n", i, N[i]);

return 0;

Copy
Sample Output:
Input the 5 members of the array:
15
25
4
35
40
A[2] = 4.0

51. Write a C program to read an array of length 6, change the


first element by the last, the second element by the fifth and the
third element by the fourth. Print the elements of the modified
array.
Test Data:
Input the 5 members of the array:
15
20
25
30
35

Expected Output:
array_n[0] = 35
array_n[1] = 30
array_n[2] = 25
array_n[3] = 20
array_n[4] = 15

C Code:

#include <stdio.h>

#define AL 5

int main() {

// Define the size of the array

int array_n[AL], i, temp;

// Prompt user to input 5 elements of the array

printf("Input the 5 members of the array:\n");

for(i = 0; i < AL; i++) {

scanf("%d", &array_n[i]);

// Swap the first half of the array with the second half

for(i = 0; i < AL; i++) {

if(i < (AL/2)) {


temp = array_n[i];

array_n[i] = array_n[AL-(i+1)];

array_n[AL-(i+1)] = temp;

// Print the modified array

for(i = 0; i < AL; i++) {

printf("array_n[%d] = %d\n", i, array_n[i]);

return 0;

Copy
Sample Output:
Input the 5 members of the array:
15
20
25
30
35
array_n[0] = 35
array_n[1] = 30
array_n[2] = 25
array_n[3] = 20
array_n[4] = 15
52. Write a C program to read an array of length 6 and find the
smallest element and its position.
Test Data:
Input the length of the array: 5 Input the array elements:
25
35
20
14
45
Expected Output:
Smallest Value: 14
Position of the element: 3

C Code:

#include <stdio.h>

int main() {

int e, i, sval, position;

// Prompt user to input the length of the array

printf("\nInput the length of the array: ");

scanf("%d", &e);

// Declare an array of length 'e'

int v[e];

// Prompt user to input the array elements

printf("\nInput the array elements:\n ");

for(i = 0; i < e; i++) {

scanf("%d", &v[i]);

// Initialize 'sval' and 'position' with the first element of the


array

sval = v[0];
position = 0;

// Find the smallest value and its position in the array

for(i = 0; i < e; i++) {

if(sval > v[i]) {

sval = v[i];

position = i;

// Print the smallest value and its position

printf("Smallest Value: %d\n", sval);

printf("Position of the element: %d\n", position);

return 0;

Copy
Sample Output:
Input the length of the array: 5

Input the array elements:


25
35
20
14
45
Smallest Value: 14
Position of the element: 3
53. Write a C program that accepts the principle, rate of interest,
and time and calculates simple interest.
Test Data:
Input Data: p = 10000, r = 10% , t = 12 year
Expected Output:
Input principle, Rate of interest & time to find simple interest:
Simple interest = 12000

C Code:

#include<stdio.h>

int main() {

int p, r, t, int_amt;

// Prompt user to input principle, rate of interest, and time

printf("Input principle, Rate of interest & time to find simple


interest: \n");

scanf("%d%d%d", &p, &r, &t);

// Calculate simple interest

int_amt = (p * r * t) / 100;

// Display the calculated simple interest

printf("Simple interest = %d", int_amt);

return 0;

Copy
Sample Output:
Input Data: p = 10000, r = 10% , t = 12 year
Input principle, Rate of interest & time to find simple interest:
Simple interest = 12000

54. Write a C program that accepts a distance in centimeters


and prints the corresponding value in inches.
Test Data:
Input Data: 500cms
Input the distance in cm:
Distance of 500.00 cms is = 196.85 inches

Note: 1 inch = 2.54 cm.


C Code:

#include <stdio.h>

// Define a constant for converting inches to centimeters

#define INCH_TO_CM 2.54

int main() {

double inch, cm;

// Prompt user to input the distance in centimeters

printf("Input the distance in cm:\n");

scanf("%lf", &cm);

// Convert centimeters to inches

inch = cm / INCH_TO_CM;

// Display the converted distance

printf("Distance of %0.2lf cms is = %0.2lf inches\n", cm, inch);


return 0;

Copy
Sample Output:
Input Data: 500cms
Input the distance in cm:
Distance of 500.00 cms is = 196.85 inches

55. Write a C program that swaps two numbers without using a


third variable.
Input value for x & y:
Before swapping the value of x & y: 5 7
After swapping the value of x & y: 7 5

This problem requires writing a C program to swap the values of


two variables without using a third, temporary variable. The
program should demonstrate the swap operation using arithmetic
or bitwise XOR operations to achieve the swap directly between
the two variables. This approach avoids the need for additional
memory allocation, making the solution more efficient in terms of
space.

What is swapping in C language?

Swapping in the C language refers to the process of exchanging


the values of two variables. This operation involves assigning the
value of one variable to another and vice versa, so that each
variable holds the initial value of the other. Swapping is a
common operation in various algorithms and applications, such
as sorting algorithms, to rearrange data.

Applications of Swapping

Swapping is widely used in various programming scenarios,


including:
 Sorting Algorithms: Algorithms like bubble sort, quick sort, and
others frequently swap elements to arrange data in a particular
order.

 Permutations: Generating permutations of a set of values often


involves swapping elements.

 Data Manipulation: Various data manipulation tasks require


swapping values to achieve desired outcomes.

Input value for x & y:

Before swapping the value of x & y: 5 7

After swapping the value of x & y: 7 5

Sample Solution: Using arithmetic operations

C Code:

#include<stdio.h>

int main()

int x, y;

printf("Input value for x & y: \n");

scanf("%d%d",&x,&y);

printf("Before swapping the value of x & y: %d %d",x,y);

x=x+y;

y=x-y;

x=x-y;

printf("\nAfter swapping the value of x & y: %d %d",x,y);

return 0;

}
Copy
Output:
Input value for x & y:
Before swapping the value of x & y: 5 7
After swapping the value of x & y: 7 5
Explanation:

 Include the Standard Input-Output Library: #include<stdio.h>


ensures that the functions for input and output operations are
available.

 Main Function Definition: int main() begins the execution of the


program.

 Variable Declaration: int x, y; declares two integer variables x


and y.

 User Input Prompt:

o printf("Input value for x & y: \n"); prompts the user to input


values for x and y.

o scanf("%d%d", &x, &y); reads the input values from the user
and stores them in x and y.

 Display Initial Values: printf("Before swapping the value of x & y:


%d %d", x, y); prints the values of x and y before swapping.

 Swap Values Using Arithmetic Operations:

o x = x + y; adds x and y and stores the result in x.

o y = x - y; subtracts the new value of y (which is the original


x + y) by y to get the original value of x and stores it in y.

o x = x - y; subtracts the new value of y (original x) from x to


get the original value of y and stores it in x.

 Display Swapped Values: printf("\nAfter swapping the value of x


& y: %d %d", x, y); prints the values of x and y after swapping.

 Return Statement: return 0; indicates that the program has


executed successfully.
Sample Solution: using bitwise XOR operations

Code:

#include <stdio.h>

int main() {

int x, y;

// Prompt user to input values for x and y

printf("Input value for x & y: \n");

scanf("%d%d", &x, &y);

// Display the values of x and y before swapping

printf("Before swapping the value of x & y: %d %d\n", x, y);

// Swap the values of x and y using bitwise XOR operations

x = x ^ y; // Step 1: x now holds the result of x XOR y

y = x ^ y; // Step 2: y now holds the original value of x

x = x ^ y; // Step 3: x now holds the original value of y

// Display the values of x and y after swapping

printf("After swapping the value of x & y: %d %d\n", x, y);

return 0;

}
Copy
Output:
Input value for x & y:
2 3
Before swapping the value of x & y: 2 3
After swapping the value of x & y: 3 2
Explanation:

 Include the Standard Input-Output Library: #include <stdio.h>


ensures that the functions for input and output operations are
available.

 Main Function Definition: int main() begins the execution of the


program.

 Variable Declaration: int x, y; declares two integer variables x


and y.

 User Input Prompt:

o printf("Input value for x & y: \n"); prompts the user to input


values for x and y.

o scanf("%d%d", &x, &y); reads the input values from the user
and stores them in x and y.

 Display Initial Values: printf("Before swapping the value of x & y:


%d %d\n", x, y); prints the values of x and y before swapping.

 Swap Values Using Bitwise XOR Operations:

o x = x ^ y; stores the result of x XOR y in x.

o y = x ^ y; stores the original value of x in y by performing x


XOR y (since x now holds x XOR y, this operation effectively
isolates the original x).

o x = x ^ y; stores the original value of y in x by performing x


XOR y (since y now holds the original x).

 Display Swapped Values: printf("After swapping the value of x &


y: %d %d\n", x, y); prints the values of x and y after swapping.
 Return Statement: return 0; indicates that the program has
executed successfully.

56. Write a C program to shift given data by two bits to the left.
Input value : 2
Read the integer from keyboard-
Integer value = 2
The left shifted data is = 16
C Code:

#include<stdio.h>

int main() {

int a, b;

// Prompt user to input an integer

printf("Read the integer from keyboard-");

scanf("%d",&a);

// Display the original integer value

printf("\nInteger value = %d ",a);

// Left shift 'a' by 2 bits and assign it to 'b'

a <<= 2;

b = a;

// Display the left shifted data

printf("\nThe left shifted data is = %d ",b);


return 0;

Copy
Sample Output:
Read the integer from keyboard-
Integer value = 2
The left shifted data is = 8

57. Write a C program to reverse and print a given number.


Input a number:
The original number = 234
The reverse of the said number = 432
C Code:

#include<stdio.h>

int main() {

int num, x, r_num = 0;

// Prompt user to input a number

printf("Input a number: ");

scanf("%d", &num);

// Display the original number

printf("\nThe original number = %d", num);

// Reverse the digits of the number

while (num >= 1) {

x = num % 10;
r_num = r_num * 10 + x;

num = num / 10;

// Display the reverse of the number

printf("\nThe reverse of the said number = %d", r_num);

return 0;

Copy
Sample Output:
Input a number:
The original number = 234
The reverse of the said number = 432

58. Write a C program that accepts 4 real numbers from the


keyboard and prints out the difference between the maximum
and minimum values of these four numbers.
Input four numbers: 1.54 1.236 1.3625 1.002
Difference is 0.5380

Note: Use 4-decimal places.


Test data and expected output:
Input: 1.54 1.236 1.3625 1.002
Output: Difference is 0.5380

C Code:

#include <stdio.h>

int main() {

// Declare variables to store four numbers


double a1, a2, a3, a4;

double max, min;

// Prompt user to input four numbers

printf("Input four numbers: \n");

scanf("%lf%lf%lf%lf", &a1, &a2, &a3, &a4);

// Find the maximum among the four numbers

if (a1 >= a2 && a1 >= a3 && a1 >= a4)

max = a1;

else if (a2 >= a1 && a2 >= a3 && a2 >= a4)

max = a2;

else if (a3 >= a1 && a3 >= a2 && a3 >= a4)

max = a3;

else

max = a4;

// Find the minimum among the four numbers

if (a1 <= a2 && a1 <= a3 && a1 <= a4)

min = a1;

else if (a2 <= a1 && a2 <= a3 && a2 <= a4)

min = a2;

else if (a3 <= a1 && a3 <= a2 && a3 <= a4)

min = a3;

else
min = a4;

// Calculate and display the difference between max and min

printf("Difference is %0.4lf\n", max - min);

return 0;

Copy
Sample Output:
Input four numbers: 1.54 1.236 1.3625 1.002
Difference is 0.5380

59. Write a C program to display the sum of series 1 + 1/2 + 1/3 +


………. + 1/n.
Input any number: 1 + 1/0
Sum = 1/0

C Code:

#include<stdio.h>

int main() {

int num, i, sum = 0;

// Prompt the user to input a number

printf("Input any number: ");

scanf("%d", &num);

// Display the initial part of the series

printf("1 + ");
// Print the series

for(i = 2; i <= num - 1; i++)

printf(" 1/%d +", i);

// Calculate the sum of the series

for(i = 1; i <= num; i++)

sum = sum + i;

// Display the last term of the series

printf(" 1/%d", num);

// Calculate and display the sum

printf("\nSum = 1/%d", sum + 1/num);

return 0;

Copy
Sample Output:
Input any number: 1 + 1/0
Sum = 1/0

60. Write a C program to create enumerated data types for 7


days and display their values in integer constants.
Sun = 0
Mon = 1
Tue = 2
Wed = 3
Thu = 4
Fri = 5
Sat = 6

C Code:

#include <stdio.h>

int main() {

// Define an enumeration type 'week'

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

// Print the values of the days using the enumeration constants

printf("Sun = %d", Sun);

printf("\nMon = %d", Mon);

printf("\nTue = %d", Tue);

printf("\nWed = %d", Wed);

printf("\nThu = %d", Thu);

printf("\nFri = %d", Fri);

printf("\nSat = %d", Sat);

return 0;

Copy
Sample Output:
Sun = 0
Mon = 1
Tue = 2
Wed = 3
Thu = 4
Fri = 5
Sat = 6

61. Write a C program that accepts a real number x and prints


out the corresponding value of sin(1/x) using 4-decimal places.
Input value of x: .6235
Value of sin(1/x) is 0.9995

Note: Use 4-decimal places.


Test data and expected output:
Input value of x:
Value of sin(1/x) is 0.8415

C Code:

#include <stdio.h>

#include <math.h>

int main() {

double x, tval;

// Prompt user for input

printf("Input value of x: \n");

// Read the input value

scanf("%lf", &x);

if (x != 0.0) {

// Calculate sin(1/x) if x is not zero

tval = sin(1/x);

printf("Value of sin(1/x) is %0.4lf\n", tval);

} else {
// Display error message if x is zero

printf("Value of x should not be zero.");

return 0;

Copy
Sample Output:
Input value of x:
Value of sin(1/x) is 0.9995

62. Write a C program that accepts a positive integer less than


500 and prints out the sum of the digits of this number.
Input a positive number less than 500:
Sum of the digits of 347 is 14

Test data and expected output:


Input a positive number less than 500:
Sum of the digits of 336 is 12

C Code:

#include <stdio.h>

int main() {

int a, x = 0, y;

// Prompt user for input

printf("Input a positive number less than 500: \n");

// Read the input value


scanf("%d", &a);

y = a;

if (y < 1 || y > 999) {

// Display error message if the number is out of range

printf("The given number is out of range\n");

} else {

// Calculate the sum of the digits

x += y % 10;

y /= 10;

x += y % 10;

y /= 10;

x += y % 10;

// Display the result

printf("Sum of the digits of %d is %d\n", a, x);

return 0;

Copy
Sample Output:
Input a positive number less than 500:
Sum of the digits of 347 is 14
63. Write a C program that accepts a positive integer n less than
100 from the user. It prints out the sum of 14 + 24 + 44 + 74 +
114 + • • • + m4. In this case, m is less than or equal to n. Print an
appropriate message.
Input a positive number less than 100: 68
Sum of the series is 37361622

It prints out the sum of 14 + 24 + 44 + 74 + 114 + • • • + m4. In


this case, m is less than or equal to n. Print an appropriate
message.
Test data and expected output:
Input a positive number less than 100:
Sum of the series is 1024388

Sample Solution:

C Code:

#include <stdio.h>

int main() {

int i, j, n, sum_int = 0;

// Prompt user for input

printf("Input a positive number less than 100: \n");

// Read the input value

scanf("%d", &n);

// Check if the input is valid

if (n < 1 || n >= 100) {

printf("Wrong input\n");
return 0;

j = 1;

for (i = 1; j <= n; i++) {

sum_int += j * j * j * j;

j += i;

// Display the result

printf("Sum of the series is %d\n", sum_int);

return 0;

Sample Output:
Input a positive number less than 100: 68
Sum of the series is 37361622

64. Write a C program that accepts integers from the user until a
zero or a negative number, displays the number of positive values,
the minimum value, the maximum value, and the average value.
Input a positive integer:
Input next positive integer: 15
Input next positive integer: 25
Input next positive integer: 37
Input next positive integer: 43
Number of positive values entered is 4
Maximum value entered is 43
Minimum value entered is 15
Average value is 30.0000

Test data and expected output:


5 2 5 8 9 12 0

C Code:

#include <stdio.h>

int main() {

int a, ctr = 0, min_num, max_num, s = 0;

double avg;

// Prompt user for input

printf("Input a positive integer:\n");

// Read the first input value

scanf("%d", &a);

// Check if the input is positive

if (a <= 0) {

printf("No positive number entered\n");

return 0;

// Initialize min_num and max_num with the first input value

min_num = a;

max_num = a;
// Loop to process subsequent inputs

while (a > 0) {

s += a;

ctr++;

max_num = a > max_num ? a : max_num;

min_num = a < min_num ? a : min_num;

// Prompt for the next positive integer

printf("Input next positive integer:\n");

scanf("%d", &a);

avg = s / (double) ctr;

// Display the results

printf("Number of positive values entered is %d\n", ctr);

printf("Maximum value entered is %d\n", max_num);

printf("Minimum value entered is %d\n", min_num);

printf("Average value is %0.4lf\n", avg);

return 0;

Copy
Sample Output:
Input a positive integer:
Input next positive integer: 15
Input next positive integer: 25
Input next positive integer: 37
Input next positive integer: 43
Number of positive values entered is 4
Maximum value entered is 43
Minimum value entered is 15
Average value is 30.0000

65. Write a C program that prints out the prime numbers


between 1 and 200. The output should be such that each row
contains a maximum of 20 prime numbers.
Expected output:
The prime numbers between 1 and 199 are:
2 3 5 7 11 13 17 19 23 29
31 37 41 43 47 53 59 61 67 71
73 79 83 89 97 101 103 107 109 113
127 131 137 139 149 151 157 163 167 173
179 181 191 193 197
C Code:

#include <stdio.h>

int main() {

int i, j, flag, ip = 0;

// Print a message indicating the purpose of the program

printf("The prime numbers between 1 and 199 are:\n");

// Loop to check prime numbers from 2 to 198

for (i = 2; i < 199; i++) {

flag = 1;
// Loop to check if i is divisible by any number other than 1
and itself

for (j = 2; j <= i / 2 && flag == 1; j++) {

if (i % j == 0) {

flag = 0;

// If i is prime, print it

if (flag == 1) {

printf("%5d ", i);

ip++;

// Print a newline character after every 10 prime numbers

if (ip % 10 == 0) {

printf("\n");

printf("\n");

return 0;

Sample Output:
The prime numbers between 1 and 199 are:
2 3 5 7 11 13 17 19 23 29
31 37 41 43 47 53 59 61 67 71
73 79 83 89 97 101 103 107 109 113
127 131 137 139 149 151 157 163 167 173
179 181 191 193 197

66. Write a C program that generates 50 random numbers


between -0.5 and 0.5 and writes them to the file rand.dat. The
first line of ran.dat contains the number of random numbers,
while the next 50 lines contain 50 random numbers.
50
-0.4215
0.2620
0.3065
-0.0485
.... 0.3980
0.1750
0.4780
-0.2915
0.0715
0.3565

C Code:

#include <stdio.h>

#include <stdlib.h>

#include <time.h>

#define N 50

int main() {

int i;

char str;

FILE * fptr;
// Open a file for writing

fptr = fopen("rand.dat", "w");

if (fptr == NULL) {

printf("Error in creating output.dat\n");

return 0;

// Seed the random number generator

srand(time(NULL));

// Write the number of values to the file

fprintf(fptr, "%d\n", N);

// Generate and write random numbers to the file

for (i = 1; i <= N; i++) {

fprintf(fptr, "%0.4lf\n", (rand() % 2001 - 1000) / 2.e3);

// Close the file

fclose(fptr);

// Open the file for reading

fptr = fopen ("rand.dat", "r");

str = fgetc(fptr);
// Print the contents of the file

while (str != EOF)

printf ("%c", str);

str = fgetc(fptr);

// Close the file

fclose(fptr);

return 0;

Copy
Sample Output:
50
-0.4215
0.2620
0.3065
-0.0485
-0.2085
-0.2490
-0.2780
0.2905
-0.3120
0.1275
0.4010
0.3060
0.4680
-0.1135
0.0130
-0.0145
-0.1890
-0.3825
0.3790
-0.2370
0.0840
-0.1985
0.2065
0.4445
0.0785
-0.2370
-0.0705
0.3870
-0.4695
0.1525
0.2755
0.3880
-0.3075
-0.1400
-0.3825
-0.0155
-0.1105
-0.1605
-0.4470
0.0780
0.4675
0.2330
-0.3380
0.2135
0.3980
0.1750
0.4780
-0.2915
0.0715
0.3565

67. Write a C program to evaluate the equation y=xn when n is a


non-negative integer.
Input the values of x and n: 256
x=256.000000; n=0;
x to power n=1.000000

C Code:

#include <stdio.h>

int main(){

int count, n;
float x,y;

// Input the values of x and n

printf("Input the values of x and n:\n");

scanf("%f%d", &x,&n);

y=1.0;

count=1;

// Calculate x to the power n

while(count<=n)

y=y*x;

count++;

// Print the result

printf("x=%f; n=%d; \nx to power n=%f", x, n,y);

return 0;

Copy
Sample Output:
Input the values of x and n: 256
x=256.000000; n=0;
x to power n=1.000000
68. Write a C program that prints the powers of 2 table for the
powers 0 to 10, both positive and negative.
=======================================
n 2 to power n 2 to power -n
=======================================
0 1 1.000000000000
1 2 0.500000000000
2 4 0.250000000000
3 8 0.125000000000
4 16 0.062500000000
5 32 0.031250000000
6 64 0.015625000000
7 128 0.007812500000
8 256 0.003906250000
9 512 0.001953125000
10 1024 0.000976562500

C Code:

#include<stdio.h>

int main() {

long int p;

int n;

double q;

// Print table header

printf("\n=======================================");

printf("\n n 2 to power n 2 to power -n");

printf("\n=======================================");

p = 1;
// Generate table

for (n = 0; n < 11; ++n) {

if (n == 0)

p = 1;

else

p = p * 2;

q = 1.0 / (double) p;

printf("\n%2d %8d %20.12lf", n, p, q);

// Print table footer

printf("\n======================================");

return 0;

Copy
Sample Output:
=======================================
n 2 to power n 2 to power -n
=======================================
0 1 1.000000000000
1 2 0.500000000000
2 4 0.250000000000
3 8 0.125000000000
4 16 0.062500000000
5 32 0.031250000000
6 64 0.015625000000
7 128 0.007812500000
8 256 0.003906250000
9 512 0.001953125000
10 1024 0.000976562500
======================================
69. Write a C program to print a binomial coefficient table.
Mx 0 1 2 3 4 5 6 7 8 9 10
----------------------------------------------------------
01
111
2121
31331
414641
5 1 5 10 10 5 1
6 1 6 15 20 15 6 1
7 1 7 21 35 35 21 7 1
8 1 8 28 56 70 56 28 8 1
9 1 9 36 84 126 126 84 36 9 1
10 1 10 45 120 210 252 210 120 45 10 1
----------------------------------------------------------

C Code:

#include<stdio.h>

#define MAX 10

int main() {

int n, a, bi_nom;

// Print header

printf("Mx ");

for (n = 0; n <= 10; ++n)

printf("%d ", n);

printf("\
n----------------------------------------------------------\n");
n = 0;

do {

a = 0, bi_nom = 1;

printf("%2d", n);

while (a <= n) {

if (n == 0 || a == 0)

printf("%4d", bi_nom);

else {

bi_nom = bi_nom * (n - a + 1) / a;

printf("%4d", bi_nom);

a = a + 1;

printf("\n");

n = n + 1;

} while (n <= MAX);

// Print footer

printf("----------------------------------------------------------");

return 0;
}

Copy
Sample Output:
Mx 0 1 2 3 4 5 6 7 8 9 10
----------------------------------------------------------
0 1
1 1 1
2 1 2 1
3 1 3 3 1
4 1 4 6 4 1
5 1 5 10 10 5 1
6 1 6 15 20 15 6 1
7 1 7 21 35 35 21 7 1
8 1 8 28 56 70 56 28 8 1
9 1 9 36 84 126 126 84 36 9 1
10 1 10 45 120 210 252 210 120 45 10 1
----------------------------------------------------------

70. Write a C program to print the alphabet set in decimal and


character form.
[65-A] [66-B] [67-C] [68-D] [69-E] [70-F] [71-G] [72-H] [73-I] [74-J]
[75-K] [76-L] [77-M] [78-N] [79-O] [80-P] [81-Q] [82-R] [83-S] [84-T]
[85-U] [86-V] [87-W] [88-X] [89-Y]
[90-Z] [97-a] [98-b] [99-c] [100-d] [101-e] [102-f] [103-g] [104-h]
[105-i] [106-j] [107-k] [108-l] [109-m] [110-n] [111-o] [112-p] [113-q]
[114-r] [115-s] [116-t] [117-u] [118-v]
[119-w] [120-x] [121-y] [122-z]

C Code:

#include <stdio.h>

#define N 10

int main() {

char chr;

printf("\n");
// Loop through ASCII values from 65 ('A') to 122 ('z')

for (chr = 65; chr <= 122; chr = chr + 1) {

// Exclude characters between 'Z' and 'a'

if (chr > 90 && chr < 97)

continue;

printf("[%2d-%c] ", chr, chr);

return 0;

Copy
Sample Output:
[65-A] [66-B] [67-C] [68-D] [69-E] [70-F] [71-G] [72-H] [73-I]
[74-J] [75-K] [76-L] [77-M] [78-N] [79-O] [80-P] [81-Q] [82-R]
[83-S] [84-T] [85-U] [86-V] [87-W] [88-X] [89-Y] [90-Z] [97-a]
[98-b] [99-c] [100-d] [101-e] [102-f] [103-g] [104-h] [105-i]
[106-j] [107-k] [108-l] [109-m] [110-n] [111-o] [112-p] [113-q]
[114-r] [115-s] [116-t] [117-u] [118-v] [119-w] [120-x] [121-y]
[122-z]

71. Write a C program to copy a given string into another and


count the number of characters copied.
Input a string
Original string: w3resource
Number of characters = 10

C Code:

#include<stdio.h>

#define N 10
int main() {

char str1[80], str2[80];

int i;

// Prompt for user input

printf("Input a string: ");

scanf("%s", str2);

// Copy characters from str2 to str1

for(i=0; str2[i]!='\0'; i++)

str1[i]=str2[i];

str1[i]='\0';

// Output results

printf("\n");

printf("Original string: %s", str1);

printf("\nNumber of characters = %d\n", i);

return 0;

Copy
Sample Output:
Input a string
Original string: w3resource
Number of characters = 10
72. Write a C program to remove any negative sign in front of a
number.
Input a value (negative):
Original value = -253
Absolute value = 253

C Code:

#include<stdio.h>

#define N 10

// Function prototype declaration

int abs_val(int);

int main() {

int x, result;

// Prompt for user input

printf("Input a value (negative): \n");

scanf("%d", &x);

printf("Original value = %d", x);

// Call the abs_val function and store the result

result = abs_val(x);

// Output the result

printf("\nAbsolute value = %d", result);


return 0;

// Function to calculate the absolute value

int abs_val(int y) {

if(y < 0)

return(y * -1);

else

return(y);

Copy
Sample Output:
Input a value (negative):
Original value = -253
Absolute value = 253

73. Write a C program that reads two integers and checks


whether the first integer is a multiple of the second integer.
Sample Input: 9 3
Sample Output:
Input the first integer : Input the second integer:
9 is a multiple of 3.

C Code:

#include<stdio.h>

// Function to check if n1 is a multiple of n2

int is_Multiple(int n1, int n2)

return n1 % n2 == 0;
}

int main()

int n1, n2;

// Prompt for user input

printf("Input the first integer : ");

scanf("%d", &n1);

printf("Input the second integer: ");

scanf("%d", &n2);

// Check if n1 is a multiple of n2 and print result

if(is_Multiple(n1, n2))

printf("\n%d is a multiple of %d.\n", n1, n2);

else

printf("\n%d is not a multiple of %d.\n", n1, n2);

return 0;

Copy
Sample Output:
Input the first integer : Input the second integer:
9 is a multiple of 3.
74. Write a C program to display the integer equivalents of
letters (a-z, A-Z).
Sample Output:
List of integer equivalents of letters (a-z, A-Z).
==================================================
97 98 99 100 101 102
103 104 105 106 107 108
109 110 111 112 113 114
115 116 117 118 119 120
121 122 32 65 66 67
68 69 70 71 72 73
74 75 76 77 78 79
80 81 82 83 84 85
86 87 88 89 90

C Code:

#include<stdio.h>

int main()

// Define a string containing lowercase and uppercase letters

char* letters = "abcdefghijklmnopqrstuvwxyz


ABCDEFGHIJKLMNOPQRSTUVWXYZ";

int n;

// Print header

printf("List of integer equivalents of letters (a-z, A-Z).\n");

printf("==================================================\n");

// Loop through each character and print its integer equivalent

for(n=0; n<53; n++) {


printf("%d\t", letters[n]);

// Add a newline every 6 characters for better formatting

if((n+1) % 6 == 0)

printf("\n");

return 0;

Copy
Sample Output:
List of integer equivalents of letters (a-z, A-Z).
==================================================
97 98 99 100 101 102
103 104 105 106 107 108
109 110 111 112 113 114
115 116 117 118 119 120
121 122 32 65 66 67
68 69 70 71 72 73
74 75 76 77 78 79
80 81 82 83 84 85
86 87 88 89 90

75. Write a C program that accepts a seven-digit number,


separates the number into its individual digits, and prints the
digits separated from one another by two spaces each.
Sample Input: 2345678
Input a seven digit number:
Output: 2 3 4 5 6 7 8

C Code:

#include<stdio.h>
int main()

int n;

// Prompt for input

printf( "Input a seven digit number: " );

// Read the input

scanf("%d", &n);

// Output header

printf( "\nOutput: " );

// Extract and print each digit

printf("%d ", (n/1000000));

n = n - ((n/1000000)*1000000);

printf("%d ", (n/100000));

n = n - ((n/100000)*100000);

printf("%d ", (n/10000));

n = n - ((n/10000)*10000);

printf("%d ", (n/1000));

n = n - ((n/1000)*1000);
printf("%d ", (n/100));

n = n - ((n/100)*100);

printf("%d ", (n/10));

n = n - ((n/10)*10);

printf("%d\n", (n%10));

return 0;

Copy
Sample Output:
Input a seven digit number:
Output: 2 3 4 5 6 7 8

76. Write a C program to calculate and print the squares and


cubes of the numbers from 0 to 20. It uses tabs to display them in
a table of values.
Sample Output:
Number Square Cube
=========================
000
111
248
3 9 27
.....
18 324 5832
19 361 6859
20 400 8000
C Code:

#include<stdio.h>

int main()

int x;

/* Print column names */

printf("Number\tSquare\tCube\n");

printf("=========================\n");

// Loop to calculate and print squares and cubes

for(x=0; x<=20; x++)

printf("%d\t%d\t%d\n", x, x*x, x*x*x);

return 0;

Copy
Sample Output:
Number Square Cube
=========================
0 0 0
1 1 1
2 4 8
3 9 27
4 16 64
5 25 125
6 36 216
7 49 343
8 64 512
9 81 729
10 100 1000
11 121 1331
12 144 1728
13 169 2197
14 196 2744
15 225 3375
16 256 4096
17 289 4913
18 324 5832
19 361 6859
20 400 8000

77. Write a C program that accepts principal amount, rate of


interest and days for a loan and calculates the simple interest for
the loan, using the following formula.
interest = principal * rate * days / 365.
Sample Input:
10000
.1
365
0
Sample Output:
Input loan amount (0 to quit): Input interest rate: Input term of
the loan in days: The interest amount is $1000.00
Input loan principal_amt (0 to quit):

Sample Input: 10000


.1
365
0

Sample Solution:

C Code:

#include<stdio.h>

int main()

{
// Declare variables

float principal_amt, rate_of_interest, days, interest;

const int yearInDays = 365; // Constant for converting interest


rate

// Prompt user for loan amount

printf( "Input loan amount (0 to quit): " );

scanf( "%f", &principal_amt );

// Main loop for processing loans

while( (int)principal_amt != 0)

// Prompt user for interest rate

printf( "Input interest rate: " );

scanf( "%f", &rate_of_interest );

// Prompt user for loan term in days

printf( "Input term of the loan in days: " );

scanf( "%f", &days );

// Calculate interest

interest = (principal_amt * rate_of_interest * days )/


yearInDays;

// Display interest amount

printf( "The interest amount is $%.2f\n", interest );


// Prompt user for next loan principal_amt

printf( "\n\nInput loan principal_amt (0 to quit): " );

scanf( "%f", &principal_amt );

return 0;

Copy
Sample Output:
Input loan amount (0 to quit): Input interest rate: Input term of
the loan in days: The interest amount is $1000.00

Input loan principal_amt (0 to quit):

78. Write a C program to demonstrate the difference between


predecrementing and postdecrementing using the decrement
operator --.
Sample Output:
Predecrementing:
x = 10
x-- = 10
x=9

C Code:

#include<stdio.h>

int main()

int x = 10; // Initialize variable x with value 10


// Predecrementing

printf("Predecrementing:\n");

printf("x = %d\n", x); // Print current value of x

printf("x-- = %d\n", x--); // Print x and then decrement it

printf("x = %d\n\n", x); // Print updated value of x

x = 10; // Reset x to 10

// Postdecrementing

printf("Postdecrementing:\n");

printf(" x = %d\n", x); // Print current value of x

printf("--x = %d\n", --x); // Decrement x and then print it

printf(" x = %d\n", x); // Print updated value of x

return 0;

Copy
Sample Output:
Predecrementing:
x = 10
x-- = 10
x = 9

79. Write a C program using looping to produce the following


table of values.
Sample Output:
x x+2 x+4 x+6
--------------------------------
1 3 5 7
4 6 8 10
7 9 11 13
10 12 14 16
13 15 17 19

C Code:

#include<stdio.h>

int main()

int x; // Declare variable x

// Print header for table

printf("x\tx+2\tx+4\tx+6\n\n");

printf("---------------------------\n");

// Loop to generate and print table values

for(x=1; x<=15; x+=3)

printf("%d\t%d\t%d\t%d\n", x, (x+2), (x+4), (x+6));

return 0; // Indicate successful program execution

Copy
Sample Output:
x x+2 x+4 x+6

---------------------------
1 3 5 7
4 6 8 10
7 9 11 13
10 12 14 16
13 15 17 19
80. Write a C program that reads the side (side sizes between 1
and 10 ) of a square and prints square using hash (#) character.
Sample Input: 10
Sample Output:
Input the size of the square:
# # # # # # # # # #
# # # # # # # # # #
# # # # # # # # # #
# # # # # # # # # #
# # # # # # # # # #
# # # # # # # # # #
# # # # # # # # # #
# # # # # # # # # #
# # # # # # # # # #
# # # # # # # # # #

Sample Input: 10

Sample Solution:

C Code:

#include<stdio.h>

int main()

int size, i, j; // Declare variables for size and loop counters

// Prompt user for the size of the square

printf( "Input the size of the square: \n" );

scanf( "%d", &size );

// Check if the size is within the valid range


if(size < 1 || size > 10) {

printf("Size should be in the range 1 to 10\n"); // Print


error message

return 0; // Exit the program

// Loop for rows

for(i=0; i<size; i++) {

// Loop for columns

for(j=0; j<size; j++) {

printf(" #"); // Print a space and a #

printf("\n"); // Move to the next line after completing a row

return 0; // Indicate successful program execution

Copy
Sample Output:
Input the size of the square:
# # # # # # # # # #
# # # # # # # # # #
# # # # # # # # # #
# # # # # # # # # #
# # # # # # # # # #
# # # # # # # # # #
# # # # # # # # # #
# # # # # # # # # #
# # # # # # # # # #
# # # # # # # # # #

81. Write a C program that reads the side (side sizes between 1
and 10 ) of a square and prints a hollow square using the hash (#)
character.
Sample Input: 10
Sample Output:
Input the size of the square:
##########
# #
# #
# #
# #
# #
# #
# #
# #
##########

Sample Input: 10

Sample Solution:

C Code:

#include <stdio.h>

int main()

// Declare variables

int size, i, j;

// Prompt user for input

printf("Input the size of the square: ");


// Read the size from user

scanf("%d", &size);

// Check if size is within valid range

if (size < 1 || size > 10) {

printf("Size should be in the range 1 to 10\n");

return 0; // Exit program if size is invalid

// Loop for rows

for (i = 0; i< size; i++)

// Loop for columns

for (j = 0; j < size; j++)

// Check if it's a border or inside space

if (i == 0 || i == size - 1)

printf("#"); // Print border

else if (j == 0 || j == size - 1)

printf("#"); // Print border

else

printf(" "); // Print space for inside

printf("\n"); // Move to the next line after each row is printed

}
return 0; // Indicate successful execution of the program

Copy
Sample Output:
Input the size of the square:
##########
# #
# #
# #
# #
# #
# #
# #
# #
##########

82. Write a C program that reads a five-digit integer and


determines whether or not it's a palindrome.
Sample Input: 33333
Sample Output:
Input a five-digit number: 33333 is a palindrome.
Sample Input: 33333

Sample Solution:

C Code:

#include <stdio.h>

// Function to check if a number is a palindrome

int is_Palindrome(int);

int main()

{
int n;

// Prompt user for input

printf("Input a five-digit number: ");

// Read the number from user

scanf("%d", &n);

// Check if the number is a palindrome using the function


is_Palindrome

if (is_Palindrome(n))

printf("%d is a palindrome.", n);

else

printf("%d is not a palindrome.", n);

return 0;

// Function to check if a number is a palindrome

int is_Palindrome(int n) {

int x = n;

int reverse_num = 0;

// Extract the digits in reverse order and reconstruct the number

reverse_num += x / 10000;
x = x - ((x / 10000) * 10000);

reverse_num += ((x / 1000) * 10);

x = x - ((x / 1000) * 1000);

reverse_num += ((x / 100) * 100);

x = x - ((x / 100) * 100);

reverse_num += ((x / 10) * 1000);

x = x - ((x / 10) * 10);

reverse_num += ((x % 10) * 10000);

// Check if the original number is equal to the reversed number

return n == reverse_num;

Copy
Sample Output:
Input a five-digit number: 33333 is a palindrome.

83. Write a C program that reads an integer (7 digits or fewer)


and counts the number of 3s in the given number.
Sample Input: 538453
Sample Output:
Input a number: The number of threes in the said number is 2

C Code:
#include<stdio.h>

// Function to count the occurrences of digit '3' in a number

int count_three(int);

int main()

int num;

// Prompt user for input

printf("Input a number: ");

scanf("%d", &num);

// Call the function count_three and print the result

printf("The number of threes in the said number is %d\n",


count_three(num) );

return 0;

int count_three(int num)

int ctr = 0; // Initialize counter variable

int remainder; // Variable to store the remainder

// Loop until num is greater than 0

while(num> 0) {

remainder = num % 10; // Get the last digit


num /= 10; // Remove the last digit

if(remainder == 3) // Check if the last digit is 3

ctr++; // Increment counter if it is 3

return ctr; // Return the count of occurrences of 3

Copy
Sample Output:
Input a number: The number of threes in the said number is 2.

84. Write a C program to calculate and print the average of some


integers. Accept all the values preceding 888.
Sample Input:12
15
24
888
Sample Output:
Input each number on a separate line (888 to exit):

The average value of the said numbers is 17.000000

Sample Input: 12
15
24
888

Sample Solution:

C Code:

#include <stdio.h>
int main()

int ctr = 0, n; // Initialize counter and variable for input

int sum = 0; // Initialize sum variable

float avg_value = 0; // Initialize average variable

// Prompt user for input

printf("Input each number on a separate line (888 to exit):\n");

// Read the first number

scanf("%d", &n);

// Loop until the user enters 888

while (n != 888) {

sum += n; // Add the number to the sum

ctr++; // Increment counter

scanf("%d", &n); // Read the next number

// Calculate the average if there were inputs

if (ctr)

avg_value = (float) sum / ctr;

// Print the average value


printf("\nThe average value of the said numbers is %f\n", avg_value);

return 0; // Indicate successful execution of the program

Copy
Sample Output:
Input each number on a separate line (888 to exit):

The average value of the said numbers is 17.000000

85. Write a C program to print a table of all the Roman numeral


equivalents of decimal numbers in the range 1 to 50.
Sample Output:
Decimal Roman
number numeral
-------------------
1 I
2 II
3 III
4 IV
.....
98 LXXXXVIII
99 LXXXXIX
100 C

C Code:

#include <stdio.h>

int main()

int i, x;

// Print the header of the Roman numeral table


printf("Decimal Roman\n");

printf("number numeral\n");

printf("-------------------\n");

// Loop through numbers from 1 to 100

for(i = 1; i<= 100; i++)

x = i; // Store current value of i in x

printf("%d ", x); // Print the decimal number

// Convert decimal number to Roman numeral

if(x == 100) {

printf("C"); // Print Roman numeral for 100

x = 0; // Reset x to 0

if(x >= 50) {

printf("L"); // Print Roman numeral for 50

x -= 50; // Subtract 50 from x

while(x >= 10) {

printf("X"); // Print Roman numeral for 10

x -= 10; // Subtract 10 from x

if(x >= 5) {

if(x % 10 == 9) {
printf("IX"); // Print Roman numeral for 9

x -= 9; // Subtract 9 from x

else {

printf("V"); // Print Roman numeral for 5

x -= 5; // Subtract 5 from x

while(x > 0)

if(x % 10 == 4) {

printf("IV"); // Print Roman numeral for 4

x -= 4; // Subtract 4 from x

else {

printf("I"); // Print Roman numeral for 1

x -= 1; // Subtract 1 from x

printf("\n"); // Move to the next line for the next number

return 0;

}
Copy
Sample Output:
Decimal Roman
numbers numerals
-------------------
1 I
2 II
3 III
4 IV
5 V
6 VI
7 VII
8 VIII
9 IX
10 X
11 XI
12 XII
13 XIII
14 XIV
15 XV
16 XVI
17 XVII
18 XVIII
19 XIX
20 XX
21 XXI
22 XXII
23 XXIII
24 XXIV
25 XXV
26 XXVI
27 XXVII
28 XXVIII
29 XXIX
30 XXX
31 XXXI
32 XXXII
33 XXXIII
34 XXXIV
35 XXXV
36 XXXVI
37 XXXVII
38 XXXVIII
39 XXXIX
40 XL
41 XLI
42 XLII
43 XLIII
44 XLIV
45 XLV
46 XLVI
47 XLVII
48 XLVIII
49 XLIX
50 L
51 LI
52 LII
53 LIII
54 LIV
55 LV
56 LVI
57 LVII
58 LVIII
59 LIX
60 LX
61 LXI
62 LXII
63 LXIII
64 LXIV
65 LXV
66 LXVI
67 LXVII
68 LXVIII
69 LXIX
70 LXX
71 LXXI
72 LXXII
73 LXXIII
74 LXXIV
75 LXXV
76 LXXVI
77 LXXVII
78 LXXVIII
79 LXXIX
80 LXXX
81 LXXXI
82 LXXXII
83 LXXXIII
84 LXXXIV
85 LXXXV
86 LXXXVI
87 LXXXVII
88 LXXXVIII
89 LXXXIX
90 XC
91 XCI
92 XCII
93 XCIII
94 XCIV
95 XCV
96 XCVI
97 XCVII
98 XCVIII
99 XCIX
100 C

86. Write a C program to display the sizes and ranges for each of
C's data types.
Sample Output:
Size of C data types:

Type Bytes

--------------------------------
char 1
int8_t 1
unsigned char 1
uint8_t 1
short 2
int16_t 2
uint16t 2
int 4
unsigned 4
long 8
unsigned long 8
int32_t 4
uint32_t 4
long long 8
int64_t 8
unsigned long long 8
uint64_t 8
float 4
double 8
long double 16
_Bool 1
C Code:

#include <stdio.h>

#include <stdint.h>

#include <stdbool.h>

#include <limits.h>

int main(void) {

// Display title

printf("Size and Range of C data types:\n\n");

// Display column headers

printf("%-20s %-20s %-20s\n", "Type", "Bytes", "Range");

// Display separator line

printf("------------------------------------------------------\
n");

// Print size and range of various data types

printf("%-20s %lu %-20d to %-20d\n", "char", sizeof(char),


CHAR_MIN, CHAR_MAX);

printf("%-20s %lu %-20d to %-20d\n", "int8_t", sizeof(int8_t),


INT8_MIN, INT8_MAX);

printf("%-20s %lu %-20d to %-20d\n", "unsigned char",


sizeof(unsigned char), 0, UCHAR_MAX);

printf("%-20s %lu %-20d to %-20d\n", "uint8_t", sizeof(uint8_t),


0, UINT8_MAX);

printf("%-20s %lu %-20d to %-20d\n", "short", sizeof(short),


SHRT_MIN, SHRT_MAX);

printf("%-20s %lu %-20d to %-20d\n", "int16_t", sizeof(int16_t),


INT16_MIN, INT16_MAX);

printf("%-20s %lu %-20d to %-20d\n", "uint16_t", sizeof(uint16_t),


0, UINT16_MAX);
printf("%-20s %lu %-20d to %-20d\n", "int", sizeof(int), INT_MIN,
INT_MAX);

printf("%-20s %lu %-20u to %-20u\n", "unsigned", sizeof(unsigned),


0, UINT_MAX);

printf("%-20s %lu %-20ld to %-20ld\n", "long", sizeof(long),


LONG_MIN, LONG_MAX);

printf("%-20s %lu %-20lu to %-20lu\n", "unsigned long",


sizeof(unsigned long), 0, ULONG_MAX);

printf("%-20s %lu %-20d to %-20d\n", "int32_t", sizeof(int32_t),


INT32_MIN, INT32_MAX);

printf("%-20s %lu %-20u to %-20u\n", "uint32_t", sizeof(uint32_t),


0, UINT32_MAX);

printf("%-20s %lu %-20lld to %-20lld\n", "long long", sizeof(long


long), LLONG_MIN, LLONG_MAX);

printf("%-20s %lu %-20llu to %-20llu\n", "int64_t",


sizeof(int64_t), 0LL, ULLONG_MAX);

printf("%-20s %lu %-20lld to %-20lld\n", "int64_t",


sizeof(int64_t), LLONG_MIN, LLONG_MAX);

printf("%-20s %lu %-20llu to %-20llu\n", "uint64_t",


sizeof(uint64_t), 0ULL, ULLONG_MAX);

// Floating point types don't have well-defined "range" in the


same sense as integers

// Add a newline for better output formatting

printf("\n");

// Indicate successful execution of the program

return 0;

Copy
Sample Output:
Size and Range of C data types:
Type Bytes Range
------------------------------------------------------
char 1 -128 to 127
int8_t 1 -128 to 127
unsigned char 1 0 to 255
uint8_t 1 0 to 255
short 2 -32768 to 32767
int16_t 2 -32768 to 32767
uint16_t 2 0 to 65535
int 4 -2147483648 to 2147483647
unsigned 4 0 to 4294967295
long 4 -2147483648 to 2147483647
unsigned long 4 0 to 4294967295
int32_t 4 -2147483648 to 2147483647
uint32_t 4 0 to 4294967295
long long 8 -9223372036854775808 to
9223372036854775807
int64_t 8 0 to
18446744073709551615
int64_t 8 -9223372036854775808 to
9223372036854775807
uint64_t 8 0 to
18446744073709551615

86. Write a C program to display the sizes and ranges for each of
C's data types.
Sample Output:
Size of C data types:

Type Bytes

--------------------------------
char 1
int8_t 1
unsigned char 1
uint8_t 1
short 2
int16_t 2
uint16t 2
int 4
unsigned 4
long 8
unsigned long 8
int32_t 4
uint32_t 4
long long 8
int64_t 8
unsigned long long 8
uint64_t 8
float 4
double 8
long double 16
_Bool 1

C Code:

#include <stdio.h>

#include <stdint.h>

#include <stdbool.h>

#include <limits.h>

int main(void) {

// Display title

printf("Size and Range of C data types:\n\n");

// Display column headers

printf("%-20s %-20s %-20s\n", "Type", "Bytes", "Range");

// Display separator line

printf("------------------------------------------------------\
n");

// Print size and range of various data types

printf("%-20s %lu %-20d to %-20d\n", "char", sizeof(char),


CHAR_MIN, CHAR_MAX);

printf("%-20s %lu %-20d to %-20d\n", "int8_t", sizeof(int8_t),


INT8_MIN, INT8_MAX);

printf("%-20s %lu %-20d to %-20d\n", "unsigned char",


sizeof(unsigned char), 0, UCHAR_MAX);

printf("%-20s %lu %-20d to %-20d\n", "uint8_t", sizeof(uint8_t),


0, UINT8_MAX);
printf("%-20s %lu %-20d to %-20d\n", "short", sizeof(short),
SHRT_MIN, SHRT_MAX);

printf("%-20s %lu %-20d to %-20d\n", "int16_t", sizeof(int16_t),


INT16_MIN, INT16_MAX);

printf("%-20s %lu %-20d to %-20d\n", "uint16_t", sizeof(uint16_t),


0, UINT16_MAX);

printf("%-20s %lu %-20d to %-20d\n", "int", sizeof(int), INT_MIN,


INT_MAX);

printf("%-20s %lu %-20u to %-20u\n", "unsigned", sizeof(unsigned),


0, UINT_MAX);

printf("%-20s %lu %-20ld to %-20ld\n", "long", sizeof(long),


LONG_MIN, LONG_MAX);

printf("%-20s %lu %-20lu to %-20lu\n", "unsigned long",


sizeof(unsigned long), 0, ULONG_MAX);

printf("%-20s %lu %-20d to %-20d\n", "int32_t", sizeof(int32_t),


INT32_MIN, INT32_MAX);

printf("%-20s %lu %-20u to %-20u\n", "uint32_t", sizeof(uint32_t),


0, UINT32_MAX);

printf("%-20s %lu %-20lld to %-20lld\n", "long long", sizeof(long


long), LLONG_MIN, LLONG_MAX);

printf("%-20s %lu %-20llu to %-20llu\n", "int64_t",


sizeof(int64_t), 0LL, ULLONG_MAX);

printf("%-20s %lu %-20lld to %-20lld\n", "int64_t",


sizeof(int64_t), LLONG_MIN, LLONG_MAX);

printf("%-20s %lu %-20llu to %-20llu\n", "uint64_t",


sizeof(uint64_t), 0ULL, ULLONG_MAX);

// Floating point types don't have well-defined "range" in the


same sense as integers

// Add a newline for better output formatting

printf("\n");

// Indicate successful execution of the program


return 0;

Copy
Sample Output:
Size and Range of C data types:

Type Bytes Range


------------------------------------------------------
char 1 -128 to 127
int8_t 1 -128 to 127
unsigned char 1 0 to 255
uint8_t 1 0 to 255
short 2 -32768 to 32767
int16_t 2 -32768 to 32767
uint16_t 2 0 to 65535
int 4 -2147483648 to 2147483647
unsigned 4 0 to 4294967295
long 4 -2147483648 to 2147483647
unsigned long 4 0 to 4294967295
int32_t 4 -2147483648 to 2147483647
uint32_t 4 0 to 4294967295
long long 8 -9223372036854775808 to
9223372036854775807
int64_t 8 0 to
18446744073709551615
int64_t 8 -9223372036854775808 to
9223372036854775807
uint64_t 8 0 to
18446744073709551615

87. Write a C program to display the minimum and maximum


values for each of C's data types.
Sample Output:
Ranges for integer data types in C

------------------------------------------------------------
int8_t -128 127
int16_t -32768 32767
int32_t -2147483648 2147483647
int64_t -9223372036854775808 9223372036854775807
uint8_t 0 255
uint16_t 0 65535
uint32_t 0 4294967295
uint64_t 0 18446744073709551615

============================================================

Ranges for real number data types in C

------------------------------------------------------------
float 1.175494e-38 3.402823e+38
double 2.225074e-308 1.797693e+308
long double 3.362103e-4932 1.189731e+4932

C Code:

#include <stdio.h>

#include <stdint.h>

#include <stdbool.h>

#include <limits.h>

#include <float.h>

int main( void )

// Print header for integer data types

printf( "Ranges for integer data types in C\n\n" );

// Print separator line

printf(
"------------------------------------------------------------\n");

// Print range for int8_t

printf( "int8_t %20d %20d\n" , SCHAR_MIN , SCHAR_MAX );

// Print range for int16_t


printf( "int16_t %20d %20d\n" , SHRT_MIN , SHRT_MAX );

// Print range for int32_t

printf( "int32_t %20d %20d\n" , INT_MIN , INT_MAX );

// Print range for int64_t

printf( "int64_t %20lld %20lld\n" , LLONG_MIN , LLONG_MAX );

// Print range for uint8_t

printf( "uint8_t %20d %20d\n" , 0 , UCHAR_MAX );

// Print range for uint16_t

printf( "uint16_t %20d %20d\n" , 0 , USHRT_MAX );

// Print range for uint32_t

printf( "uint32_t %20d %20u\n" , 0 , UINT_MAX );

// Print range for uint64_t

printf( "uint64_t %20d %20llu\n" , 0 , ULLONG_MAX );

// Print separator line

printf( "\n" );

// Print separator line


printf(
"============================================================\n\n");

// Print header for real number data types

printf( "Ranges for real number data types in C\n\n" );

// Print separator line

printf(
"------------------------------------------------------------\n");

// Print range for float

printf( "float %14.7g %14.7g\n" , FLT_MIN , FLT_MAX );

// Print range for double

printf( "double %14.7g %14.7g\n" , DBL_MIN , DBL_MAX );

// Print range for long double

printf( "long double %14.7Lg %14.7Lg\n" , LDBL_MIN , LDBL_MAX );

// Print separator line

printf( "\n" );

return 0;

Copy
Sample Output:
Ranges for integer data types in C

------------------------------------------------------------
int8_t -128 127
int16_t -32768 32767
int32_t -2147483648 2147483647
int64_t -9223372036854775808 9223372036854775807
uint8_t 0 255
uint16_t 0 65535
uint32_t 0 4294967295
uint64_t 0 18446744073709551615

============================================================

Ranges for real number data types in C

------------------------------------------------------------
float 1.175494e-38 3.402823e+38
double 2.225074e-308 1.797693e+308
long double 3.362103e-4932 1.189731e+4932

88. Write a C program to create an extended ASCII table. Print


the ASCII values 32 through 255.
Sample Output:
|----------------------------------------------------------------
-----------------------------------------|
|extended ASCII table - excluding control characters
|
| Ch Dec Hex | Ch Dec Hex | Ch Dec Hex | Ch Dec Hex |
Ch Dec Hex | Ch Dec Hex | Ch Dec Hex |
|----------------|----------------|-------------|--------------|-
-------------|-------------|-------------|
| har 32 0x20 | @har 64 0x40 | ` 96 0x60 | � 128 0x80 |
� 160 0xa0 | � 192 0xc0 | � 224 0xe0 |
| !har 33 0x21 | Ahar 65 0x41 | a 97 0x61 | � 129 0x81 |
� 161 0xa1 | � 193 0xc1 | � 225 0xe1 |
| "har 34 0x22 | Bhar 66 0x42 | b 98 0x62 | � 130 0x82 |
� 162 0xa2 | � 194 0xc2 | � 226 0xe2 |
| #har 35 0x23 | Char 67 0x43 | c 99 0x63 | � 131 0x83 |
� 163 0xa3 | � 195 0xc3 | � 227 0xe3 |
| $har 36 0x24 | Dhar 68 0x44 | d 100 0x64 | � 132 0x84 |
� 164 0xa4 | � 196 0xc4 | � 228 0xe4 |
| %har 37 0x25 | Ehar 69 0x45 | e 101 0x65 | � 133 0x85 |
� 165 0xa5 | � 197 0xc5 | � 229 0xe5 |
| &har 38 0x26 | Fhar 70 0x46 | f 102 0x66 | � 134 0x86 |
� 166 0xa6 | � 198 0xc6 | � 230 0xe6 |
| 'har 39 0x27 | Ghar 71 0x47 | g 103 0x67 | � 135 0x87 |
� 167 0xa7 | � 199 0xc7 | � 231 0xe7 |
| (har 40 0x28 | Hhar 72 0x48 | h 104 0x68 | � 136 0x88 |
� 168 0xa8 | � 200 0xc8 | � 232 0xe8 |
| )har 41 0x29 | Ihar 73 0x49 | i 105 0x69 | � 137 0x89 |
� 169 0xa9 | � 201 0xc9 | � 233 0xe9 |
| *har 42 0x2a | Jhar 74 0x4a | j 106 0x6a | � 138 0x8a |
� 170 0xaa | � 202 0xca | � 234 0xea |
| +har 43 0x2b | Khar 75 0x4b | k 107 0x6b | � 139 0x8b |
� 171 0xab | � 203 0xcb | � 235 0xeb |
| ,har 44 0x2c | Lhar 76 0x4c | l 108 0x6c | � 140 0x8c |
� 172 0xac | � 204 0xcc | � 236 0xec |
| -har 45 0x2d | Mhar 77 0x4d | m 109 0x6d | � 141 0x8d |
� 173 0xad | � 205 0xcd | � 237 0xed |
| .har 46 0x2e | Nhar 78 0x4e | n 110 0x6e | � 142 0x8e |
� 174 0xae | � 206 0xce | � 238 0xee |
| /har 47 0x2f | Ohar 79 0x4f | o 111 0x6f | � 143 0x8f |
� 175 0xaf | � 207 0xcf | � 239 0xef |
| 0har 48 0x30 | Phar 80 0x50 | p 112 0x70 | � 144 0x90 |
� 176 0xb0 | � 208 0xd0 | � 240 0xf0 |
| 1har 49 0x31 | Qhar 81 0x51 | q 113 0x71 | � 145 0x91 |
� 177 0xb1 | � 209 0xd1 | � 241 0xf1 |
| 2har 50 0x32 | Rhar 82 0x52 | r 114 0x72 | � 146 0x92 |
� 178 0xb2 | � 210 0xd2 | � 242 0xf2 |
| 3har 51 0x33 | Shar 83 0x53 | s 115 0x73 | � 147 0x93 |
� 179 0xb3 | � 211 0xd3 | � 243 0xf3 |
| 4har 52 0x34 | Thar 84 0x54 | t 116 0x74 | � 148 0x94 |
� 180 0xb4 | � 212 0xd4 | � 244 0xf4 |
| 5har 53 0x35 | Uhar 85 0x55 | u 117 0x75 | � 149 0x95 |
� 181 0xb5 | � 213 0xd5 | � 245 0xf5 |
| 6har 54 0x36 | Vhar 86 0x56 | v 118 0x76 | � 150 0x96 |
� 182 0xb6 | � 214 0xd6 | � 246 0xf6 |
| 7har 55 0x37 | Whar 87 0x57 | w 119 0x77 | � 151 0x97 |
� 183 0xb7 | � 215 0xd7 | � 247 0xf7 |
| 8har 56 0x38 | Xhar 88 0x58 | x 120 0x78 | � 152 0x98 |
� 184 0xb8 | � 216 0xd8 | � 248 0xf8 |
| 9har 57 0x39 | Yhar 89 0x59 | y 121 0x79 | � 153 0x99 |
� 185 0xb9 | � 217 0xd9 | � 249 0xf9 |
| :har 58 0x3a | Zhar 90 0x5a | z 122 0x7a | � 154 0x9a |
� 186 0xba | � 218 0xda | � 250 0xfa |
| ;har 59 0x3b | [har 91 0x5b | { 123 0x7b | � 155 0x9b |
� 187 0xbb | � 219 0xdb | � 251 0xfb |
| <har 60 0x3c | \har 92 0x5c | | 124 0x7c | � 156 0x9c |
� 188 0xbc | � 220 0xdc | � 252 0xfc |
| =har 61 0x3d | ]har 93 0x5d | } 125 0x7d | � 157 0x9d |
� 189 0xbd | � 221 0xdd | � 253 0xfd |
| >har 62 0x3e | ^har 94 0x5e | ~ 126 0x7e | � 158 0x9e |
� 190 0xbe | � 222 0xde | � 254 0xfe |
| ?har 63 0x3f | _har 95 0x5f |DEL 127 0x7f | � 159 0x9f |
� 191 0xbf | � 223 0xdf | � 255 0xff |

C Code:

#include <stdio.h>

int main( void )

unsigned char char1 , char2 , char3 , char4 , char5 , char6 , char7 ,


char8 ;

// Print table header

printf("|-------------------------------------------------------------
--------------------------------------------|\n" );

printf("|extended ASCII table - excluding control characters


|\n" );

printf("| Ch Dec Hex | Ch Dec Hex | Ch Dec Hex | Ch Dec Hex


| Ch Dec Hex | Ch Dec Hex | Ch Dec Hex |\n" );

printf("|----------------|----------------|-------------|-------------
-|--------------|-------------|-------------|\n" );

// Loop through characters


for(int i = 0 ; i< 32; i++)

// Calculate characters for different ranges

char1 = i;

char2 = i+32;

char3 = i+64;

char4 = i+96;

char5 = i+128; // extended ASCII characters

char6 = i+160;

char7 = i+192;

char8 = i+224;

// Print characters and their decimal and hexadecimal


representations

printf( "| %c %3d %#x " , char2 , char2 , char2 );

printf( "| %c %3d %#x " , char3 , char3 , char3 );

// Special case for DEL character

if( char4 == 127 ) {

printf("|%s %3d %#x |" , "DEL" , char4 , char4 );

} else {

printf("| %c %3d %#x |" , char4 , char4 , char4 );

// Print extended ASCII characters for current system.


printf(" %c %3d %#x | %c %3d %#x | %c %3d %#x | %c %3d %#x |\n" ,

char5 , char5 , char5 ,

char6 , char6 , char6 ,

char7 , char7 , char7 ,

char8 , char8 , char8 );

return 0; // Indicate successful execution of the program

Copy
Sample Output:

|----------------------------------------------------------------
-----------------------------------------|
|extended ASCII table - excluding control characters
|
| Ch Dec Hex | Ch Dec Hex | Ch Dec Hex | Ch Dec Hex |
Ch Dec Hex | Ch Dec Hex | Ch Dec Hex |
|----------------|----------------|-------------|--------------|-
-------------|-------------|-------------|
| har 32 0x20 | @har 64 0x40 | ` 96 0x60 | � 128 0x80 |
� 160 0xa0 | � 192 0xc0 | � 224 0xe0 |
| !har 33 0x21 | Ahar 65 0x41 | a 97 0x61 | � 129 0x81 |
� 161 0xa1 | � 193 0xc1 | � 225 0xe1 |
| "har 34 0x22 | Bhar 66 0x42 | b 98 0x62 | � 130 0x82 |
� 162 0xa2 | � 194 0xc2 | � 226 0xe2 |
| #har 35 0x23 | Char 67 0x43 | c 99 0x63 | � 131 0x83 |
� 163 0xa3 | � 195 0xc3 | � 227 0xe3 |
| $har 36 0x24 | Dhar 68 0x44 | d 100 0x64 | � 132 0x84 |
� 164 0xa4 | � 196 0xc4 | � 228 0xe4 |
| %har 37 0x25 | Ehar 69 0x45 | e 101 0x65 | � 133 0x85 |
� 165 0xa5 | � 197 0xc5 | � 229 0xe5 |
| &har 38 0x26 | Fhar 70 0x46 | f 102 0x66 | � 134 0x86 |
� 166 0xa6 | � 198 0xc6 | � 230 0xe6 |
| 'har 39 0x27 | Ghar 71 0x47 | g 103 0x67 | � 135 0x87 |
� 167 0xa7 | � 199 0xc7 | � 231 0xe7 |
| (har 40 0x28 | Hhar 72 0x48 | h 104 0x68 | � 136 0x88 |
� 168 0xa8 | � 200 0xc8 | � 232 0xe8 |
| )har 41 0x29 | Ihar 73 0x49 | i 105 0x69 | � 137 0x89 |
� 169 0xa9 | � 201 0xc9 | � 233 0xe9 |
| *har 42 0x2a | Jhar 74 0x4a | j 106 0x6a | � 138 0x8a |
� 170 0xaa | � 202 0xca | � 234 0xea |
| +har 43 0x2b | Khar 75 0x4b | k 107 0x6b | � 139 0x8b |
� 171 0xab | � 203 0xcb | � 235 0xeb |
| ,har 44 0x2c | Lhar 76 0x4c | l 108 0x6c | � 140 0x8c |
� 172 0xac | � 204 0xcc | � 236 0xec |
| -har 45 0x2d | Mhar 77 0x4d | m 109 0x6d | � 141 0x8d |
� 173 0xad | � 205 0xcd | � 237 0xed |
| .har 46 0x2e | Nhar 78 0x4e | n 110 0x6e | � 142 0x8e |
� 174 0xae | � 206 0xce | � 238 0xee |
| /har 47 0x2f | Ohar 79 0x4f | o 111 0x6f | � 143 0x8f |
� 175 0xaf | � 207 0xcf | � 239 0xef |
| 0har 48 0x30 | Phar 80 0x50 | p 112 0x70 | � 144 0x90 |
� 176 0xb0 | � 208 0xd0 | � 240 0xf0 |
| 1har 49 0x31 | Qhar 81 0x51 | q 113 0x71 | � 145 0x91 |
� 177 0xb1 | � 209 0xd1 | � 241 0xf1 |
| 2har 50 0x32 | Rhar 82 0x52 | r 114 0x72 | � 146 0x92 |
� 178 0xb2 | � 210 0xd2 | � 242 0xf2 |
| 3har 51 0x33 | Shar 83 0x53 | s 115 0x73 | � 147 0x93 |
� 179 0xb3 | � 211 0xd3 | � 243 0xf3 |
| 4har 52 0x34 | Thar 84 0x54 | t 116 0x74 | � 148 0x94 |
� 180 0xb4 | � 212 0xd4 | � 244 0xf4 |
| 5har 53 0x35 | Uhar 85 0x55 | u 117 0x75 | � 149 0x95 |
� 181 0xb5 | � 213 0xd5 | � 245 0xf5 |
| 6har 54 0x36 | Vhar 86 0x56 | v 118 0x76 | � 150 0x96 |
� 182 0xb6 | � 214 0xd6 | � 246 0xf6 |
| 7har 55 0x37 | Whar 87 0x57 | w 119 0x77 | � 151 0x97 |
� 183 0xb7 | � 215 0xd7 | � 247 0xf7 |
| 8har 56 0x38 | Xhar 88 0x58 | x 120 0x78 | � 152 0x98 |
� 184 0xb8 | � 216 0xd8 | � 248 0xf8 |
| 9har 57 0x39 | Yhar 89 0x59 | y 121 0x79 | � 153 0x99 |
� 185 0xb9 | � 217 0xd9 | � 249 0xf9 |
| :har 58 0x3a | Zhar 90 0x5a | z 122 0x7a | � 154 0x9a |
� 186 0xba | � 218 0xda | � 250 0xfa |
| ;har 59 0x3b | [har 91 0x5b | { 123 0x7b | � 155 0x9b |
� 187 0xbb | � 219 0xdb | � 251 0xfb |
| <har 60 0x3c | \har 92 0x5c | | 124 0x7c | � 156 0x9c |
� 188 0xbc | � 220 0xdc | � 252 0xfc |
| =har 61 0x3d | ]har 93 0x5d | } 125 0x7d | � 157 0x9d |
� 189 0xbd | � 221 0xdd | � 253 0xfd |
| >har 62 0x3e | ^har 94 0x5e | ~ 126 0x7e | � 158 0x9e |
� 190 0xbe | � 222 0xde | � 254 0xfe |
| ?har 63 0x3f | _har 95 0x5f |DEL 127 0x7f | � 159 0x9f |
� 191 0xbf | � 223 0xdf | � 255 0xff |

89. Write a C programming to calculate (x + y + z) for each pair


of integers x, y and z where -2^31 <= x, y, z<= 2^31-1.
Sample Output:
Result: 140733606875472

C Code:

#include <stdio.h>

int main()

// Declare variables

long long x, y, z;

// Prompt the user for input

printf("Input x, y, z:\n");

// Read input values

scanf("%lld %lld %lld", &x, &y, &z);


// Calculate and print the result

printf("Result: %lld\n", x + y + z);

return 0; // Indicate successful execution of the program

Copy
Sample Output:
Input x,y,x:
Result: 140733606875472

90. Write a C program to find all prime palindromes in the range


of two given numbers x and y (5 <= x<y<= 1000,000,000).
A number is called a prime palindrome if the number is both a
prime number and a palindrome.
Sample Output:
Input two numbers (separated by a space):
List of prime palindromes:
0
1

C Code:

#include<stdio.h>

// Function to compute a palindrome number from a given number

int compute(int n){

if(n == 9) // Special case for n = 9

return 11; // Return 11

int res = 0, tmp, base = 1;

// Loop to reverse the digits of n


for(tmp = n / 10; tmp> 0; tmp = tmp / 10){

res = res * 10 + tmp % 10; // Build the reversed number

base *= 10;

return n * base + res; // Combine the original and reversed


numbers

// Function to check if a number is prime and print it if it is

int prime(int n){

int i;

int flag;

// Loop to check for factors of n

for(i = 2; i * i<= n; i++){

flag = 0;

if(n % i == 0){

flag = 1; // Set flag to indicate non-prime

break;

if(flag == 0){ // If flag remains 0, n is a prime number

printf("%d\n", n); // Print the prime number


}

int main(){

int x, y, temp = 0;

printf("Input two numbers (separated by a space):\n");

scanf("%d %d", &x, &y);

printf("List of prime palindromes:\n");

// Loop to generate and check palindrome numbers

for(; temp <= y; x++){

temp = compute(x);

prime(temp);

return 0; // Indicate successful execution of the program

Copy
Sample Output:
Input two numbers (separated by a space):
List of prime palindromes:
0
1

91. Write a C program to find the angle between (12:00 to 11:59)


the hour hand and the minute hand of a clock. The hour hand and
the minute hand are always between 0 and 180 degrees.
For example, when it's 12 o'clock, the angle of the two hands is 0
while 3:00 is 45 degrees and 6:00 is 180 degrees.
Sample Output:
Input hour(h) and minute(m) (separated by a space):
3 0
At 3:00 the angle is 90.0 degrees.
Input hour(h) and minute(m) (separated by a space):
6 15
The angle is 90.0 degrees at 6:15.
Input hour(h) and minute(m) (separated by a space):
12 0
At 12:00 the angle is 0.0 degrees.

C Code:

#include <stdio.h>

#include <math.h>

#include <stdlib.h>

int main()

int h, m; // Declare variables for hour and minute

double angle; // Declare variable for angle

const int num[13] = {0,30,60,90,120,150,180,210,240,270,300,330,0}; //


Define an array of angles

printf("Input hour(h) and minute(m) (separated by a space):\n"); //


Prompt user for input

scanf("%d %d",&h,&m); // Read input for hour and minute


angle = num[h] - m*5.5; // Calculate the angle based on the input
values

if (angle < 0) // Ensure angle is positive

angle = -angle;

if (angle > 180) // Ensure angle is within 180 degrees

angle = 360 - angle;

if ( m < 10 )

printf("At %d:0%d the angle is %.1f degrees.\n",h,m,angle); // Print


angle and time in format HH:MM

else

printf("The angle is %.1f degrees at %d:%d.\n",angle,h,m); // Print


angle and time in format HH:MM

return 0; // Indicate successful execution of the program

Copy
Sample Output:
Input hour(h) and minute(m) (separated by a space):
3 0
At 3:00 the angle is 90.0 degrees.
Input hour(h) and minute(m) (separated by a space):
6 15
The angle is 90.0 degrees at 6:15.
Input hour(h) and minute(m) (separated by a space):
12 0
At 12:00 the angle is 0.0 degrees.
92. Write a C program to find the last non-zero digit of the
factorial of a given positive integer.
For example for 5!, the output will be "2" because 5! = 120, and 2
is the last nonzero digit of 120
Sample Output:
Input a positive number:
The last non-zero digit of the said factorial:
0

C Code:

#include <stdio.h>

#include <string.h>

// Array representing the factorials of numbers 0 to 9

const char ftr[] = {1,1,2,6,4,4,4,8,4,6};

// Function to perform computation on an array of digits

void comp(char i[], int* len)

int j;

char c, tmp;

if(i[0] < 5)

c = i[0];

(*len)--;

// Iterate through the digits and perform computation


for(j = 0; j < *len; j++)

tmp = (c*10 + i[j+1]) % 5;

i[j] = (c*10 + i[j+1]) / 5;

c = tmp;

else

c = 0;

// Iterate through the digits and perform computation

for(j = 0; j < *len; j++)

tmp = (c*10 + i[j]) % 5;

i[j] = (c*10 + i[j]) / 5;

c = tmp;

// Recursive function to calculate factorial

char fact(char i[], int len)

char ans, c, d;
if(len == 1 &&i[0] < 5)

return ftr[(int)i[0]];

else

ans = ftr[(int)i[len-1]] * 6 % 10;

comp(i, &len);

d = (i[len-1] + ((len> 1) ? i[len-2] * 10 : 0)) & 0x03;

// Apply further calculations

for(c = 0; c < d; c++)

if(ans == 2 || ans == 6)

ans += 10;

ans /= 2;

return fact(i, len) * ans % 10;

int main()

char chr[1002];

int len, i;
char c;

printf("Input a positive number:\n");

scanf("%s", chr);

len = strlen(chr);

// Convert character digits to actual integers

for(i = 0; i<len; i++)

chr[i] -= '0';

// Calculate factorial and get the last non-zero digit

c = fact(chr, len);

printf("The last non-zero digit of the said factorial:\n");

putchar(c + '0');

putchar(10);

return 0;

Copy
Sample Output:
Input a positive number:
The last non-zero digit of the said factorial:
0

93. Write a C program to check if a given number is nearly prime


number or not.
Nearly prime numbers are a positive integer which is equal to the
product of two prime numbers.
Sample Output:
It is not a Nearly prime number.

C Code:

#include <stdio.h>

// Define the number of primes to generate

#define NUM_OF_PRIMES 3500

// Function to check if a number is prime

int is_prime(int num);

int main() {

int primes[NUM_OF_PRIMES], num_of_primes = 0;

// Initialize the list of primes with the first prime number

primes[num_of_primes++] = 2;

// Generate primes up to 1000000000

for(int num = 3; num * num<= 1000000000; num++) {

int flag = 1;

// Check if num is divisible by any previously generated


primes

for(int id = 0; id <num_of_primes; id++) {


if(num % primes[id] == 0) {

flag = 0;

break;

// If num is prime, add it to the list of primes

if(flag) primes[num_of_primes++] = num;

int N, num;

scanf("%d", &num);

int flag = 0;

// Check if num is a Nearly prime number

for(int j = 0; (j <num_of_primes) && (primes[j] * primes[j] <= num);


j++) {

if(num % primes[j] == 0) {

num /= primes[j];

flag = 1;

break;

// Check if the remaining number after division is also prime


if(flag &&is_prime(num))

printf("It is a Nearly prime number.\n");

else

printf("It is not a Nearly prime number.\n");

return 0;

// Function to check if a number is prime

int is_prime(int num) {

if(num != 2 &&num % 2 == 0)

return 0;

for(int factor = 3; factor * factor <= num ; factor += 2) {

if(num % factor == 0)

return 0;

return 1;

Copy
Sample Output:
It is not a Nearly prime number.
94. Write a C program to calculate body mass index and display
the grade.
Sample Output:
Input the weight: 65
Input the height: 5.6
BMI = 2.072704

Grade: Under

C Code:

#include <stdio.h>

// Function to calculate and display BMI

void BMI(int, float);

int main(void) {

int w; // Variable to store weight

float h; // Variable to store height

// Prompt user for weight and height

printf("Input the weight: ");

scanf("%d", &w);

printf("Input the height: ");

scanf("%f", &h);

// Call the BMI function with provided weight and height

BMI(w, h);
}

// Function to calculate and display BMI

void BMI(int weight, float height) {

// Calculate BMI using the provided formula

float temp = weight / (height * height);

// Display the calculated BMI

printf("BMI = %f\n", temp);

printf("\nGrade: ");

// Determine BMI grade and display it

temp< 18.5 ? printf("Under ") : temp < 25 ? printf("Normal ") : temp <
30 ? printf("Over ") : temp < 40 ? printf("Obese ") : printf("Error");

Copy
Sample Output:
Input the weight: 65
Input the height: 5.6
BMI = 2.072704

Grade: Under

95. Write a C program to print the corresponding Fahrenheit to


Celsius and Celsius to Fahrenheit.
Both cases initial tempratue = 00, maximum temperature =
1500 and step 100
Sample Output:
Celsius to Fahrenheit
---------------------
Celsius Fahrenheit
0.0 32.0
10.0 50.0
20.0 68.0
30.0 86.0
....
120.0 248.0
130.0 266.0
140.0 284.0
150.0 302.0

Fahrenheit to Celsius
---------------------
Fahrenheit Celsius
0.0 -17.8
10.0 -12.2
20.0 -6.7
30.0 -1.1
40.0 4.4
50.0 10.0
...
120.0 48.9
130.0 54.4
140.0 60.0
150.0 65.6

C Code:

#include <stdio.h>

int main() {

float f_temp, c_temp; // Variables to store Fahrenheit and Celsius


temperatures

float start_temp, end_temp; // Starting and ending temperatures for


the conversion

int STEP; // Step size for temperature increments


// Initialize temperature conversion settings

start_temp = 0;

end_temp = 150;

STEP = 10;

// Fahrenheit to Celsius conversion

printf("Fahrenheit to Celsius");

printf("\n---------------------\n");

printf("Fahrenheit Celsius\n");

// Loop through the range of Fahrenheit temperatures

while (start_temp<= end_temp) {

// Convert Fahrenheit to Celsius

f_temp = start_temp * 9 / 5 + 32;

// Print the conversion results

printf("%6.1f \t %8.1f\n", start_temp, f_temp);

// Increment the temperature by the specified step size

start_temp = start_temp + STEP;

// Reset temperature conversion settings for the second conversion

start_temp = 0;

end_temp = 150;
STEP = 10;

// Celsius to Fahrenheit conversion

printf("\n\nCelsius to Fahrenheit\n");

printf("---------------------\n");

printf("Celsius Fahrenheit\n");

// Loop through the range of Celsius temperatures

while (start_temp<= end_temp) {

// Convert Celsius to Fahrenheit

c_temp = (start_temp - 32) * 5 / 9;

// Print the conversion results

printf("%6.1f \t %8.1f\n", start_temp, c_temp);

// Increment the temperature by the specified step size

start_temp = start_temp + STEP;

Copy
Sample Output:
Celsius to Fahrenheit
---------------------
Celsius Fahrenheit
0.0 32.0
10.0 50.0
20.0 68.0
30.0 86.0
40.0 104.0
50.0 122.0
60.0 140.0
70.0 158.0
80.0 176.0
90.0 194.0
100.0 212.0
110.0 230.0
120.0 248.0
130.0 266.0
140.0 284.0
150.0 302.0

Fahrenheit to Celsius
---------------------
Fahrenheit Celsius
0.0 -17.8
10.0 -12.2
20.0 -6.7
30.0 -1.1
40.0 4.4
50.0 10.0
60.0 15.6
70.0 21.1
80.0 26.7
90.0 32.2
100.0 37.8
110.0 43.3
120.0 48.9
130.0 54.4
140.0 60.0
150.0 65.6

96. Write a C program to count blanks, tabs, and newlines in


input text.
Sample Output:
Number of blanks, tabs, and newlines:
Input few words/tab/newlines
The quick
brown fox jumps
over the lazy dog
^Z
blank=7,tab=2,newline=3
C Code:

#include <stdio.h>

int main() {

int blank_char, tab_char, new_line; // Variables to count blank


characters, tab characters, and newlines

blank_char = 0; // Initialize the count of blank characters

tab_char = 0; // Initialize the count of tab characters

new_line = 0; // Initialize the count of newlines

int c; // Variable to hold input characters

printf("Number of blanks, tabs, and newlines:\n");

printf("Input few words/tab/newlines\n");

// Loop to read characters until end-of-file (EOF) is encountered

for (; (c = getchar()) != EOF;) {

if (c == ' ') {

++blank_char; // Increment the count of blank characters

if (c == '\t') {

++tab_char; // Increment the count of tab characters

if (c == '\n') {

++new_line; // Increment the count of newlines

}
}

// Print the final counts of blanks, tabs, and newlines

printf("blank=%d,tab=%d,newline=%d\n", blank_char, tab_char,


new_line);

Copy
Sample Output:
Number of blanks, tabs, and newlines:
Input few words/tab/newlines
The quick
brown fox jumps
over the lazy dog
^Z
blank=7,tab=2,newline=3

97. Write a C program that accepts a string and counts the


number of characters, words and lines.
Sample Output:
Input a string and get number of charcters, words and lines:
The quick brown fox jumps over the lazy dog
^Z

Number of Characters = 44
Number of words = 9
Number of lines = 1

C Code:

#include <stdio.h>

int main() {

long ctr_char, ctr_word, ctr_line; // Variables to count characters,


words, and lines

int c; // Variable to hold input characters


int flag; // Flag to track word boundaries

ctr_char = 0; // Initialize the count of characters

flag = ctr_line = ctr_word = 0; // Initialize flag and counts for


words and lines

printf("Input a string and get number of characters, words and lines:\


n");

// Loop to read characters until end-of-file (EOF) is encountered

while ((c = getchar()) != EOF) {

++ctr_char; // Increment the count of characters

if (c == ' ' || c == '\t') {

flag = 0; // Reset the flag when a space or tab is encountered

} else if (c == '\n') {

++ctr_line; // Increment the count of lines

flag = 0; // Reset the flag on a newline

} else {

if (flag == 0) {

++ctr_word; // Increment the count of words when a new word


begins

flag = 1; // Set the flag to indicate a word is in progress

}
// Print the counts of characters, words, and lines

printf("\nNumber of Characters = %ld", ctr_char);

printf("\nNumber of words = %d", ctr_word);

printf("\nNumber of lines = %d", ctr_line);

Copy
Sample Output:
Input a string and get number of characters, words and lines:
The quick brown fox jumps over the lazy dog
^Z

Number of Characters = 44
Number of words = 9
Number of lines = 1

98. Write a C program that accepts some text from the user and
prints each word of that text on a separate line.
Sample Output:
Input some text:
The quick brown fox jumps over the lazy dog
The
quick
brown
fox
jumps
over
the
lazy
dog

C Code:

#include <stdio.h>

int main() {
long nc = 0; // Variable to count characters

int new_l = 0; // Variable to count newlines

int n_word = 0; // Variable to count words

int chr; // Variable to hold input characters

int flag = 0; // Flag to track word boundaries

int last = 0; // Flag to track the last character

printf("Input some text:\n");

while ((chr = getchar()) != EOF) {

++nc; // Increment the count of characters

if (chr == ' ' || chr == '\t') {

flag = 0; // Reset the flag when a space or tab is encountered

} else if (chr == '\n') {

++new_l; // Increment the count of newlines

flag = 0; // Reset the flag on a newline

} else {

if (flag == 0) {

++n_word; // Increment the count of words when a new word


begins

flag = 1; // Set the flag to indicate a word is in progress

}
if (flag == 0 && last == 0) {

printf("\n"); // Print a newline when a word ends and the last


character was not a space

last = 1; // Set last to 1 to indicate the last character was a


space

} else {

putchar(chr); // Print the character

last = 0; // Set last to 0 to indicate the last character was not


a space

Copy
Sample Output:
Input some text:
The quick brown fox jumps over the lazy dog
The
quick
brown
fox
jumps
over
the
lazy
dog

99. Write a C program that takes some integer values from the
user and prints a histogram.
Sample Output:
Input number of histogram bar (Maximum 10):
4
Input the values between 0 and 10 (separated by space):
9
7
4
3
Histogram:
#########
#######
####
###

C Code:

#include <stdio.h>

// Function to print a histogram

void print_Histogram ( int *hist, int n );

int main() {

int i, j;

int inputValue, hist_value=0;

// Prompt the user to input the number of histogram bars (Maximum


10)

printf("Input number of histogram bar (Maximum 10): \n");

scanf("%d", &inputValue);

int hist[inputValue];

if (inputValue<=10)

// Prompt the user to input values for the histogram bars

printf("Input the values between 0 and 10 (separated by space): \


n");

for (i = 0; i < inputValue; ++i) {


scanf("%d", &hist_value);

// Check if the input value is within the valid range (1 to 10)

if (hist_value>=1 && hist_value<=10)

hist[i] = hist_value;

hist_value=0;

int results[10] = {0};

// Count the occurrences of each value in the histogram

for(j = 0; j < inputValue; j++) {

if ( hist[j] == i){

results[i]++;

printf("\n");

// Print the histogram

print_Histogram(hist, inputValue);

return 0;

// Function to print the histogram

void print_Histogram(int *hist, int n) {

printf("\nHistogram:\n");
int i, j;

// Loop through the histogram bars and print '#' for each
occurrence

for (i = 0; i < n; i++) {

for ( j = 0; j < hist[i]; ++j) {

printf("#");

printf("\n");

Copy
Sample Output:
Input number of histogram bar (Maximum 10):
4
Input the values between 0 and 10 (separated by space):
9
7
4
3

Histogram:
#########
#######
####
###

100. Write a C program to convert a currency value (floating


point with two decimal places) to the number of coins and notes.
Sample Output:
Input the currency value (floating point with two decimal
places):
10357.75
Currency Notes:
100 number of Note(s): 103
50 number of Note(s): 1
5 number of Note(s): 1
2 number of Note(s): 1

Currency Coins:
.50 number of Coin(s): 1
.25 number of Coin(s): 1

C Code:

#include <stdio.h>

#include <math.h>

int main() {

double amt;

unsigned int int_amt, frac_amt;

// Prompt the user to input the currency value

printf("Input the currency value (floating point with two decimal


places):\n");

// Read the input value

scanf("%lf", &amt);

// Separate the integer part and fractional part

int_amt = (int) amt;

amt -= int_amt;

frac_amt = round((amt * 100));


// Display currency notes

printf("\nCurrency Notes:");

// Calculate and display 100 rupee notes

printf("\n100 number of Note(s): %d", int_amt / 100);

// Update the integer amount after deducting 100 rupee notes

int_amt -= (int_amt / 100) * 100;

// Check and display 50 rupee note

if (int_amt > 50) {

printf("\n50 number of Note(s): 1");

int_amt -= 50;

// Check and display 20 rupee notes

if (int_amt/20 > 0)

printf("\n20 number of Note(s): %d", int_amt / 20);

// Update the integer amount after deducting 20 rupee notes

int_amt -= (int_amt / 20) * 20;

// Check and display 10 rupee notes

if (int_amt/10 > 0)
printf("\n10 number of Note(s): %d", int_amt / 10);

// Update the integer amount after deducting 10 rupee notes

int_amt -= (int_amt / 10) * 10;

// Check and display 5 rupee notes

if (int_amt/5 > 0)

printf("\n5 number of Note(s): %d", int_amt / 5);

// Update the integer amount after deducting 5 rupee notes

int_amt -= (int_amt / 5) * 5;

// Check and display 2 rupee notes

if (int_amt > 0)

printf("\n2 number of Note(s): %d", int_amt / 2);

// Update the integer amount after deducting 2 rupee notes

int_amt -= (int_amt / 2) * 2;

// Check and display 1 rupee notes

if (int_amt > 0)

printf("\n1 number of Note(s): %d", int_amt);

// Display currency coins

printf("\n\nCurrency Coins:");
// Check and display 50 paise coins

if (frac_amt > 50) {

printf("\n.50 number of Coin(s): 1");

frac_amt -= 50;

// Check and display 25 paise coins

if (frac_amt/25 > 0)

printf("\n.25 number of Coin(s): %d", frac_amt / 25);

// Update the fractional amount after deducting 25 paise coins

frac_amt -= (frac_amt / 25) * 25;

// Check and display 10 paise coins

if (frac_amt/10 > 0)

printf("\n.10 number of Coin(s): %d", frac_amt / 10);

// Update the fractional amount after deducting 10 paise coins

frac_amt -= (frac_amt / 10) * 10;

// Check and display 5 paise coins

if (frac_amt/5 > 0)

printf("\n.05 number of Coin(s): %d", frac_amt / 5);


// Update the fractional amount after deducting 5 paise coins

frac_amt -= (frac_amt / 5) * 5;

// Check and display 1 paise coins

if (frac_amt > 0)

printf("\n.01 number of Coin(s): %d", frac_amt);

return 0;

Copy
Sample Output:
Input the currency value (floating point with two decimal
places):
10387.75

Currency Notes:
100 number of Note(s): 103
50 number of Note(s): 1
20 number of Note(s): 1
10 number of Note(s): 1
5 number of Note(s): 1
2 number of Note(s): 1

Currency Coins:
.50 number of Coin(s): 1
.25 number of Coin(s): 1

101. There are three given ranges. Write a C program that reads
a floating-point number and finds the range where it belongs from
four given ranges.
Sample Output:
Input a number: 87
Range (80,100]

C Code:
#include <stdio.h>

int main ()

// Declare a variable "x" to hold the input number

float x = 0;

// Prompt the user to input a number

printf("Input a number: ");

// Read the input number

scanf("%f", &x);

// Check the range of the input number and print the corresponding
message

if (x >= 0 && x <= 30)

printf("Range [0,30]\n");

else if (x > 30 && x <= 50)

printf("Range (30,50]\n");

else if (x > 50 && x <= 80)

printf("Range (50,80]\n");

else if (x > 80 && x <= 100)

printf("Range (80,100]\n");

else

printf("\nNot within range..!\n");


}

Copy
Sample Output:
Input a number: 87
Range (80,100]

102. Write a C program that reads three integers and sorts the
numbers in ascending order. Print the original numbers and the
sorted numbers.
Sample Output:
Input 3 integers: 17
-5
25

---------------------------
Original numbers: 17, -5, 25
Sorted numbers: -5, 17, 25

C Code:

#include <stdio.h>

#include <math.h>

int main (){

// Declare three integer variables

int x, y, z;

// Prompt the user to input three integers

printf("Input 3 integers: ");

// Read the input values for x, y, and z

scanf("%d %d %d", &x, &y, &z);


// Print a separator line for clarity

printf("\n---------------------------\n");

// Display the original input numbers

printf("Original numbers: %d, %d, %d", x, y, z);

// Display the sorted numbers

printf("\nSorted numbers: ");

// Nested if-else statements to sort and print the numbers

if (x <= y && y <= z){

printf("%d, %d, %d", x, y, z);

else{

if (x <= z && z <= y){

printf("%d, %d, %d", x, z, y);

else{

if (y <= x && x <= z){

printf("%d, %d, %d", y, x, z);

else{

if (y <= z && z <= x){

printf("%d, %d, %d", y, z, x);


}

else{

if (z <= x && x <= y){

printf("%d, %d, %d", z, x, y);

else{

if (x == y && y == z){

printf("%d, %d, %d", x, y, z);

else{

printf("%d, %d, %d", z, y, x);

Copy
Sample Output:
Input 3 integers: 17
-5
25

---------------------------
Original numbers: 17, -5, 25
Sorted numbers: -5, 17, 25
103. Write a C program that takes two integers and tests
whether they are multiplied or not.
In science, a multiple is the product of any quantity and an
integer. In other words, for the quantities a and b, we say that b
is a multiple of a if b = na for some integer n, which is called the
multiplier. If a is not zero, this is equivalent to saying that b/a is
an integer.
Sample Output:
Input two integers:
3
9
Multiplies

C Code:

#include <stdio.h>

int main () {

// Declare unsigned short integer variables x, y, and multi

unsigned short int x, y, multi;

// Prompt the user to input two integers

printf("Input two integers: \n");

// Read the input values for x and y

scanf("%hd %hd", &x, &y);

// Check if x is greater than y

if (x > y){
// Calculate the remainder when x is divided by y

multi = x % y;

// Check if the remainder is zero

if ( multi == 0){

printf("Multiplies\n");

else{

printf("Not Multiplies\n");

else{

// Calculate the remainder when y is divided by x

multi = y % x;

// Check if the remainder is zero

if (multi == 0){

printf("Multiplies\n");

else{

printf("Not Multiplies\n");

Copy
Sample Output:
Input two integers:
3
9
Multiplies

104. Write a C program that reads the item's price and creates a
revised price for the item, based on the item price table.
Sample Output:
Input the item price:525
New Item price: 582.75
Increased price: 57.75
Increase Percentage: 11%

C Code:

#include <stdio.h>

int main ()

// Declare variables for item price and increased price

float price, increased_price;

// Prompt the user to input the item price

printf("Input the item price:");

// Read the input value for item price

scanf("%f", &price);

// Check the range of the item price and calculate increased price
and percentage accordingly

if (price >= 100 && price <= 400){


// Calculate increased price and update item price

increased_price = price * 0.14;

price = price + increased_price;

// Print the new item price, increased price, and increase


percentage

printf("New Item price: %.2f\n", price);

printf("Increased price: %.2f\n", increased_price);

printf("Increase Percentage: 14%%\n");

else{

if (price > 400 && price <= 800){

increased_price = price * 0.11;

price = price + increased_price;

printf("New Item price: %.2f\n", price);

printf("Increased price: %.2f\n", increased_price);

printf("Increase Percentage: 11%%\n");

else{

if (price > 800 && price <= 1200){


increased_price = price * 0.09;

price = price + increased_price;

printf("New Item price: %.2f\n", price);

printf("Increased price: %.2f\n", increased_price);

printf("Increase Percentage: 9%%\n");

else{

if (price > 1200 && price <= 2000){

increased_price = price * 0.06;

price = price + increased_price;

printf("New Item price: %.2f\n", price);

printf("Increased price: %.2f\n",


increased_price);

printf("Increase Percentage: 6%%\n");

else{

increased_price = price * 0.03;

price = price + increased_price;

printf("New Item price: %.2f\n", price);


printf("Increased price: %.2f\n",
increased_price);

printf("Increase Percentage: 3%%\n");

Copy
Sample Output:
Input the item price:525
New Item price: 582.75
Increased price: 57.75
Increase Percentage: 11%

105. Write a C program that accepts seven floating point


numbers and counts the number of positive and negative
numbers. Print the average of all positive and negative values
with two digits after the decimal number.
Sample Output:
Input 7 numbers(int/float):
25
35.75
15
-3.5
40
35
16

6 Number of positive numbers: Average 27.79

1 Number of negative numbers: Average -3.50

C Code:

#include <stdio.h>
int main () {

float x, p_avg = 0, n_avg = 0, temp_p = 0, temp_n = 0;

int i, p_ctr = 0, n_ctr = 0;

// Prompt the user to input 7 numbers

printf("Input 7 numbers(int/float):\n");

// Loop through 7 times to read the numbers

for (i = 0; i < 7; i++){

// Read a number

scanf("%f", &x);

// Check if the number is positive

if (x > 0){

p_ctr++; // Increment positive counter

temp_p += x; // Sum positive numbers

// Check if the number is negative

if (x < 0){

n_ctr++; // Increment negative counter

temp_n += x; // Sum negative numbers

}
}

// Calculate the average of positive numbers

p_avg = temp_p/p_ctr;

// Calculate the average of negative numbers

n_avg = temp_n/n_ctr;

// Check if there were positive numbers

if (p_ctr > 0){

printf("\n%d Number of positive numbers: ", p_ctr);

printf("Average %.2f\n", p_avg);

// Check if there were negative numbers

if (n_ctr > 0){

printf("\n%d Number of negative numbers: ", n_ctr);

printf("Average %.2f\n", n_avg);

Copy
Sample Output:
Input 7 numbers(int/float):
25
35.75
15
-3.5
40
35
16

6 Number of positive numbers: Average 27.79

1 Number of negative numbers: Average -3.50

106. Write a C program that accepts 7 integer values and counts


the even, odd, positive and negative values.
Sample Output:

Input 7 integers:
10
12
15
-15
26
35
17

Number of even values: 3


Number of odd values: 4
Number of positive values: 6
Number of negative values: 1

C Code:

#include <stdio.h>

int main ()

// Declare variables for input, counters for even, odd, positive,


and negative numbers

int x, i, ctr_even = 0, ctr_odd = 0, ctr_positive = 0,


ctr_negative = 0;

// Prompt the user to input 7 integers


printf("\nInput 7 integers:\n");

// Loop through 7 times to read the numbers

for (i = 0; i < 7; i++){

// Read an integer

scanf("%d", &x);

// Check if the number is positive

if (x > 0){

ctr_positive++; // Increment positive counter

// Check if the number is negative

if (x < 0){

ctr_negative++; // Increment negative counter

// Check if the number is even

if (x % 2 == 0){

ctr_even++; // Increment even counter

// Check if the number is odd

if (x % 2 != 0){
ctr_odd++; // Increment odd counter

// Print the counts of even, odd, positive, and negative numbers

printf("\nNumber of even values: %d", ctr_even);

printf("\nNumber of odd values: %d", ctr_odd);

printf("\nNumber of positive values: %d", ctr_positive);

printf("\nNumber of negative values: %d", ctr_negative);

Copy
Sample Output:
Input 7 integers:
10
12
15
-15
26
35
17

Number of even values: 3


Number of odd values: 4
Number of positive values: 6
Number of negative values: 1

107. Write a C program that prints ten consecutive odd and even
numbers after accepting an integer.
Sample Output:
Input an integer number:
15

Next 10 consecutive odd numbers:


17, 19, 21, 23, 25, 27, 29, 31, 33, 35,
Next 10 consecutive even numbers:
26, 28, 30, 32, 34, 36, 38, 40, 42, 44,

C Code:

#include <stdio.h>

int main () {

int a, i, ctr = 0;

// Prompt the user to input an integer number

printf("Input an integer number:\n");

scanf("%d", &a);

// Print the next 10 consecutive odd numbers

printf("\nNext 10 consecutive odd numbers:\n");

for (i = a + 1; ctr < 10; i++){

if (i % 2 != 0){

printf("%d, ", i);

ctr++;

}
// Reset counter for even numbers

ctr = 0;

// Print the next 10 consecutive even numbers

printf("\n\nNext 10 consecutive even numbers:\n");

for (i = a + 1; ctr < 10; i++){

if (i % 2 == 0){

printf("%d, ", i);

ctr++;

Copy
Sample Output:
Input an integer number:
15

Next 10 consecutive odd numbers:


17, 19, 21, 23, 25, 27, 29, 31, 33, 35,

Next 10 consecutive even numbers:


26, 28, 30, 32, 34, 36, 38, 40, 42, 44,

108. Write a C program that reads two integer values and


calculates the sum of all odd numbers between them.
Sample Output:
Input the first integer number:
25
Input the second integer number (greater than first integer):
45
Sum of all odd values between 25 and 45:
385
Sum of all even values between 25 and 45:
350

C Code:

#include <stdio.h>

int main () {

// Declare variables for input, counters, and sum of odd and even
numbers

int a, b, i, ctr = 0, sum_odd = 0, sum_even = 0;

// Prompt the user to input the first integer number

printf("Input the first integer number:\n");

scanf("%d", &a);

// Prompt the user to input the second integer number (greater


than the first integer)

printf("Input the second integer number (greater than first


integer):\n");

scanf("%d", &b);

// Check if b is greater than a

if (b > a)

// Calculate the sum of all odd values between a and b


for (i = a; i <= b; i++){

if (i % 2 != 0){

sum_odd = sum_odd + i;

// Print the sum of all odd values

printf("Sum of all odd values between %d and %d:", a, b);

printf("\n%d", sum_odd);

// Reset counter

ctr = 0;

// Calculate the sum of all even values between a and b

for (i = a; i <= b; i++){

if (i % 2 == 0){

sum_even = sum_even + i;

// Print the sum of all even values

printf("\nSum of all even values between %d and %d:", a, b);

printf("\n%d", sum_even);

}
}

Copy
Sample Output:
Input the first integer number:
25
Input the second integer number (greater than first integer):
45
Sum of all odd values between 25 and 45:
385
Sum of all even values between 25 and 45:
350

109. Write a C program to find and print the square of each even
and odd value between 1 and a given number (4 < n < 101).
Sample Output:
Input a number(integer): 15

Square of each even between 1 and 15:


2^2 = 4
4^2 = 16
6^2 = 36
8^2 = 64
10^2 = 100
12^2 = 144
14^2 = 196

Square of each odd between 1 and 15:


1^2 = 1
3^2 = 9
5^2 = 25
7^2 = 49
9^2 = 81
11^2 = 121
13^2 = 169
15^2 = 225

C Code:

#include <stdio.h>

#include <math.h>
int main () {

int x, cont = 0, i;

// Prompt the user to input a number

printf("Input a number(integer): ");

scanf("%d", &x);

// Check if x is between 5 and 100

if (x >= 5 && x <= 100)

// Print the squares of even numbers between 1 and x

printf("\nSquare of each even between 1 and %d:\n",x);

for (i = 1; i <= x; i++){

if (i % 2 == 0){

cont = pow(i, 2);

printf("%d^2 = %d\n", i, cont);

// Print the squares of odd numbers between 1 and x

printf("\nSquare of each odd between 1 and %d:\n",x);

for (i = 1; i <= x; i++){

if (i % 2 != 0){
cont = pow(i, 2);

printf("%d^2 = %d\n", i, cont);

Copy
Sample Output:
Input a number(integer): 15

Square of each even between 1 and 15:


2^2 = 4
4^2 = 16
6^2 = 36
8^2 = 64
10^2 = 100
12^2 = 144
14^2 = 196

Square of each odd between 1 and 15:


1^2 = 1
3^2 = 9
5^2 = 25
7^2 = 49
9^2 = 81
11^2 = 121
13^2 = 169
15^2 = 225

110. Write a C program to find the odd, even, positive and


negative numbers from a given number (integer) and print a
message 'Number is positive odd' or 'Number is negative odd' or
'Number is positive even' or 'Number is negative even'. If the
number is 0 print "Zero".
Sample Output:
Input a number (integer):
12
Number is positive-even

C Code:

#include <stdio.h>

int main () {

int b;

// Prompt the user to input a number (integer)

printf("Input a number (integer):\n");

// Read the input number

scanf("%d", &b);

// Check if the number is positive and even

if ((b % 2 == 0) && b > 0){

printf("Number is positive-even\n");

else{

// Check if the number is negative and even

if ((b % 2 == 0) && b < 0){

printf("Number is negative-even'\n");

else{

// Check if the number is positive and odd

if ((b % 2 !=0) && b > 0){


printf("Number is positive-odd\n");

else{

// Check if the number is negative and odd

if ((b % 2 != 0) && b < 0){

printf("Number is negative-odd\n");

else{

// If none of the above conditions are met, it


must be zero

printf("Zero\n");

Copy
Sample Output:
Input a number (integer):
12
Number is positive-even

111. Write a C program that accepts an integer from the user


and divides all numbers between 1 and 100. Print those numbers
where the remainder value is 3.
Sample Output:
Input a number (integer):
65
Remainder value is 3 after divide all numbers between 1 and 100
by 65:
3
68

C Code:

#include <stdio.h>

int main () {

// Declare variables

int x, i, y;

// Prompt user for input

printf("Input a number (integer):\n");

// Read an integer from user and store it in 'x'

scanf("%d", &x);

// Print a message about the remainder condition

printf("\nRemainder value is 3 after divide all numbers between 1


and 100 by %d:\n", x);

// Loop to check for remainder condition

for (i = 1; i <= 100; i++){

if (i % x == 3){

printf("%d\n", i);

}
return 0; // End of program

Copy
Sample Output:
Input a number (integer):
65

Remainder value is 3 after divide all numbers between 1 and 100


by 65:
3
68

112. Write a C program that reads seven integer values from the
user and finds the highest value and its position.
Sample Output:
Input 6 numbers (integer values):
15
20
25
17
-8
35

Maximum value: 35
Position: 6

C Code:

#include <stdio.h>

int main () {

// Declare variables

int x, i, n = 0, temp_num = 0, position = 0;


// Prompt user for input

printf("Input 6 numbers (integer values):\n");

// Loop to read and process 6 numbers

for (i = 1; i < 7; i++){

// Read an integer from user and store it in 'x'

scanf("%d", &x);

n = x; // Assign 'x' to 'n'

// Check if 'n' is greater than or equal to 'temp_num'

if (n >= temp_num){

temp_num = n; // Update 'temp_num' with the new maximum


value

position = i; // Update 'position' with the current


position

// Print the maximum value and its position

printf("\nMaximum value: %d\n", temp_num);

printf("Position: %d", position);

return 0; // End of program

}
Copy
Sample Output:
Input 6 numbers (integer values):
15
20
25
17
-8
35

Maximum value: 35
Position: 6

113. Write a C program to create and print the sequence of the


following example.
Sample Output:
a=1 b=100
a=6 b=90
a=11 b=80
a=16 b=70
a=21 b=60
a=26 b=50
a=31 b=40
a=36 b=30
a=41 b=20
a=46 b=10
a=51 b=0

C Code:

#include <stdio.h>

int main ()

int a, b;

// Loop to execute statements with changing values of 'a' and 'b'

for (a = 1, b = 100; b >= 0; a += 5, b -= 10)


printf("a=%d \t b=%d\n", a, b);

Copy
Sample Output:
a=1 b=100
a=6 b=90
a=11 b=80
a=16 b=70
a=21 b=60
a=26 b=50
a=31 b=40
a=36 b=30
a=41 b=20
a=46 b=10
a=51 b=0

114. Write a C program that accepts two integer values and


calculates the sum of all even values between them.
Sample Output:
Input two numbers (integer values):
25
45

Sum of all even values between 25 and 45


350
Sample Output:
Input two numbers (integer values):
27
13

Sum of all even values between 27 and 13


140

C Code:

#include <stdio.h>

int main () {
int y, i, z;

int l, m, n, ctr1 = 0, ctr2 = 0;

// Prompt user for input

printf("Input two numbers (integer values):\n");

// Read two integer values from user and store them in 'm' and 'n'

scanf("%d %d", &m, &n);

ctr1 = 0; // Reset counter 1

printf("\nSum of all even values between %d and %d\n", m, n);

// Check if 'm' is greater than 'n'

if (m > n) {

// Loop to find and sum all even numbers between 'n' and 'm'

for (l = n + 1; l < m; l++){

if (l % 2 == 0){

ctr1 += l; // Accumulate even numbers in counter 1

printf("%d\n", ctr1); // Print the sum of even numbers

else {

// Loop to find and sum all even numbers between 'm' and 'n'

for (l = m + 1; l < n; l++){


if (l % 2 == 0){

ctr2 += l; // Accumulate even numbers in counter 2

printf("%d\n", ctr2); // Print the sum of even numbers

return 0; // End of program

Copy
Sample Output:
Input two numbers (integer values):
25
45

Sum of all even values between 25 and 45


350
Sample Output:
Input two numbers (integer values):
27
13

Sum of all even values between 27 and 13


140

115. Write a C program that accepts a pair of numbers from the


user and prints the sequence from the lowest to the highest
number. Also, print the average value of the sequence.

Sample Output:
Input two pairs values (integer values):
14
25
Sequence from the lowest to highest number:
14 15 16 17 18 19 20 21 22 23 24 25
Average value of the said sequence
19.50
Sample Output:
Input two pairs values (integer values):
35
13

Sequence from the lowest to highest number:


13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
35
Average value of the said sequence
24.00

C Code:

#include <stdio.h>

int main () {

int p, x = 1, y = 1, i = 0, temp = 0;

float sum_val = 0;

// Prompt user for input

printf("Input two pairs values (integer values):\n");

// Read two integer values from user and store them in 'x' and 'y'

scanf("%d %d", &x, &y);

// Check if both 'x' and 'y' are positive

if (x > 0 && y > 0) {

// Swap 'x' and 'y' if 'y' is smaller than 'x'


if (y < x) {

temp = x;

x = y;

y = temp;

printf("\nSequence from the lowest to highest number:\n");

// Loop to print and accumulate values from 'x' to 'y'

for (p= 0, i = x; i <= y; i++) {

sum_val += i; // Accumulate the values for average


calculation

printf("%d ", i);

p++;

// Print the average value of the sequence

printf("\nAverage value of the said sequence\n%9.2f", sum_val


/ p);

return 0; // End of program

Copy
Sample Output:
Input two pairs values (integer values):
14
25
Sequence from the lowest to highest number:
14 15 16 17 18 19 20 21 22 23 24 25
Average value of the said sequence
19.50
Sample Output:
Input two pairs values (integer values):
35
13

Sequence from the lowest to highest number:


13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
35
Average value of the said sequence
24.00

116. Write a C program that accepts a pair of numbers from the


user and prints "Ascending order" if the two numbers are in
ascending order, otherwise prints, "Descending order".

Sample Output:
Input two pairs values (integer values):
12
35
Ascending order
Sample Output:
Input two pairs values (integer values):
65
25
Descending order

C Code:

#include <stdio.h>

int main () {

int a, b;
// Prompt user for input

printf("Input two pairs values (integer values):\n");

// Read two integer values from user and store them in 'a' and 'b'

scanf("%d %d", &a, &b);

// Check if 'a' is not equal to 'b'

if (a != b) {

// Check if 'b' is greater than 'a'

if (b > a) {

printf("Ascending order\n"); // Print message for


ascending order

else {

printf("Descending order\n"); // Print message for


descending order

return 0; // End of program

Copy
Sample Output:
Input two pairs values (integer values):
12
35
Ascending order
Sample Output:
Input two pairs values (integer values):
65
25
Descending order

117. Write a C program that reads two integers and divides the
first number by second, print the result of this division with two
digits after the decimal point and prints “Division not possible..!”
if the division is not possible.

Sample Output:
Input two integer values:
75
5
Result: 15.00

C Code:

#include <stdio.h>

int main () {

int n, x, y, i;

float result = 0;

// Prompt user for input

printf("Input two integer values:\n");

// Read two integer values from user and store them in 'x' and 'y'

scanf("%d %d", &x, &y);


// Check if 'y' is zero (division by zero case)

if (y == 0) {

printf("Division not possible..!\n"); // Print an error


message

else {

// Calculate the result of division as a float value

result = (x * 1.0) / (y);

// Print the result with two decimal places

printf("Result: %.2f\n", result);

return 0; // End of program

Copy
Sample Output:
Input two integer values:
75
5
Result: 15.00

118. Write a C program that reads five subject marks (0-100) of a


student and calculates the average of these marks.

Sample Output:
Input five subject marks(0-100):
75
84
56
98
68
Average marks = 76.20

C Code:

#include <stdio.h>

int main () {

float marks, tot_marks = 0;

int i = 0, subject = 0;

// Prompt user for input

printf("Input five subject marks(0-100):\n");

// Loop to read marks for five subjects

while (subject != 5) {

// Read a float value 'marks' from user

scanf("%f", &marks);

// Check if 'marks' is within valid range (0-100)

if (marks < 0 || marks > 100) {

printf("Not a valid marks\n"); // Print an error message

else {

tot_marks += marks; // Accumulate valid marks

subject++; // Increment subject count


}

// Calculate and print the average marks

printf("Average marks = %.2f\n", tot_marks/5);

return 0; // End of program

Copy
Sample Output:
Input five subject marks(0-100):
75
84
56
98
68
Average marks = 76.20

119. Write a C program to calculate the sum of all numbers


between two given numbers (inclusive) not divisible by 7.

Sample Output:
Input two numbers(integer):
25
5
Sum of all numbers between said numbers (inclusive) not divisible
by 7:
273
Sample Output:
Input two numbers(integer):
6
36
Sum of all numbers between said numbers (inclusive) not divisible
by 7:
546

C Code:

#include <stdio.h>

int main () {

int a, b, sum_nums = 0, i, temp = 0;

// Prompt user for input

printf("Input two numbers(integer):\n");

// Read two integer values from user and store them in 'a' and 'b'

scanf("%d %d", &a, &b);

// Swap 'a' and 'b' if 'b' is smaller than 'a'

if (b < a) {

temp = a;

a = b;

b = temp;

// Loop through the range from 'a' to 'b' (inclusive)

for (i = a; i <= b; i++) {

// Check if 'i' is not divisible by 7

if (i % 7 != 0) {

sum_nums += i; // Accumulate numbers not divisible by 7


}

// Print the sum of numbers not divisible by 7

printf("Sum of all numbers between said numbers (inclusive) not


divisible by 7:\n");

printf("%d\n", sum_nums);

return 0; // End of program

Copy
Sample Output:
Input two numbers(integer):
25
5
Sum of all numbers between said numbers (inclusive) not divisible
by 7:
273
Sample Output:
Input two numbers(integer):
6
36
Sum of all numbers between said numbers (inclusive) not divisible
by 7:
546

120. Write a C program to print a sequence from 1 to a given


(integer) number, inserting a comma between these numbers.
There will be no comma after the last character.

Sample Output:
Input a number(integer):
25
Sequence:
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25

C Code:

#include <stdio.h>

int main () {

int n, i;

// Prompt user for input

printf("\nInput a number(integer):\n");

// Read an integer value 'n' from user

scanf("%d", &n);

// Check if 'n' is positive

if (n > 0) {

printf("Sequence:\n");

// Loop to print numbers from 1 to 'n-1'

for (i = 1; i < n; i++) {

printf("%d,", i); // Print each number followed by a comma

printf("%d\n", i); // Print the last number without a comma


}

Copy
Sample Output:
Input a number(integer):
25
Sequence:
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25

121. Write a C program that reads an integer and finds all the
divisors of the said integer.

Sample Output:
Input a number (integer value):
35

All positive divisors of 35


1
5
7
35

C Code:

#include <stdio.h>

int main () {

int i, n;

// Prompt user for input

printf("Input a number (integer value):\n");

// Read an integer value 'n' from user

scanf("%d", &n);
// Print a message indicating what the program will do

printf("\nAll positive divisors of %d \n",n);

// Loop through numbers from 1 to 'n'

for (i = 1; i <= n; i++) {

// Check if 'i' is a divisor of 'n'

if (n % i == 0) {

printf("%d\n", i); // Print 'i' if it is a divisor of 'n'

return 0; // End of program

Copy
Sample Output:
Input a number (integer value):
35

All positive divisors of 35


1
5
7
35

122. Write a C program that reads two integers m, n and


computes the sum of n even numbers starting from m.

Sample Output:
Input two integes (m, n):
20
60

Sum of 60 even numbers starting from 20:


4740

C Code:

#include <stdio.h>

int main () {

int m, n, i, j, k, sum_even_nums = 0;

// Prompt user for input

printf("\nInput two integers (m, n):\n");

// Read two integer values 'm' and 'n' from user

scanf("%d %d", &m, &n);

// Print a message indicating what the program will do

printf("\nSum of %d even numbers starting from %d: ",n,m);

// Loop to find and sum 'n' even numbers starting from 'm'

for (k = 0, j = m; k < n; j++) {

// Check if 'j' is even

if (j % 2 == 0) {

sum_even_nums += j; // Accumulate even numbers


k++; // Increment the count of even numbers found

// Print the sum of even numbers

printf("\n%d", sum_even_nums);

return 0; // End of program

Copy
Sample Output:
Input two integes (m, n):
20
60

Sum of 60 even numbers starting from 20:


4740

C Code:

#include <stdio.h>

int main () {

int m, n, i, j, k, sum_even_nums = 0;

// Prompt user for input

printf("\nInput two integers (m, n):\n");

// Read two integer values 'm' and 'n' from user


scanf("%d %d", &m, &n);

// Print a message indicating what the program will do

printf("\nSum of %d even numbers starting from %d: ",n,m);

// Loop to find and sum 'n' even numbers starting from 'm'

for (k = 0, j = m; k < n; j++) {

// Check if 'j' is even

if (j % 2 == 0) {

sum_even_nums += j; // Accumulate even numbers

k++; // Increment the count of even numbers found

// Print the sum of even numbers

printf("\n%d", sum_even_nums);

return 0; // End of program

Copy
Sample Output:
Input two integes (m, n):
20
60

Sum of 60 even numbers starting from 20:


4740

123. Write a C program that reads two integers m, n and


computes the sum of n odd numbers starting from m.

Sample Output:
Input two integes (m, n):
65
5

Sum of 5 odd numbers starting from 65:


345

124. Write a C program that reads an array of integers (length 7),


replaces every negative or null element with 1 and prints the
array elements.

Sample Output:
Input 7 array elements:
15
12
-7
25
0
27
53

Array elements:
array_nums[0] = 15
array_nums[1] = 12
array_nums[2] = 1
array_nums[3] = 25
array_nums[4] = 1
array_nums[5] = 27
array_nums[6] = 53

C Code:

#include <stdio.h>

int main () {
int array_nums[7], i, n;

// Prompt user for input

printf("Input 7 array elements:\n");

// Loop to read 7 integer values from the user and store them in
the array

for (i = 0; i < 7; i++) {

scanf("%d", &n);

array_nums[i] = n;

// Print a message indicating the array elements will be displayed

printf("\nArray elements:\n");

// Loop to print each element of the array

for (i = 0; i < 7; i++) {

// Check if the element is less than or equal to 0

if (array_nums[i] <= 0) {

array_nums[i] = 1; // Set the element to 1 if it's less


than or equal to 0

// Print the array element and its value

printf("array_nums[%d] = %d\n", i, array_nums[i]);


}

return 0; // End of program

Copy
Sample Output:
Input 7 array elements:
15
12
-7
25
0
27
53

Array elements:
array_nums[0] = 15
array_nums[1] = 12
array_nums[2] = 1
array_nums[3] = 25
array_nums[4] = 1
array_nums[5] = 27
array_nums[6] = 53
125. Write a C program that reads an array of integers (length 7),
and replaces the first element of the array by a given number and
replaces each subsequent position of the array by the double
value of the previous.

Sample Output:
Input the first element of the array:
5

Array elements:
array_nums[0] = 5
array_nums[1] = 10
array_nums[2] = 20
array_nums[3] = 40
array_nums[4] = 80
array_nums[5] = 160
array_nums[6] = 320
C Code:

#include <stdio.h>

int main () {

int array_nums[7], i, x, k;

// Prompt user for the first element of the array

printf("Input the first element of the array:\n");

scanf("%d", &x);

// Loop to generate array elements by doubling 'x' in each


iteration

for (k = 0, i = x; k < 7; i *= 2, k++) {

array_nums[k] = i; // Assign the calculated value to the array

// Print a message indicating the array elements will be displayed

printf("\nArray elements:\n");

// Loop to print each element of the array

for (i = 0; i < 7; i++) {

printf("array_nums[%d] = %d\n", i, array_nums[i]);

return 0; // End of program


}

Copy
Sample Output:
Input the first element of the array:
5

Array elements:
array_nums[0] = 5
array_nums[1] = 10
array_nums[2] = 20
array_nums[3] = 40
array_nums[4] = 80
array_nums[5] = 160
array_nums[6] = 320

126. Write a C program that reads an array (length 7) and prints


all array positions that store a value less than or equal to 0.

Sample Output:
Input 7 array elements:
15
23
37
65
20
-7
65

Array positions that store a value less or equal to 0:


array_nums[5] = -7.0

C Code:

#include <stdio.h>

int main () {

float n, array_nums[7];

int i;
// Prompt user for input

printf("Input 7 array elements:\n");

// Loop to read 7 float values from the user and store them in the
array

for (i = 0; i < 7; i++) {

scanf("%f", &n);

array_nums[i] = n;

// Print a message indicating the positions with values less than


or equal to 0

printf("\nArray positions that store a value less or equal to 0:\


n");

// Loop to check and print positions with values less than or


equal to 0

for (i = 0; i < 7; i++) {

if (array_nums[i] <= 0) {

printf("array_nums[%d] = %.1f\n", i, array_nums[i]);

return 0; // End of program

Sample Output:
Input 7 array elements:
15
23
37
65
20
-7
65

Array positions that store a value less or equal to 0:


array_nums[5] = -7.0

127. Write a C program that reads an array of integers (length 8),


replaces the 1st element with the 8th, the 2nd with the 7th and so
on. Print the final array.

Sample Output:
Input 8 array elements:
25
35
17
-5
29
45
60
65

Modified array:
array_nums[0] = 65
array_nums[1] = 60
array_nums[2] = 45
array_nums[3] = 29
array_nums[4] = -5
array_nums[5] = 17
array_nums[6] = 35
array_nums[7] = 25

C Code:

#include <stdio.h>

int main () {

unsigned short i, j; // Declare variables for looping


short array_nums[8], n, temp1, temp2; // Declare array and
temporary variables

// Prompt user for input

printf("Input 8 array elements:\n");

// Loop to read 8 short values from the user and store them in the
array

for (i = 0; i < 8; i++) {

scanf("%hd", &n);

array_nums[i] = n;

// Loop to swap elements from the first half of the array with the
second half

for (i = 0, j = 7; i <= 4 && j >= 4; i++, j--) {

temp1 = array_nums[i];

temp2 = array_nums[j];

array_nums[i] = temp2;

array_nums[j] = temp1;

// Print modified array

printf("\nModified array:\n");

for (i = 0; i < 8; i++)

printf("array_nums[%d] = %d\n", i, array_nums[i]);


return 0; // End of program

Copy
Sample Output:
Input 8 array elements:
25
35
17
-5
29
45
60
65

Modified array:
array_nums[0] = 65
array_nums[1] = 60
array_nums[2] = 45
array_nums[3] = 29
array_nums[4] = -5
array_nums[5] = 17
array_nums[6] = 35
array_nums[7] = 25

128. Write a C program that reads an array of integers (length


10), fills it with numbers from o to a (given number) n – 1
repeatedly, where 2 ≤ n ≤ 10.

Sample Output:
Input an integer (2-10)
8
array_nums[0] = 0
array_nums[1] = 1
array_nums[2] = 2
array_nums[3] = 3
array_nums[4] = 4
array_nums[5] = 5
array_nums[6] = 6
array_nums[7] = 7
array_nums[8] = 0
array_nums[9] = 1

C Code:

#include <stdio.h>

int main ()

int n, i, array_nums[10], k;

// Prompt user for input

printf("Input an integer (2-10)\n");

scanf("%d", &n);

if (n >= 2 && n <= 10)

k = 0;

// Loop to fill array with sequential numbers, starting from 0

for (i = 0; i < 10; i++)

array_nums[i] = k;

k++;

if (k == n)

k = 0;

}
}

// Loop to print array elements

for (i = 0; i < 10; i++)

printf("array_nums[%d] = %d\n", i, array_nums[i]);

return 0; // End of program

Copy
Sample Output:
Input an integer (2-10)
8
array_nums[0] = 0
array_nums[1] = 1
array_nums[2] = 2
array_nums[3] = 3
array_nums[4] = 4
array_nums[5] = 5
array_nums[6] = 6
array_nums[7] = 7
array_nums[8] = 0
array_nums[9] = 1

129. Write a C program that reads an array (length 10), and


replaces the first element of the array by a given number and
replaces each subsequent position of the array by one-third the
value of the previous.

Sample Output:
Input an integer (2-10)
8
array_nums[0] = 0
array_nums[1] = 1
array_nums[2] = 2
array_nums[3] = 3
array_nums[4] = 4
array_nums[5] = 5
array_nums[6] = 6
array_nums[7] = 7
array_nums[8] = 0
array_nums[9] = 1

C Code:

#include <stdio.h>

int main ()

int i;

double array_nums[10];

double n;

// Prompt user for input

printf("Input a number:\n");

scanf("%lf", &n);

// Initialize the first element of the array with the input value

array_nums[0] = n;

// Loop to generate and store subsequent array elements

for (i = 1; i < 10; i++)

n = n / 3; // Divide the current value by 3


array_nums[i] = n; // Store the result in the array

// Print the array elements

printf("\nArray elements:\n");

for (i = 0; i < 10; i++)

printf("array_nums[%d] = %.4lf\n", i, array_nums[i]);

return 0; // End of program

Copy
Sample Output:
Input a number:
35

Array elements:
array_nums[0] = 35.0000
array_nums[1] = 11.6667
array_nums[2] = 3.8889
array_nums[3] = 1.2963
array_nums[4] = 0.4321
array_nums[5] = 0.1440
array_nums[6] = 0.0480
array_nums[7] = 0.0160
array_nums[8] = 0.0053
array_nums[9] = 0.0018

130. Write a C program to create an array of length n and fill the


array elements with integer values. Find the smallest value and
its position in the array.

Sample Output:
Input a number:
35

Array elements:
array_nums[0] = 35.0000
array_nums[1] = 11.6667
array_nums[2] = 3.8889
array_nums[3] = 1.2963
array_nums[4] = 0.4321
array_nums[5] = 0.1440
array_nums[6] = 0.0480
array_nums[7] = 0.0160
array_nums[8] = 0.0053
array_nums[9] = 0.0018

C Code:

#include <stdio.h>

int main ()

int array_size, i, x, z;

int min_val, position;

// Prompt the user for the array size

printf("Input the array size:\n");

scanf("%d", &array_size);

// Declare an array of integers with the specified size

int vetor[array_size];

// Prompt the user to input array elements

printf("\nInput array elements:\n");

for (i = 0; i < array_size; i++)


{

scanf("%d", &z);

vetor[i] = z; // Store the input value in the array

// Initialize min_val and position with the first element of the


array

min_val = vetor[0];

position = 0;

// Loop to find the smallest value and its position within the array

for (i = 1; i < array_size; i++)

if (vetor[i] < min_val)

min_val = vetor[i]; // Update the minimum value

position = i; // Update the position of the minimum value

// Print the smallest value and its position

printf("\nSmallest Value: %d\n", min_val);

printf("Position within array: %d\n", position);

return 0; // End of program


}

Sample Output:
Input the array size:
5

Input array elements:


35
17
-5
45
36

Smallest Value: -5
Position within array: 2

131.Write a C program that accepts two strings and checks


whether the second string is present in the last part of the first
string.

Sample Output:
Input the first string:
abcdef
Input the second string:
ef
Is second string present in the last part of the first string?
Present!

C Code:

#include <stdio.h>

#include <string.h>

int main() {

short num1_len, num2_len;

char num1[50], num2[50];


// Prompt the user to input the first string

printf("Input the first string:\n");

scanf("%s", num1);

// Prompt the user to input the second string

printf("Input the second string:\n");

scanf("%s", num2);

// Get the lengths of the two strings

num1_len = strlen(num1);

num2_len = strlen(num2);

// Check if the second string is present in the last part of the


first string

printf("Is second string present in the last part of the first


string?\n");

if (num1_len == num2_len) // If the lengths are equal

if (strcmp(num1, num2) == 0) // If the strings are equal

printf("Present!\n");

else

printf("Not Present!\n");

else if (num1_len < num2_len) // If the first string is shorter than


the second

printf("Not Present!\n");

else if (strstr(&num1[num1_len - num2_len - 1], num2)) // If the


second string is found in the last part of the first string
printf("Present!\n");

else

printf("Not Present!\n");

return 0; // End of program

Copy
Sample Output:
Input the first string:
abcdef
Input the second string:
ef
Is second string present in the last part of the first string?
Present!

132. Write a C program to find the heights of the top three


buildings in descending order from eight given buildings.
Input:
0 <= height of building (integer) <= 10,000

Sample Output:
Input heights(integer values) of the top eight buildings:
25
15
45
22
35
18
95
65

Heights of the top three building:


95
65
45

C Code:
#include<stdio.h>

int main(){

int heights[10], i, j, h, max_heights;

// Prompt the user to input heights of the top eight buildings

printf("Input heights (integer values) of the top eight buildings:\


n");

// Read the heights into the array

for(i = 0; i < 8; i++){

scanf("%d", &heights[i]);

// Sorting the heights in descending order

for(i = 0; i < 8; i++){

max_heights = i;

for(j = i; j < 8; j++){

if(heights[j] > heights[max_heights]){

max_heights = j;

h = heights[max_heights];

heights[max_heights] = heights[i];
heights[i] = h;

// Printing the heights of the top three buildings

printf("\nHeights of the top three buildings:\n");

printf("%d\n%d\n%d\n", heights[0], heights[1], heights[2]);

return 0; // End of program

Copy
Sample Output:
Input heights(integer values) of the top eight buildings:
25
15
45
22
35
18
95
65

Heights of the top three building:


95
65
45

133. Write a C program to calculate the sum of two given


integers and count the number of digits in the sum value.

Sample Output:
Input two integer values:
68
75

Number of digits of the sum value of the said numbers:


3
C Code:

#include <stdio.h>

int main()

int x, y, sum_val, ctr;

printf("Input two integer values:\n");

scanf("%d %d", &x, &y);

ctr = 0; // Initialize a counter to keep track of digits

sum_val = x + y; // Calculate the sum of x and y

// Loop to count the number of digits in the sum value

while (sum_val != 0)

if (sum_val > 0)

sum_val = sum_val / 10; // Divide by 10 to remove the


rightmost digit

ctr++; // Increment the counter

// Print the number of digits in the sum value

printf("\nNumber of digits of the sum value of the said numbers:\


n");
printf("%d\n", ctr);

return 0; // End of program

Copy
Sample Output:
Input two integer values:
68
75

Number of digits of the sum value of the said numbers:


3

134. Write a C program to check whether the three given lengths


(integers) of three sides of a triangle form a right triangle or not.
Print "Yes" if the given sides form a right triangle otherwise print
"No".
Input:
Integers separated by a single space.
1 <= length of the side <= 1,000

Sample Output:
Input the three sides of a trainagel:
12
11
13
It is not a right angle triangle!

Input:
Integers separated by a single space.
1 <= length of the side <= 1,000

Sample Solution:

C Code:

#include<stdio.h>
int main()

int x, y, z;

// Prompt the user to input the three sides of a triangle

printf("Input the three sides of a triangle:\n");

// Read the input values for x, y, and z

scanf("%d %d %d", &x, &y, &z);

// Check if the triangle is a right angle triangle

if ((x*x) + (y*y) == (z*z) || (x*x) + (z*z) == (y*y) || (y*y) +


(z*z) == (x*x))

// If the condition is true, print that it's a right angle


triangle

printf("It is a right angle triangle!\n");

else

// If the condition is false, print that it's not a right


angle triangle

printf("It is not a right angle triangle!\n");

}
return 0; // End of the program

Copy
Sample Output:
Input the three sides of a trainagel:
12
11
13
It is not a right angle triangle!

135. Write a C program that reads an integer n and finds the


number of combinations of a, b, c and d (0 ≤ a, b, c, d ≤ 9) where
(a + b + c + d) will be equal to n.
Input:
n (1 <= n <= 50)

Sample Output:
Input a number:
5

a + b + c + d = n
0, 0, 0, 5
0, 0, 1, 4
....
4, 0, 1, 0
4, 1, 0, 0
5, 0, 0, 0

Total number of combinations:


56

Input:
n (1 <= n <= 50)

Sample Solution:

C Code:

#include<stdio.h>
int main() {

int i, j, k, l, n;

printf("Input a number:\n");

scanf("%d", &n);

// Check if n is within the valid range (1 to 39)

if (n >= 1 && n <= 39) {

printf("\na + b + c + d = n");

// Initialize a counter to keep track of the valid combinations

int count = 0;

// Nested loops to iterate through all possible combinations of a,


b, c, and d

for (i = 0; i <= 9; i++) {

for (j = 0; j <= 9; j++) {

for (k = 0; k <= 9; k++) {

for (l = 0; l <= 9; l++) {

if (i + j + k + l == n) {

// Print the combination and increment the counter

printf("\n%d, %d, %d, %d", i, j, k, l);

count++;

}
}

// Print the total number of valid combinations

printf("\n\nTotal number of combinations: %d\n", count);

return 0; // End of the program

Copy
Sample Output:
Input a number:
5

a + b + c + d = n
0, 0, 0, 5
0, 0, 1, 4
0, 0, 2, 3
0, 0, 3, 2
0, 0, 4, 1
0, 0, 5, 0
0, 1, 0, 4
0, 1, 1, 3
0, 1, 2, 2
0, 1, 3, 1
0, 1, 4, 0
0, 2, 0, 3
0, 2, 1, 2
0, 2, 2, 1
0, 2, 3, 0
0, 3, 0, 2
0, 3, 1, 1
0, 3, 2, 0
0, 4, 0, 1
0, 4, 1, 0
0, 5, 0, 0
1, 0, 0, 4
1, 0, 1, 3
1, 0, 2, 2
1, 0, 3, 1
1, 0, 4, 0
1, 1, 0, 3
1, 1, 1, 2
1, 1, 2, 1
1, 1, 3, 0
1, 2, 0, 2
1, 2, 1, 1
1, 2, 2, 0
1, 3, 0, 1
1, 3, 1, 0
1, 4, 0, 0
2, 0, 0, 3
2, 0, 1, 2
2, 0, 2, 1
2, 0, 3, 0
2, 1, 0, 2
2, 1, 1, 1
2, 1, 2, 0
2, 2, 0, 1
2, 2, 1, 0
2, 3, 0, 0
3, 0, 0, 2
3, 0, 1, 1
3, 0, 2, 0
3, 1, 0, 1
3, 1, 1, 0
3, 2, 0, 0
4, 0, 0, 1
4, 0, 1, 0
4, 1, 0, 0
5, 0, 0, 0

Total number of combinations:


56

136. Write a C program to find prime numbers that are less than
or equal to a given integer.
Input:
n (1 <= n <= 999,999)

Sample Output:
Input a number:
123
Number of prime numbers which are less than or equal to 123
30

Input:
n (1 <= n <= 999,999)

Sample Solution:

C Code:

#include<stdio.h>

#define MAX_N 999999

int is_prime[MAX_N + 1];

int prime[MAX_N];

int main() {

int p = 0, i, j, n;

// Prompting the user to input a number

printf("Input a number:\n");

scanf("%d", &n);

// Initializing the is_prime array to all true (1)

for (i = 0; i <= n; i++)

is_prime[i] = 1;

is_prime[0] = is_prime[1] = 0; // 0 and 1 are not prime


// Finding prime numbers using the Sieve of Eratosthenes algorithm

for (i = 2; i <= n; i++) {

if (is_prime[i]) {

prime[p++] = i; // Storing prime numbers in the prime array

for (j = 2 * i; j <= n; j += i)

is_prime[j] = 0; // Marking multiples of a prime as not prime

// Printing the number of prime numbers and the count

printf("Number of prime numbers which are less than or equal to %d


", n);

printf("\n%d", p);

return 0; // End of the program

Copy
Sample Output:
Input a number:
123
Number of prime numbers which are less than or equal to 123
30

137. Write a C program to check if a point (x, y) is within a


triangle or not. Three points make up a triangle.
Input:
x1,y1,x2,y2,x3,y3,xp,yp separated by a single space

Sample Output:
Input three points to form a triangle:
x1 y1 z1

Input the point to check it is inside the triangle or not:


The point is outside the triangle!

Input:
x1,y1,x2,y2,x3,y3,xp,yp separated by a single space

Sample Solution:

C Code:

#include <stdio.h>

// Function to calculate the outer product of two vectors

double check_outer_product(double X1, double Y1, double X2, double Y2)


{

return X1 * Y2 - X2 * Y2;

int main() {

double x[3], y[3], xp, yp, cop1, cop2, cop3;

// Prompting the user to input three points to form a triangle

printf("Input three points to form a triangle:\n");

scanf("%lf %lf %lf %lf %lf %lf", &x[0], &y[0], &x[1], &y[1], &x[2],
&y[2]);

// Prompting the user to input a point to check if it's inside the


triangle

printf("\nInput the point to check if it is inside the triangle or


not:\n");
scanf("%lf %lf", &xp, &yp);

// Calculating the outer products using the function

cop1 = check_outer_product(x[1] - x[0], y[1] - y[0], xp - x[0], yp -


y[0]);

cop2 = check_outer_product(x[2] - x[1], y[2] - y[1], xp - x[1], yp -


y[1]);

cop3 = check_outer_product(x[0] - x[2], y[0] - y[2], xp - x[2], yp -


y[2]);

// Checking if the point is inside or outside the triangle based on


outer products

if (((cop1 > 0.0) && (cop2 > 0.0) && (cop3 > 0.0)) ||

((cop1 < 0.0) && (cop2 < 0.0) && (cop3 < 0.0))) {

printf("The point is inside the triangle!");

} else {

printf("The point is outside the triangle!");

return 0; // End of the program

Copy
Sample Output:
Input three points to form a triangle:
x1 y1 z1

Input the point to check it is inside the triangle or not:


The point is outside the triangle!
138.Write a C program to test whether two lines are parallel or
not. The four points are P(x1, y1), Q(x2, y2), R(x3, y3) and S(x4,
y4), check PQ and RS are parallel are not.
Input:
−100 <= x1, y1, x2, y2, x3, y3, x4, y4 <= 100
Each value is a real number with at most 5 digits after the
decimal point.

Sample Output:
Input P(x1,y1):
5
7

Input P(x2,y2):
3
6

Input P(x3,y3):
8
9

Input P(x4,y4):
5
6

PQ and RS are not parallel!

Input:
−100 <= x1, y1, x2, y2, x3, y3, x4, y4 <= 100
Each value is a real number with at most 5 digits after the
decimal point.

Sample Solution:

C Code:

#include <stdio.h>

main() {
// Variable declarations

double x1, x2, y1, y2, x3, y3, x4, y4;

int i, n;

// Getting user input for coordinates

printf("Input P(x1,y1):\n");

scanf("%lf %lf", &x1, &y1);

printf("\nInput P(x2,y2):\n");

scanf("%lf %lf", &x2, &y2);

printf("\nInput P(x3,y3):\n");

scanf("%lf %lf", &x3, &y3);

printf("\nInput P(x4,y4):\n");

scanf("%lf %lf", &x4, &y4);

// Checking if lines PQ and RS are parallel

if ((x1 == x2) && (x3 == x4))

printf("\nPQ and RS are parallel!\n");

else if ((x1 == x2) || (x3 == x4))

printf("\nPQ and RS are not parallel!\n");

else if (((y1 - y2) / (x1 - x2) - (y3 - y4) / (x3 - x4)) == 0.0)

printf("\nPQ and RS are parallel!\n");

else

printf("\nPQ and RS are not parallel!\n");

return (0); // End of the program


}

Copy
Sample Output:
Input P(x1,y1):
5
7

Input P(x2,y2):
3
6

Input P(x3,y3):
8
9

Input P(x4,y4):
5
6

PQ and RS are not parallel!

139. Write a C program to find the maximum sum of a contiguous


subsequence from a given sequence of numbers a1, a2, a3, ... an
( n = number of terms in the sequence).
Input:
You can assume that 1 <= n <= 500 and -10000 <= ai <= 10000.

Sample Output:
Input number of terms in the sequence:
5

Input the terms of the said sequence:


3
2
6
-7
8
Maximum sum of a contiguous subsequence:
12
Write a C program to find the maximum sum of a contiguous
subsequence from a given sequence of numbers a1, a2, a3, ... an
( n = number of terms in the sequence).

You can assume that 1 <= n <= 500 and -10000 <= ai <= 10000.
A contiguous subsequence of a list S is a subsequence made up
of consecutive elements of S.
For instance, if S is
5, 15, −30, 10, −5, 40, 10,
then 15, −30, 10 is a contiguous subsequence but 5, 15, 40 is not.
Give a linear-time algorithm for the following task:
• Input: A list of numbers a1, a2, . . . , an
• Output: The contiguous subsequence of maximum sum. (Note
that a subsequence of length zero has sum zero.)
For the preceding example, the answer would be 10, −5, 40, 10,
with a sum of 55
Ref: https://bit.ly/2IGGI3f

Sample Solution:

C Code:

#include <stdio.h>

int main() {

int n;

long a[5000];

long long max, tmp;

int i, j;

// Getting the number of terms in the sequence from the user

printf("Input number of terms in the sequence:\n");

scanf("%d", &n);
// Getting the terms of the sequence from the user

printf("\nInput the terms of the said sequence:\n");

for (i = 0; i < n; i++)

scanf("%ld", &(a[i]));

max = a[0];

tmp = 0;

// Finding the maximum sum of a contiguous subsequence

for (i = 0; i < n; i++) {

for (j = i; j < n; j++) {

tmp += a[j];

if (max < tmp)

max = tmp;

tmp = 0;

// Printing the maximum sum of a contiguous subsequence

printf("Maximum sum of a contiguous subsequence:\n");

printf("%lld\n", max);

return 0; // End of the program

}
Sample Output:
Input number of terms in the sequence:
5

Input the terms of the said sequence:


3
2
6
-7
8
Maximum sum of a contiguous subsequence:
12

140. Write a C program that reads a sequence of integers and


finds the element that occurs most frequently.

Sample Output:

Input the terms of the sequence:


5
2
4
6
8
10
^Z
Mode values of the said sequence in ascending order:
2
4
5
6
8
10

C Code:

#include <stdio.h>

#include<stdlib.h>

#include<math.h>

#include<string.h>
int main(void) {

int in;

int nums[101] = {0}; // Initialize an array to store frequency of


each number (from 1 to 100)

int i;

int max_val = 0; // Variable to keep track of the maximum frequency

printf("\nInput the terms of the sequence:\n");

while (scanf("%d", &in) != EOF) // Keep reading numbers until end of


input (EOF)

nums[in]++; // Increment the frequency count for the input number

// Find the maximum frequency

for (i = 1; i <= 100; i++) {

if (max_val < nums[i])

max_val = nums[i];

printf("Mode values of the said sequence in ascending order:\n");

// Print numbers that have the maximum frequency

for (i = 1; i <= 100; i++) {

if (max_val == nums[i])

printf("%d\n", i);
}

return 0; // End of the program

Copy
Sample Output:

Input the terms of the sequence:


5
2
4
6
8
10
^Z
Mode values of the said sequence in ascending order:
2
4
5
6
8
10
141. Write a C program that reads n digits (given) chosen from 0
to 9 and prints the number of combinations where the sum of the
digits equals another given number (s). Do not use the same
digits in a combination.
For example, the combinations where n = 3 and s = 6 are as
follows:
1+2+3=6
0+1+5=6
0+2+4=6

Sample Output:
Input the number:
3

Sum of the digits:


6
Number of combinations: 3

C Code:

#include<stdio.h>

// Recursive function to find combinations

int combination(int n, int s, int a) {

int i, result = 0;

// Base case: if n is 1, check if s is within valid range

if (n == 1) {

if (s >= a && s <= 9) {

return 1;

} else {

return 0;

// Iterate through possible values (a to 9)

for (i = a; i <= 9; i++) {

// Recursively call combination for (n-1) and adjust s and a


values

result += combination(n - 1, s - i, i + 1);

return result; // Return the total combinations


}

int main() {

int n, s;

printf("Input the number:\n");

scanf("%d", &n);

printf("\nSum of the digits:\n");

scanf("%d", &s);

if (n != 0 && s != 0) {

printf("Number of combinations: %d\n", combination(n, s, 0));

return 0;

Copy
Sample Output:
Input the number:
3

Sum of the digits:


6
Number of combinations: 3

142. Write a C program that reads the two adjoining sides and
the diagonal of a parallelogram and checks whether the
parallelogram is a rectangle or a rhombus.
Input:
Two adjoined sides and the diagonal.
1 <= ai, bi, ci <= 1000, ai + bi > ci

Sample Output:
Input two adjoined sides of the parallelogram:
3
4

Input the diagonal of the parallelogram:


5

This is a rectangle.
Sample Output:
Input two adjoined sides of the parallelogram:
5
5

Input the diagonal of the parallelogram:


7

This is a rhombus.

According to Wikipedia-
parallelograms: In Euclidean geometry, a parallelogram is a
simple (non-self-intersecting) quadrilateral with two pairs of
parallel sides. The opposite or facing sides of a parallelogram are
of equal length and the opposite angles of a parallelogram are of
equal measure.
rectangles: In Euclidean plane geometry, a rectangle is a
quadrilateral with four right angles. It can also be defined as an
equiangular quadrilateral, since equiangular means that all of its
angles are equal (360°/4 = 90°). It can also be defined as a
parallelogram containing a right angle.
rhombus: In plane Euclidean geometry, a rhombus (plural rhombi
or rhombuses) is a simple (non-self-intersecting) quadrilateral
whose four sides all have the same length. Another name is
equilateral quadrilateral, since equilateral means that all of its
sides are equal in length. The rhombus is often called a diamond,
after the diamonds suit in playing cards which resembles the
projection of an octahedral diamond, or a lozenge, though the
former sometimes refers specifically to a rhombus with a 60°
angle (see Polyiamond), and the latter sometimes refers
specifically to a rhombus with a 45° angle.
Input:
Two adjoined sides and the diagonal.
1 <= ai, bi, ci <= 1000, ai + bi > ci

Sample Solution:

C Code:

#include <stdio.h>

int main() {

int h1, h2, t;

int rect = 0;

int hisi = 0;

// Initialize variables

rect = 0;

hisi = 0;

// Input the adjoined sides of the parallelogram

printf("Input two adjoined sides of the parallelogram:\n");

scanf("%d", &h1);

scanf("%d", &h2);

// Input the diagonal of the parallelogram


printf("\nInput the diagonal of the parallelogram:\n");

scanf("%d", &t);

// Check if it's a rectangle

if (t * t == h1 * h1 + h2 * h2)

rect++;

// Check if it's a rhombus

if (h1 == h2)

hisi++;

// Output the results

if (rect > 0)

printf("\nThis is a rectangle.");

if (hisi > 0)

printf("\nThis is a rhombus.");

return 0;

Copy
Sample Output:
Input two adjoined sides of the parallelogram:
3
4

Input the diagonal of the parallelogram:


5
This is a rectangle.
Sample Output:
Input two adjoined sides of the parallelogram:
5
5

Input the diagonal of the parallelogram:


7

This is a rhombus.

143. Write a C program to find the difference between the


largest integer and the smallest integer, which are created by 8
numbers from 0 to 9. The number that can be rearranged shall
start with 0 as in 00135668.
Input:
Data is a sequence of 8 numbers (digits from 0 to 9).
Output:
The difference between the largest integer and the smallest
integer.

Sample Output:
Input an integer created by 8 numbers (0 to 9):
25346879

The difference between the largest integer and the smallest


integer.
98765432 - 23456789 = 75308643

Input:
Data is a sequence of 8 numbers (digits from 0 to 9).
Output:
The difference between the largest integer and the smallest
integer.

Sample Solution:

C Code:

#include<stdio.h>
int main() {

int max_val, min_val, k, d, t;

// Prompt user to input an integer created by 8 numbers (0 to 9)

printf("Input an integer created by 8 numbers (0 to 9):\n");

scanf("%d", &d);

int i, j, s[8] = {0};

// Extract individual digits and store them in array s

for (i = 0; d != 0; i++) {

s[i] = d % 10;

d /= 10;

// Sort the digits in descending order

for (i = 0; i < 8; i++) {

for (j = 1; j + i < 8; j++) {

if (s[j - 1] < s[j]) {

t = s[j - 1];

s[j - 1] = s[j];

s[j] = t;

}
}

max_val = 0;

// Construct the largest integer from sorted digits

for (i = 0; i < 8; i++) {

max_val *= 10;

max_val += s[i];

// Reverse the order of digits in array s

for (i = 0; i * 2 < 8; i++) {

t = s[i];

s[i] = s[7 - i];

s[7 - i] = t;

min_val = 0;

// Construct the smallest integer from reversed digits

for (i = 0; i < 8; i++) {

min_val *= 10;

min_val += s[i];

}
// Calculate and display the difference between the largest and
smallest integers

printf("\nThe difference between the largest integer and the


smallest integer.\n");

printf("%d - %d = %d\n", max_val, min_val, max_val - min_val);

return 0;

Copy
Sample Output:
Input an integer created by 8 numbers (0 to 9):
25346879

The difference between the largest integer and the smallest


integer.
98765432 - 23456789 = 75308643

144. Write a C program to create the maximum number of


regions obtained by drawing n given straight lines.
Input:
(1 ≤ n ≤ 10,000).

Sample Output:
Input number of straight lines:
2
Maximum number of regions obtained by drawing 2 given straight
lines:
4

If you draw a straight line on a plane, the plane is divided into


two regions. For example, if you pull two straight lines in parallel,
you get three areas, and if you draw vertically one to the other,
you get four areas.

Input:
(1 ≤ n ≤ 10,000)
C Code:

#include <stdio.h>

int main() {

long n;

// Prompt user to input number of straight lines

printf("Input number of straight lines:\n");

scanf("%ld", &n);

// Calculate and display maximum number of regions obtained by


drawing 'n' given straight lines

printf("Maximum number of regions obtained by drawing %ld given


straight lines:\n", n);

printf("%ld\n", (n*n+n+2)/2);

return 0;

Copy
Sample Output:
Input number of straight lines:
2
Maximum number of regions obtained by drawing 2 given straight
lines:
4

145. Write a C program to sum all numerical values (positive


integers) embedded in a sentence.
Input:
Sentences with positive integers are given over multiple lines.
Each line is a character string containing one-byte alphanumeric
characters, symbols, spaces, or an empty line. However the input
is 80 characters or less per line and the sum is 10,000 or less.

Sample Output:
Input Sentences with positive integers:
5littleJackand2mouse.

Sum of all numerical values embedded in a sentence:


7

Input:
Sentences with positive integers are given over multiple lines.
Each line is a character string containing one-byte alphanumeric
characters, symbols, spaces, or an empty line. However the input
is 80 characters or less per line and the sum is 10,000 or less

Sample Solution:

C Code:

#include <stdio.h>

#include <stdlib.h>

// Define a character array to store text

char text[128];

int main(void) {

int i, j, k;

int result = 0;

char temp[8];
// Prompt user to input sentences with positive integers

printf("Input Sentences with positive integers:\n");

// Read user input into the 'text' array

scanf("%s", text);

i = 0;

while (text[i]) {

// Loop through characters until a digit is found

for (; (text[i] < '0' || '9' < text[i]) && text[i]; i++);

if ('0' <= text[i] && text[i] <= '9') {

// Extract and store the numerical value in 'temp'

for (j = 0; '0' <= text[i] && text[i] <= '9'; j++, i++) {

temp[j] = text[i];

temp[j] = '\0';

// Convert 'temp' to an integer and add it to 'result'

result += atoi(temp);

// Print the sum of all numerical values embedded in the sentence

printf("\nSum of all numerical values embedded in a sentence:\n");


printf("%d\n", result);

return 0;

Copy
Sample Output:
Input Sentences with positive integers:
5littleJackand2mouse.

Sum of all numerical values embedded in a sentence:


7

146. Write a C program to extract words of 3 to 6 characters


length from a given sentence not more than 1024 characters.
Input:
English sentences consisting of delimiters and alphanumeric
characters are given on one line.

Sample Output:
English sentences consisting of delimiters and alphanumeric
characters on one line:
w3resource.com

Extract words of 3 to 6 characters length from the said sentence:


com

Internet search engine giant, such as Google accepts web pages


around the world and classify them, creating a huge database.
The search engines also analyze the search keywords entered by
the user and create inquiries for database search. In both cases,
complicated processing is carried out in order to realize efficient
retrieval, but basics are all cutting out words from sentences.

Input:
English sentences consisting of delimiters and alphanumeric
characters are given on one line.
Sample Solution:

C Code:

#include <stdio.h>

#include <stdlib.h>

#include <ctype.h>

#include <string.h>

int main() {

// Define an array to store input text

char input_text[1536];

// Initialize a counter variable

int ctr = 0;

// Define a pointer variable 'temp'

char * temp;

// Prompt user for input

printf("English sentences consisting of delimiters and alphanumeric


characters on one line:\n");

// Read a line of text from the user

fgets(input_text, sizeof(input_text), stdin);

// Print message indicating the purpose of the operation


printf("\nExtract words of 3 to 6 characters length from the said
sentence:\n");

// Tokenize the input text using delimiters (space, period, comma,


newline)

for (temp = strtok(input_text, " .,\n"); temp != NULL; temp =


strtok(NULL, " .,\n")) {

const int len = strlen(temp);

// Check if the length of the word is between 3 and 6 characters

if (3 <= len && len <= 6) {

// If not the first word, print a space before the word

if (ctr++) putchar(' ');

// Print the word

fputs(temp, stdout);

// Print a newline character after the extracted words

puts("");

return (0);

Copy
Sample Output:
English sentences consisting of delimiters and alphanumeric
characters on one line:
w3resource.com

Extract words of 3 to 6 characters length from the said sentence:


com

147. Write a C program to find the number of combinations that


satisfy p + q + r + s = n where n is a given number <= 4000 and p,
q, r, s are between 0 and 1000.

Sample Output:
Input a positive integer:
25

Number of combinations of p,q,r,s:


3276

C Code:

#include <stdio.h>

#include <stdlib.h>

// Define a macro to ensure non-negative numbers

#define check_num(x) (x>0?x:0)

// Define global variables

int n, result, x;

int main(void) {

// Prompt user for input

printf("Input a positive integer:\n");


// Read the input

scanf("%d", &n);

// Initialize result variable

result = 0;

// Loop through possible values of x within the specified range

for (x = check_num(n - 2000); x <= 2000 && n >= x; x++) {

// Calculate the result based on the given formula

result += (1001 - abs(1000 - (n - x))) * (1001 - abs(1000


- x));

// Print the number of combinations

printf("\nNumber of combinations of p,q,r,s:\n");

printf("%d\n", result);

// Return 0 to indicate successful execution

return 0;

Sample Output:
Input a positive integer:
25

Number of combinations of p,q,r,s:


3276
148. Write a C program, which adds up columns and rows of
given table as shown in the following figure.

Input:
n (the size of row and column of the given table)
1st row of the table
2nd row of the table
:
:
n th row of the table
The input ends with a line consisting of a single 0.

Sample Output:
Input number of rows/columns:
4
Input the cell value

Row 0 input cell values


25
69
51
26

Row 1 input cell values


68
35
29
54

Row 2 input cell values


54
57
45
63

Row 3 input cell values


61
68
47
59

Result:
25 69 51 26 171
68 35 29 54 186
54 57 45 63 219
61 68 47 59 235
208 229 172 202 811

Input:
n (the size of row and column of the given table)
1st row of the table
2nd row of the table
:
:
n th row of the table
The input ends with a line consisting of a single 0.
Output:
For each dataset, print the table with sum of rows and columns.

Sample Solution:

C Code:

#include <stdio.h>

int main() {

// Declare a 2D array to store cell data

int cell_data[11][11];

int i, j, n, sum_val;

// Prompt user for input

printf("Input number of rows/columns:\n");

scanf("%d", &n);

// Prompt user for cell values

printf("Input the cell value\n");


// Check if n is a positive value

if (n > 0) {

// Loop through rows

for(i = 0; i < n; i++) {

printf("\nRow %d input cell values\n", i);

// Loop through columns

for(j = 0; j < n; j++) {

// Read cell value and store it in the array

scanf("%d", &cell_data[i][j]);

// Calculate row sums and update array

printf("\nResult:\n");

for(i = 0; i < n; i++) {

sum_val = 0;

for(j = 0; j < n; j++) {

sum_val += cell_data[j][i];

cell_data[n][i] = sum_val;

// Calculate column sums and update array


for(i = 0; i < n; i++) {

sum_val = 0;

for(j = 0; j < n; j++) {

sum_val += cell_data[i][j];

cell_data[i][n] = sum_val;

// Calculate total sum and update array

sum_val = 0;

for(i = 0; i < n; i++) {

sum_val += cell_data[n][i];

cell_data[n][n] = sum_val;

// Print the updated array

for(i = 0; i < n + 1; i++) {

for(j = 0; j < n + 1; j++) {

printf("%5d", cell_data[i][j]);

printf("\n");

// Return 0 to indicate successful execution


return 0;

Copy
Sample Output:
Input number of rows/columns:
4
Input the cell value

Row 0 input cell values


25
69
51
26

Row 1 input cell values


68
35
29
54

Row 2 input cell values


54
57
45
63

Row 3 input cell values


61
68
47
59

Result:
25 69 51 26 171
68 35 29 54 186
54 57 45 63 219
61 68 47 59 235
208 229 172 202 811

149. Write a C program that reads a list of pairs of a word and a


page number, and prints the word and a list of the corresponding
page numbers.
Input:
word page_number
Output:
word
a_list_of_the_page_number
word
a_list_of_the_Page_number.

Sample Output:
Input pairs of a word and a page_no number:
Twinkle
65
Twinkle
55
Little
25
Star
35
^Z

Word and page_no number in alphabetical order:


Little
25
Star
35
Twinkle
55 65
The number of pairs of a word and a page number is less than or
equal to 1000. A word never appears in a page more than once.
The words should be printed in alphabetical order and the page
numbers should be printed in ascending order.

Input:
word page_number
Output:
word
a_list_of_the_page_number
word
a_list_of_the_Page_number

Sample Solution:
C Code:

#include<stdio.h>

#include<string.h>

// Define a structure to hold a word and its corresponding page number

typedef struct{

int page_no;

char word[50];

} STR;

main(){

STR temp, str[10000]; // Declare variables of type STR

int i=0,j,k;

int count=0;

// Prompt user for input

printf("Input pairs of a word and a page_no number:\n");

// Read word and page_no pairs until end of file (EOF)

while(scanf("%s %d",str[i].word,&str[i].page_no)!=EOF){

i++;

// Sorting algorithm to sort words alphabetically and by page number


if words are the same
for(j=0;j<i;j++){

for(k=i-1;0<k;k--){

if(strcmp(str[k].word,str[k-1].word)<0){

temp=str[k];

str[k]=str[k-1];

str[k-1]=temp;

else if(strcmp(str[k].word,str[k-1].word)==0){

if(str[k].page_no<str[k-1].page_no){

temp=str[k];

str[k]=str[k-1];

str[k-1]=temp;

// Print sorted word and page number pairs

printf("\nWord and page_no number in alphabetical order:\n");

for(j=0;j<i;j++){

if(j!=0){

if(strcmp(str[j].word,str[j-1].word)==0){

printf(" %d",str[j].page_no);

else{
printf("\n%s\n%d",str[j].word,str[j].page_no);

else{

printf("%s\n%d",str[j].word,str[j].page_no);

printf("\n");

return 0;

Copy
Sample Output:
Input pairs of a word and a page_no number:
Twinkle
65
Twinkle
55
Little
25
Star
35
^Z

Word and page_no number in alphabetical order:


Little
25
Star
35
Twinkle
55 65

150. Write a C program that reads an expression and evaluates


it.
Input:
4
10-2*3=
8*(8+2-5)=

Sample Output:
Input an expression using +, -, *, / operators:
1+6*8-4/2
47
Sample Output:
Input an expression using +, -, *, / operators:
25/5-6*7+2
-35
Sample Output:
Input an expression using +, -, *, / operators:
9+6+(5*2)-5
20

Terms and conditions:


The expression consists of numerical values, operators and
parentheses, and the ends with '='.
The operators includes +, -, *, / where, represents, addition,
subtraction, multiplication and division.
When two operators have the same precedence, they are applied
to left to right.
You may assume that there is no division by zero.
All calculation is performed as integers, and after the decimal
point should be truncated
Length of the expression will not exceed 100.
-1 × 10 9 <= intermediate results of computation <= 10 9
Sample Input:
4
10-2*3=
8*(8+2-5)=

Sample Solution:

C Code:
#include <stdio.h>

#include <string.h>

// Function declarations

int addsub();

int muldiv();

int term();

char input[101]; // Declare character array to store user input

int pos = 0; // Initialize a global variable to keep track of the


position in the input string

// Function to parse and evaluate a term (number or expression inside


parentheses)

int term(){

int n = 0;

// Check if the current character is an opening parenthesis

if(input[pos] == '('){

pos++; // Move to the next character

n = addsub(); // Evaluate the expression inside the parentheses

// Check if the next character is a closing parenthesis

if(input[pos] == ')'){

pos++; // Move to the next character (closing parenthesis)

return n; // Return the evaluated result


}

}else{

// If the current character is a digit, parse the number

while('0' <= input[pos] && input[pos] <= '9'){

n = n*10 + (input[pos] - '0'); // Convert characters to integer


and build the number

pos++; // Move to the next character

return n; // Return the parsed number

// Function to handle multiplication and division operations

int muldiv(){

int first,second;

first = term(); // Evaluate the first term

for(;;){

if(input[pos] == '*'){

pos++; // Move to the next character (operator)

second = term(); // Evaluate the second term

first *= second; // Perform multiplication

}else if(input[pos] == '/'){

pos++; // Move to the next character (operator)


second = term(); // Evaluate the second term

first /= second; // Perform division

}else{

return first; // If no more operators, return the result

// Function to handle addition and subtraction operations

int addsub(){

int first,second;

first = muldiv(); // Evaluate the first term

for(;;){

if(input[pos] == '+'){

pos++; // Move to the next character (operator)

second = muldiv(); // Evaluate the second term

first += second; // Perform addition

}else if(input[pos] == '-'){

pos++; // Move to the next character (operator)

second = muldiv(); // Evaluate the second term

first -= second; // Perform subtraction

}else{

return first; // If no more operators, return the result


}

int main(){

int n,i,j;

printf("Input an expression using +, -, *, / operators:\n");

scanf("%s",input); // Read the user input as a string

printf("%d\n",addsub()); // Evaluate the expression and print the


result

return 0; // Indicate successful execution and return 0 to the


operating system

Copy
Sample Output:
Input an expression using +, -, *, / operators:
1+6*8-4/2
47
Sample Output:
Input an expression using +, -, *, / operators:
25/5-6*7+2
-35
Sample Output:
Input an expression using +, -, *, / operators:
9+6+(5*2)-5
20

You might also like