C Written Book

You might also like

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

Basic Definition of Programming

1.What is Program?

Ans : A program is a set of instructions that a computer uses to


perform a specific function.

2. What is Programming Language?


Ans: A programming language is a vocabulary and set of grammatical
rules for instructing a computer or computing device to perform specific
tasks. The term programming language usually refers to high-level
languages.

Example of Programming Language:


BASIC, C, C++, COBOL, Java, FORTRAN, Ada, and Pascal.
3.what is c Pogramming?
Ans:C is a general-purpose programming language that is extremely
popular, simple, and flexible to use. It is a structured programming
language .

4.What is IDE?
Ans: An integrated development environment (IDE) is a software
application that helps programmers develop software code efficiently. It
increases developer productivity by combining capabilities such as
software editing, building, testing, and packaging in an easy-to-use
application.
CodeBlocks is one of the famous IDE for C Programming.

1
Basic Definition of Programming

5.What is Compiler?
Ans: A compiler is a special program that translates a programming
language's source code into machine code, bytecode or another
programming language.

6.What is variable?
Ans: Variables are containers for storing data values, like numbers and
characters.
7.what is constant?
Ans: A constant is a named piece of memory where the value cannot be
changed while a program runs.
9.What is interpreter?
Ans: An interpreter is a computer program, which converts each
high-level program statement into the machine code.

Difference between compiler & interpreter:

2
History of C Programming Language:

C is a general-purpose programming language that was developed in


the early 1970s by Dennis Ritchie at Bell Labs. It was originally designed
to be used for writing the Unix operating system.

At the time, most programming languages were high-level languages


that were not efficient enough for systems programming. C was
designed to be a low-level language that could be used to write efficient
code that could run directly on the hardware.

The name "C" was chosen because it followed the previous language, B.
C was an improvement over B and included features like data types,
structures, and pointers.

In the late 1970s and early 1980s, the popularity of C grew rapidly as it
was adopted by many other operating systems, including MS-DOS,

3
Windows, and Mac OS. The development of the C compiler made it
easier to write C code on a variety of platforms.

Today, C is still widely used in many areas of programming, including


systems programming, embedded systems, game development, and

scientific computing. Its popularity has led to the development of many


libraries and frameworks that make it easier to write C code for a variety
of applications.

Charactaristics of C Programming Language:

1. Efficiency
2. Low-level programming
3. Portability
4. Modularity
5. Structured programming
6. Procedural programming
7. Extensibility

10.What is data types?

Ans: In computer programming, a datatype is a classification of data that


specifies the type of value that a variable or expression can hold. It is a

4
way of indicating to the computer how to interpret and handle the data
that is being used in a program.

Datatypes can include simple types like integers, floating-point numbers,


and characters, as well as more complex types like arrays, structures, and
classes. Each datatype has a specific set of rules for how the data can be
used and manipulated.

Data types list of C Programming:

Bit means binary digit. 0 & 1.


1 bit=8 byte

Format Specifire:
Float=%f
Char=%c
Int=%d

Data type declaration process:

5
Here is an example of a declaration statement in the C programming
language that declares an integer variable named "x":

int x;
Some programming languages require you to specify an initial value for
the variable at the time of declaration. For example, in C, you can
initialize the integer variable "x" to the value 10 as follows:
int x = 10;

Here is a list of the keywords used in the C programming language:


auto, break, case, char, const, continue, default, do, double, else, enum,
extern, float, for, goto, if, int, long, register, return, short, signed, sizeof,
static, struct, switch, typedef, union, unsigned, void, volatile, while.

C tokens:
1. Keywords: These are reserved words in C that have a specific meaning
and cannot be used as variable or function names. Examples include
if, while, int, float, else, etc.
2. Identifiers: These are user-defined names that represent variables,
functions, or other program elements. Identifiers must begin with a
letter or underscore, followed by any combination of letters,
underscores, or digits. For example, sum, _count, calculateArea, etc.
3. Constants: These are fixed values that do not change during the
execution of a program. There are two types of constants in C:
 Integer constants: These represent whole numbers and can be

expressed in decimal, octal, or hexadecimal form. For example, 25,


034, 0x1A, etc.

6
 Floating-point constants: These represent decimal numbers and
include a decimal point or an exponent. For example , 3.14159, 2.5e-
3, etc.
4. String literals: These are sequences of characters enclosed in double
quotes. For example, "Hello, world!".
5. Operators: These are symbols that perform mathematical or logical
operations on operands. Examples include +, -, *, /, %, ==, !=, &&, ||,
etc.
6. Punctuators: These are special characters that are used to separate or
group parts of a program. Examples include {, }, (), [], ,, ;, etc.

In summary, tokens in C programming language are classified into six


types: keywords, identifiers, constants, string literals, operators, and
punctuators. Understanding these different types of tokens is crucial for
writing correct and efficient C programs.

Oparator in C:

Here are the different types of operators in C:

1. Arithmetic operators: These operators perform basic arithmetic


operations on numerical operands. Examples include + (addition), -
(subtraction), * (multiplication), / (division), and % (modulus).
2. Relational operators: These operators compare two operands and
return a boolean value (true or false) depending on the
relationship between them. Examples include == (equal to), != (not
equal to), < (less than), > (greater than), <= (less than or equal to),
and >= (greater than or equal to).
3. Logical operators: These operators perform logical operations on
boolean operands. Examples include && (logical AND), || (logical
OR), and ! (logical NOT).
4. Bitwise operators: These operators perform bitwise operations on
numerical operands, which means that they manipulate the

7
individual bits that make up the operands. Examples include &
(bitwise AND), | (bitwise OR), ^ (bitwise XOR), ~ (bitwise NOT), <<
(left shift), and >> (right shift).
5. Assignment operators: These operators assign a value to a variable.
Examples include = (simple assignment), += (add and assign), -=
(subtract and assign), *= (multiply and assign), /= (divide and
assign), %= (modulus and assign), <<= (left shift and assign), >>=
(right shift and assign), &= (bitwise AND and assign), |= (bitwise OR
and assign), and ^= (bitwise XOR and assign).
6. Increment and decrement operators: These operators are used to
increment or decrement the value of a variable by one. Examples
include ++ (increment) and -- (decrement).
7. Conditional operator: This operator is also known as the ternary
operator, and it is used to assign a value to a variable based on a
condition. The syntax is condition ? value1 : value2, where condition
is a boolean expression, value1 is the value to be assigned if the
condition is true, and value2 is the value to be assigned if the
condition is false.

In summary, operators in C programming language are used to perform


various operations on operands, such as arithmetic, comparison, logical,
bitwise, assignment, and conditional operations. Understanding the
different types of operators and their usage is essential for writing correct
and efficient C programs.

Header file in c: header files are provided by the C standard library


and the operating system. They contain declarations for functions,
variables, and other resources that are part of the standard library or
provided by the operating system. Examples of system header files
include stdio.h, stdlib.h, string.h, math.h, and unistd.h.

#include <stdio.h>

There are two ways to add comments in C:

8
1. Single-line comments: These are comments that span only one
line. They are useful for providing brief descriptions or
explanations of code. To add a single-line comment, you can use
two forward slashes ( //) followed by the text of the comment. For
example:
// This is a single-line comment
Anything after the // is considered a comment and will not be executed
by the compiler.

2. Multi-line comments: These are comments that can span multiple


lines. They are useful for providing longer descriptions or
explanations of code. To add a multi-line comment, you can use /*
to start the comment and */ to end the comment. For example:

/* This is a multi-line comment that spans multiple lines */


Anything between the /* and */ is considered a comment and will not be
executed by the compiler.
Here's an example of a C program with both single-line and multi-line
comments:
#include <stdio.h>

int main() {
// This is a single-line comment
/*
This is a multi-line comment that spans multiple lines.
It can be used to provide more detailed descriptions or explanations
of code, or to temporarily disable code that you don't want to execute.
*/
printf("Hello, world!\n"); // Another single-line comment
return 0;

9
}

\n=new line.
\t=tab (1 tab means 4 space)

Syntex of c program:
#include <stdio.h>

int main() {
printf("Hello, world!\n");
return 0;
}

1. #include <stdio.h>: This is a preprocessor directive that tells the


compiler to include the standard input/output library in the
program. This library provides functions like printf() and scanf() for
handling input and output.
2. int main() { ... }: This is the main function of the program, which is
the entry point for execution. The int keyword specifies the return
type of the function, which in this case is an integer. The function
body is enclosed in curly braces {}.
3. printf("Hello, world!\n");: This is a function call to printf(), which is
used to print text to the console. The text to be printed is enclosed
in double quotes " ", and the \n at the end represents a newline
character.
4. return 0;: This statement returns the value 0 from the main
function. In C, a return value of 0 from the main function indicates
that the program executed successfully.

10
Overall, the basic structure of a C program includes a main() function
that serves as the entry point for execution, as well as any necessary

preprocessor directives and function calls to perform specific tasks. The C


language is known for its concise syntax and its emphasis on low-level
control over hardware and memory, which allows for efficient and
powerful programming.

Take input from User:


***When we take input from user we use scanf() function.

Q-1.Write a c program to enter two numbers and find their sum.


Solution:
#include <stdio.h>
int main() {
int num1, num2, sum;

printf("Enter the first number: ");


scanf("%d", &num1);
printf("Enter the second number: ");
scanf("%d", &num2);
sum = num1 + num2;
printf("The sum of %d and %d is %d\n", num1, num2, sum);

return 0;
}

Explanation:

11
1. We start by including the stdio.h header file, which contains
functions for input and output.
2. We declare three variables: num1, num2, and sum. num1 and num2
are used to store the two numbers entered by the user, while sum
will hold their sum.
3. We use the printf function to prompt the user to enter the first
number, and then we use the scanf function to read the input
value and store it in the num1 variable.
4. We do the same for the second number, using printf to prompt
the user and scanf to read the input and store it in num2.
5. We calculate the sum of the two numbers and store the result in
sum.
6. Finally, we use printf to display the result to the user, with the
original numbers and their sum.
7. The return 0 statement at the end of the main function indicates
that the program has executed successfully.

p.p-1. Write a c program to enter three numbers and find their sum.

Q-2. .Write a c program to enter length & breadth of a rectangle and


finds its perimeter & area.
Solution:
Rectangle area = length * breadth
Rectangle perimeter = 2 * (length + breadth)

#include <stdio.h>

int main() {
float length, breadth, area, perimeter;

printf("Enter the length of the rectangle: ");


scanf("%f", &length);

12
printf("Enter the breadth of the rectangle: ");
scanf("%f", &breadth);

area = length * breadth;


perimeter = 2 * (length + breadth);

printf("The area of the rectangle is %.2f\n", area);


printf("The perimeter of the rectangle is %.2f\n", perimeter);

return 0;
}

Q-3.Write a c program to enter radius of a circle and find its diameter,


circumference and area.
Solution:
Circle diameter = 2 * radius
Circle circumference = 2 * PI * radius
Circle area = PI * radius * radius

#include <stdio.h>

#define PI 3.14159

int main() {
float radius, diameter, circumference, area;

printf("Enter the radius of the circle: ");


scanf("%f", &radius);

diameter = 2 * radius;
circumference = 2 * PI * radius;
area = PI * radius * radius;

printf("The diameter of the circle is %.2f\n", diameter);


printf("The circumference of the circle is %.2f\n", circumference);
printf("The area of the circle is %.2f\n", area);

13
return 0;
}

Q-4. .Write a c program to enter base and height of a triangle and


finds its area.
Solution:
Triangle area = 0.5 * base * height

#include <stdio.h>

int main() {
float base, height, area;

printf("Enter the base of the triangle: ");


scanf("%f", &base);

printf("Enter the height of the triangle: ");


scanf("%f", &height);

area = 0.5 * base * height;

printf("The area of the triangle is %.2f\n", area);

return 0;
}

Q-5. Write a c program to enter length in centimeter and convert it


into meter and kilometer.
Solution:
1meter=100cm

#include <stdio.h>

int main() {
float cm, m, km;

printf("Enter length in centimeters: ");

14
scanf("%f", &cm);

m = cm / 100;
km = cm / 100000;

printf("%.2f cm = %.2f m\n", cm, m);


printf("%.2f cm = %.2f km\n", cm, km);

return 0;
}

Q-6. Write a c program to enter temperature in celcius and convert it


into fahrenhite.
Solution:

c/5=(f-32)/9=(k-273)/5

#include <stdio.h>

int main() {
float celsius, fahrenheit;

printf("Enter temperature in Celsius: ");


scanf("%f", &celsius);

fahrenheit = (celsius * 9/5) + 32;

printf("%.2f Celsius = %.2f Fahrenheit\n", celsius, fahrenheit);

return 0;
}

Q-7. Write a c program to enter temperature in fahrenhite and


convert it into celcius.
Solution:
c/5=(f-32)/9=(k-273)/5

15
#include <stdio.h>

int main() {
float fahrenheit, celsius;

printf("Enter temperature in Fahrenheit: ");


scanf("%f", &fahrenheit);

celsius = (fahrenheit - 32) * 5/9;

printf("%.2f Fahrenheit = %.2f Celsius\n", fahrenheit, celsius);

return 0;
}

Q-8. Write a c program to convert days into years,week and days.


Solution:

#include <stdio.h>

int main() {
int days, years, weeks, remaining_days;

printf("Enter number of days: ");


scanf("%d", &days);

years = days / 365;


weeks = (days % 365) / 7;
remaining_days = days - (years * 365 + weeks * 7);

printf("%d days = %d years, %d weeks, and %d days\n", days, years, weeks,


remaining_days);

return 0;
}

16
Q-9. Write a c program to find the power of any number(x^y).
Solution:
#include <stdio.h>
#include <math.h>

int main() {
float base, exponent, result;

printf("Enter base number: ");


scanf("%f", &base);

printf("Enter exponent: ");


scanf("%f", &exponent);

result = pow(base, exponent);

printf("%.2f^%.2f = %.2f\n", base, exponent, result);

return 0;
}
Q-10.Write a c program to enter any number and calculate its squre
root.
Solution:

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

int main() {
float number, square_root;

printf("Enter a number: ");


scanf("%f", &number);

square_root = sqrt(number);

printf("Square root of %.2f is %.2f\n", number, square_root);

return 0;

17
}

Q-11.Write a c program to enter two angles of a triangle and find the


third angle.
Solution:
angle1+angle2+ angle3=180

#include <stdio.h>

int main() {
float angle1, angle2, angle3;

printf("Enter the first angle of the triangle: ");


scanf("%f", &angle1);

printf("Enter the second angle of the triangle: ");


scanf("%f", &angle2);

angle3 = 180 - angle1 - angle2;

printf("The third angle of the triangle is: %.2f degrees\n", angle3);

return 0;
}

p.p-11. 11.Write a c program to enter three angles of a rectangle and


find the fourth angle.

Q-12.Write a c program to calculate the area of an equilateral


triangle.
Solution:

equilateral triangle area = (sqrt(3) / 4) * side * side;

#include <stdio.h>

18
#include <math.h>

int main() {
float side, area;

printf("Enter the length of the side of the equilateral triangle: ");


scanf("%f", &side);

area = (sqrt(3) / 4) * side * side;

printf("The area of the equilateral triangle is: %.2f square units\n", area);

return 0;
}

Q-13.Write a c program to enter marks of five subjects and calculate


total,average and percentage.
Solution:
avg = total / 5
percentage = (total / 500) * 100

#include <stdio.h>

int main() {
float marks[5], total = 0, avg, percentage;
int i;

printf("Enter the marks of five subjects:\n");

// Reading marks of five subjects from user


for(i=0; i<5; i++) {
printf("Subject %d: ", i+1);
scanf("%f", &marks[i]);
total += marks[i];
}

avg = total / 5; // Calculating average marks

percentage = (total / 500) * 100; // Calculating percentage marks

19
printf("Total marks obtained: %.2f\n", total);
printf("Average marks obtained: %.2f\n", avg);
printf("Percentage of marks obtained: %.2f%%\n", percentage);

return 0;
}

p.p-13. Write a c program to enter marks of seven subjects and


calculate total,average and percentage

Q-14.Write a c program to enter P,T, and R and calculate simple and


compound interest.
Solution:

SimpIe Interest = (P * T * R) / 100


Compound Interest = P * pow((1 + R/100), T) – P
P=principle,T=time,R=Rate

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

int main() {
float P, T, R, SI, CI;

printf("Enter the principal amount: ");


scanf("%f", &P);

printf("Enter the time period (in years): ");


scanf("%f", &T);

printf("Enter the rate of interest (in percentage): ");


scanf("%f", &R);

// Calculating simple interest


SI = (P * T * R) / 100;

// Calculating compound interest


CI = P * pow((1 + R/100), T) - P;

20
printf("Simple interest = %.2f\n", SI);
printf("Compound interest = %.2f\n", CI);

return 0;
}

Condition based problem : If- Else

Syntex of if-else problem:

if (condition) {

// code to execute if the condition is true

else {

// code to execute if the condition is false

Explain: Here, condition is a boolean expression that evaluates to


either true or false. If the condition is true, the code inside the first set of
curly braces will be executed, otherwise, the code inside the second set
of curly braces will be executed.

Note that the else block is optional. If it is not included, then only the
code inside the if block will be executed if the condition is true, and
nothing will happen if the condition is false.

21
Q-15. Write a c program to check whether a number is
negative ,positive or zero.
Solution:

Number>0=positive
Number<0=negative
Number=0 then zero count

#include <stdio.h>

int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);

if (num > 0) {
printf("%d is positive.", num);
}
else if (num < 0) {
printf("%d is negative.", num);
}
else {
printf("The number is zero.");
}

return 0;
}

Here's how the program works:

 The program prompts the user to enter a number.


 The user enters a number, which is stored in the num variable
using scanf().
 The program checks whether the number is positive, negative or
zero using an if-else statement.
 If the number is greater than 0, it's considered positive and the
program prints a message indicating that.

22
 If the number is less than 0, it's considered negative and the
program prints a message indicating that.
 If the number is equal to 0, it's considered zero and the program
prints a message indicating that.

Q-16. Write a c program to check whether number is divisible by 5


and 11 or not.
Solution:
#include <stdio.h>

int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);

if (num % 5 == 0 && num % 11 == 0) {


printf("%d is divisible by both 5 and 11.", num);
}
else {
printf("%d is not divisible by both 5 and 11.", num);
}

return 0;
}

Q-17. Write a c program to check whether a character is alphabet or


not.
Solution:

Alphabet=(a-z)&(A-Z)

#include <stdio.h>

int main() {
char ch;
printf("Enter a character: ");

23
scanf("%c", &ch);

if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) {
printf("%c is an alphabet.", ch);
}
else {
printf("%c is not an alphabet.", ch);
}

return 0;
}

Q-18. Write a c program to input any alphabet and check whether it is


vowel or consonant.
Solution:

vowel: A,E,I O,U,( a,e,i,o,u)

#include <stdio.h>

int main() {
char ch;
printf("Enter a character: ");
scanf("%c", &ch);

if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' ||


ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U') {
printf("%c is a vowel.", ch);
}
else {
printf("%c is a consonant.", ch);
}

return 0;
}

24
Q-19. Write a c program to input any character and check whether it
is alphabet,digit or special character.
Solution:

Digit=(0-9)
Alphabet=(a-z)&(A-Z)
Special character=@,%,+,-,*,/,!,?.

#include <stdio.h>

int main() {
char ch;
printf("Enter a character: ");
scanf("%c", &ch);

if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) {
printf("%c is an alphabet.", ch);
}
else if (ch >= '0' && ch <= '9') {
printf("%c is a digit.", ch);
}
else {
printf("%c is a special character.", ch);
}

return 0;
}

Q-20. Write a c program to input week number and print week day.
Solution:

#include <stdio.h>
int main() {
int week;
printf("Enter week number (1-7): ");
scanf("%d", &week);

if (week == 1) {

25
printf("Monday");
}
else if (week == 2) {
printf("Tuesday");
}
else if (week == 3) {
printf("Wednesday");
}
else if (week == 4) {
printf("Thursday");
}
else if (week == 5) {
printf("Friday");
}
else if (week == 6) {
printf("Saturday");
}
else if (week == 7) {
printf("Sunday");
}
else {
printf("Invalid week number!");
}

return 0;
}

Q-21. Write a c program to check whether a character is uppercase or


lowercase alphabet.
Solution:

Alphabet uppercase=(A-Z)
Alphabet lowercase=(a-z)

#include <stdio.h>

int main() {
char ch;
printf("Enter a character: ");

26
scanf("%c", &ch);

if (ch >= 'A' && ch <= 'Z') {


printf("The character is an uppercase alphabet.");
}
else if (ch >= 'a' && ch <= 'z') {
printf("The character is a lowercase alphabet.");
}
else {
printf("The character is not an alphabet.");
}

return 0;
}

Q-22. Write a c program to input all angles of a triangle and check


whether triangle is valid or not.
Solution:
#include <stdio.h>

int main() {
float angle1, angle2, angle3;
printf("Enter the three angles of the triangle: ");
scanf("%f %f %f", &angle1, &angle2, &angle3);

// Check if any angle is zero or negative


if (angle1 <= 0 || angle2 <= 0 || angle3 <= 0) {
printf("Invalid input: All angles must be positive.\n");
}
// Check if the sum of angles is equal to 180 degrees
else if (angle1 + angle2 + angle3 == 180) {
printf("The triangle is valid.\n");
}
else {
printf("The triangle is not valid.\n");
}

return 0;
}

27
Q-23. Write a c program to input all sides triangle and check whether
triangle is valid or not.
Solution:

side1 + side2 > side3

#include <stdio.h>

int main() {
float side1, side2, side3;
printf("Enter the three sides of the triangle: ");
scanf("%f %f %f", &side1, &side2, &side3);

// Check if any side is zero or negative


if (side1 <= 0 || side2 <= 0 || side3 <= 0) {
printf("Invalid input: All sides must be positive.\n");
}
// Check if the sum of any two sides is greater than the third side
else if (side1 + side2 > side3 && side1 + side3 > side2 && side2 + side3 > side1)
{
printf("The triangle is valid.\n");
}
else {
printf("The triangle is not valid.\n");
}

return 0;
}

Q-24. Write a c program to check whether triangle equilateral, isosceles


or scalene triangle.
Solution:

#include <stdio.h>

int main() {
float side1, side2, side3;
printf("Enter the three sides of the triangle: ");
scanf("%f %f %f", &side1, &side2, &side3);
28
// Check if any side is zero or negative
if (side1 <= 0 || side2 <= 0 || side3 <= 0) {
printf("Invalid input: All sides must be positive.\n");
}
// Check if the sum of any two sides is greater than the third side
else if (side1 + side2 > side3 && side1 + side3 > side2 && side2 + side3 >
side1) {
// Check if all sides are equal
if (side1 == side2 && side1 == side3) {
printf("The triangle is an equilateral triangle.\n");
}
// Check if any two sides are equal
else if (side1 == side2 || side1 == side3 || side2 == side3) {
printf("The triangle is an isosceles triangle.\n");
}
// Otherwise, all sides are different
else {
printf("The triangle is a scalene triangle.\n");
}
}
else {
printf("The input does not form a valid triangle.\n");
}

return 0;
}

Q-25. Write a c program to calculate profit or loss.


Solution:

#include <stdio.h>

int main() {
float costPrice, sellingPrice, profit, loss;

printf("Enter cost price: ");


scanf("%f", &costPrice);

printf("Enter selling price: ");


scanf("%f", &sellingPrice);

29
if(sellingPrice > costPrice) {
profit = sellingPrice - costPrice;
printf("Profit = %.2f\n", profit);
} else if(costPrice > sellingPrice) {
loss = costPrice - sellingPrice;
printf("Loss = %.2f\n", loss);
} else {
printf("No profit or loss\n");
}

return 0;
}

Q-26. Write a c program to find all roots of a quadratic equation.


Solution:

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

int main() {
float a, b, c, discriminant, root1, root2, realPart, imaginaryPart;

printf("Enter coefficients a, b, and c: ");


scanf("%f %f %f", &a, &b, &c);

discriminant = b * b - 4 * a * c;

if (discriminant > 0) {
root1 = (-b + sqrt(discriminant)) / (2 * a);
root2 = (-b - sqrt(discriminant)) / (2 * a);
printf("Roots are real and different. Root 1 = %.2f and Root 2 = %.2f", root1,
root2);
} else if (discriminant == 0) {
root1 = -b / (2 * a);
printf("Roots are real and equal. Root 1 = Root 2 = %.2f;", root1);
} else {
realPart = -b / (2 * a);
imaginaryPart = sqrt(-discriminant) / (2 * a);
printf("Roots are complex and different. Root 1 = %.2f + %.2fi and Root 2 =
%.2f - %.2fi", realPart, imaginaryPart, realPart, imaginaryPart); }
return 0;
}

30
Q-27. Write a c program to count total number of notes(money) in given
amount.
Solution:

#include <stdio.h>

int main() {
int amount, notes;

printf("Enter the amount: ");


scanf("%d", &amount);

if(amount >= 2000) {


printf("Notes of 2000: %d\n", amount / 2000);
amount = amount % 2000;
}

if(amount >= 500) {


printf("Notes of 500: %d\n", amount / 500);
amount = amount % 500;
}

if(amount >= 200) {


printf("Notes of 200: %d\n", amount / 200);
amount = amount % 200;
}

if(amount >= 100) {


printf("Notes of 100: %d\n", amount / 100);
amount = amount % 100;
}

if(amount >= 50) {


printf("Notes of 50: %d\n", amount / 50);
amount = amount % 50;
}

31
if(amount >= 20) {
printf("Notes of 20: %d\n", amount / 20);
amount = amount % 20;
}

if(amount >= 10) {


printf("Notes of 10: %d\n", amount / 10);
amount = amount % 10;
}

if(amount >= 5) {
printf("Notes of 5: %d\n", amount / 5);
amount = amount % 5;
}

if(amount >= 2) {
printf("Notes of 2: %d\n", amount / 2);
amount = amount % 2;
}

if(amount >= 1) {
printf("Notes of 1: %d\n", amount);
}

return 0;
}

Condition Based Problem: Switch Case

Syntex of switch case:


switch (expression) {
case constant1:
// code to be executed when expression == constant1
break;
case constant2:
// code to be executed when expression == constant2

32
break;
// more case statements can be added as needed
default:
// code to be executed when none of the above cases are matched
break;
}

Explain: The switch-case statement starts with the keyword switch


followed by a set of parentheses enclosing an expression. The expression
is evaluated, and the value is compared against the constants listed in
the case statements.

If the value of the expression matches a constant, the code associated


with that case statement is executed. The break statement is used to exit
the switch block and prevent execution of the code in subsequent cases.

The default case is executed if none of the constants match the value of
the expression. It is optional and can be omitted if there is no default
behavior required.

Note that the expression used in the switch statement must be an


integer or a character data type.

Q-28. Write a c program to check whether an alphabet is vowel or


consonant using switch case.
Solution:
#include <stdio.h>

int main() {
char ch;

printf("Enter an alphabet: ");


scanf("%c", &ch);

switch(ch) {
case 'a':
printf("%c is a vowel.", ch);
33
break;
case 'e':
printf("%c is a vowel.", ch);
break;
case 'i':
printf("%c is a vowel.", ch);
break;
case 'o':
printf("%c is a vowel.", ch);
break;
case 'u':
printf("%c is a vowel.", ch);
break;
case 'A':
printf("%c is a vowel.", ch);
break;
case 'E':
printf("%c is a vowel.", ch);
break;
case 'I':
printf("%c is a vowel.", ch);
break;
case 'O':
printf("%c is a vowel.", ch);
break;
case 'U':
printf("%c is a vowel.", ch);
break;
default:
printf("%c is a consonant.", ch);
}

return 0;
}

34
Here, we declare a character variable ch to store the alphabet entered by
the user. We prompt the user to enter an alphabet using the printf()
function followed by a call to scanf() function to read the input value.

We then use the switch-case statement to compare the value of ch


against each vowel. If ch matches any of the vowels, we use the printf()
function to display a message indicating that the character is a vowel. If
ch doesn't match any of the vowels, the default case is executed and we
display a message indicating that the character is a consonant.

Finally, we return 0 to indicate that the program has executed


successfully.

Q-29. Write a c program to print day of week name using switch case.
Solution:
#include <stdio.h>

int main() {
int day;

printf("Enter a number between 1 and 7: ");


scanf("%d", &day);

switch(day) {
case 1:
printf("Monday");
break;
case 2:
printf("Tuesday");
break;
case 3:
printf("Wednesday");
break;
case 4:
printf("Thursday");
break;
case 5:
printf("Friday");
break;

35
case 6:
printf("Saturday");
break;
case 7:
printf("Sunday");
break;
default:
printf("Invalid day");
}

return 0;
}

p-p-29. Write a c program to print total number of days in a month using


switch case.

Q-30. Write a c program to find maximum between two number using


switch case.
Solution:

#include<stdio.h>
int main()
{
int x,y;
printf("enter the two number:");
scanf("%d%d",&x,&y);
switch(x>y){
case 1 :
printf("%d is big ",x);
break;
default :
printf("%d is big",y);
break;
}

return 0;
}

p-p-30. Write a c program to find minimum between two number using


switch case.

36
Q-31. Write a c program to check a number is even or odd using switch
case.
Solution:
#include <stdio.h>

int main() {
int num, remainder;
printf("Enter a number: ");
scanf("%d", &num);

remainder = num % 2;

switch (remainder) {
case 0:
printf("%d is an even number.\n", num);
break;
case 1:
printf("%d is an odd number.\n", num);
break;
default:
printf("Invalid input.\n");
}

return 0;
}

Q-32. Write a c program to find roots of a quadratic equation using


switch case.
Solution:
The quadratic equation is of the form ax^2 + bx + c = 0

x = (-b ± sqrt(b^2 - 4ac)) / 2a

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

int main() {
float a, b, c, root1, root2, discriminant;
printf("Enter coefficients a, b, and c: ");
scanf("%f %f %f", &a, &b, &c);
37
discriminant = b * b - 4 * a * c;

switch (discriminant > 0) {


case 1:
root1 = (-b + sqrt(discriminant)) / (2 * a);
root2 = (-b - sqrt(discriminant)) / (2 * a);
printf("Roots are real and different:\n");
printf("root1 = %.2f\n", root1);
printf("root2 = %.2f\n", root2);
break;
case 0:
switch (discriminant == 0) {
case 1:
root1 = root2 = -b / (2 * a);
printf("Roots are real and equal:\n");
printf("root1 = root2 = %.2f\n", root1);
break;
case 0:
printf("Roots are imaginary.\n");
}
break;
}

return 0;
}

Q-33. Write a c program to create simple calculator using switch case.


Solution:
#include <stdio.h>

int main() {
char operator;
float num1, num2, result;

printf("Enter an operator (+, -, *, /): ");


scanf("%c", &operator);

printf("Enter two operands: ");


scanf("%f %f", &num1, &num2);

38
switch (operator) {
case '+':
result = num1 + num2;
printf("%.2f + %.2f = %.2f", num1, num2, result);
break;
case '-':
result = num1 - num2;
printf("%.2f - %.2f = %.2f", num1, num2, result);
break;
case '*':
result = num1 * num2;
printf("%.2f * %.2f = %.2f", num1, num2, result);
break;
case '/':
if (num2 == 0) {
printf("Error: Division by zero!");
} else {
result = num1 / num2;
printf("%.2f / %.2f = %.2f", num1, num2, result);
}
break;
default:
printf("Error: Invalid operator!");
}

return 0;
}

Conditional/Ternary Oparator:

The basic syntax of the conditional operator is:

(condition) ? (expression1) : (expression2)

39
Here, condition is a boolean expression that evaluates to either
true or false. If condition is true, the value of expression1 is
returned. If condition is false, the value of expression2 is returned.
Q-34. Write a c program to find maximum among three number using
ternary operator.
Solution:
#include <stdio.h>

int main() {
int a, b, c, max;

printf("Enter three numbers: ");


scanf("%d %d %d", &a, &b, &c);

max = (a > b) ? (a > c ? a : c) : (b > c ? b : c);

printf("The maximum of %d, %d and %d is %d\n", a, b, c, max);

return 0;
}

Explain: In this program, we first declare three integer variables a, b, and


c to store the three numbers. We then prompt the user to enter these
three numbers using the printf() and scanf() functions.

Next, we use the ternary operator to find the maximum among these
three numbers. We first compare a and b, and if a is greater than b, we
compare a and c to get the maximum. Otherwise, we compare b and c to
get the maximum.

Finally, we print out the maximum value using the printf() function.

40
p-p-34. Write a c program to find minimum among three number using
ternary operator.

Q-35. Write a c program to check whether number is even or odd.


Solution:
Number%2=0 (even)

#include <stdio.h>

int main() {
int num;

printf("Enter a number: ");


scanf("%d", &num);

(num % 2 == 0) ? printf("%d is even.\n", num) : printf("%d is odd.\n", num);

return 0;
}

Q-36. Write a c program to check whether year is leap year or not.


Solution:
Condition of leap year:
year % 4 == 0
year % 100 != 0
year % 400 == 0
#include <stdio.h>

41
int main() {
int year;

printf("Enter a year: ");


scanf("%d", &year);

year % 4 == 0 && year % 100 != 0 || year % 400 == 0 ? printf("%d is a leap


year.\n", year) : printf("%d is not a leap year.\n", year);

return 0;
}

Q-37. Write a c program to check whether character is alphabet or not


using ternary operator.
Solution:
#include <stdio.h>

int main() {
char c;

printf("Enter a character: ");


scanf("%c", &c);
(c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') ? printf("%c is an alphabet.\n",
c) : printf("%c is not an alphabet.\n", c);
return 0;
}

42
p-p-37. Write a c program to check whether a character is lowercase or
uppercase alphabet using ternary operator.

Loop Programming:
Q. What is loop?
In computer programming, a loop is a sequence of instructions that is executed
repeatedly until a certain condition is met. The basic idea of a loop is to allow a block
of code to be executed repeatedly, either a fixed number of times or until a certain
condition is met.

Types of loop:

There are several types of loops, such as for loops, while loops, and do-while loops.

The structure of a for loop:

for (initialization; condition; increment/decrement) {


// code to be executed repeatedly
}

Let's break down the components of a for loop:

initialization: This is where you set an initial value for the loop
variable. This statement is executed only once, at the beginning of
the loop.
condition: This is the condition that is checked at the beginning of
each iteration of the loop. If the condition evaluates to true, the
loop body is executed. If the condition evaluates to false, the loop
exits.
increment/decrement: This statement is executed at the end of each
iteration of the loop, after the loop body has been executed. The
purpose of this statement is usually to modify the loop variable so
that the loop eventually terminates.

43
 code to be executed repeatedly: This is the block of code that will be
executed repeatedly as long as the condition is true .

A for loop is used to iterate over a sequence of values for a specified


number of times.

Example of for loop:


***write a c program to print 1 to 10 using for loop.
#include <stdio.h>

int main() {
for (int i = 1; i <= 10; i++) {
printf("%d ", i);
}
return 0;
}

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

The structure of While loop:


while (condition) {
// code to be executed repeatedly
}

Let's break down the components of a while loop:

 condition: This is the condition that is checked at the beginning of


each iteration of the loop. If the condition evaluates to true, the
loop body is executed. If the condition evaluates to false, the loop
exits.

44
 code to be executed repeatedly: This is the block of code that will be
executed repeatedly as long as the condition is true.
Example of while loop:
*** write a c program to print 1 to 10 using while loop.

#include <stdio.h>

int main() {
int i = 1;
while (i <= 10) {
printf("%d ", i);
i++;
}
return 0;
}

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

The structure of do- While loop:


do {
// code to be executed repeatedly
} while (condition);

Let's break down the components of a do-while loop:

 code to be executed repeatedly: This is the block of code that will be


executed repeatedly, at least once.
 condition: This is the condition that is checked at the end of each
iteration of the loop. If the condition evaluates to true, the loop will

45
continue to execute. If the condition evaluates to false, the loop
exits.

Example of do- while loop:


#include <stdio.h>

int main() {
int i = 1;
do {
printf("%d ", i);
i++;
} while (i <= 10);
return 0;
}

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

Q-38.Write a c program to print all natural number in reverse (from n to


1)-using while loop.
Solution:
#include <stdio.h>

int main() {
int n, i;

printf("Enter a positive integer: ");


scanf("%d", &n);

46
i = n;
while (i >= 1) {
printf("%d ", i);
i--;
}
return 0;
}
p-p-38. Write a c program to print all natural number in reverse (from 1
to n)-using while loop.

Q-39.Write a c program to print all alphabets from a to z – using while


loop.
Solution:
#include <stdio.h>

int main() {
char alphabet = 'a';

while (alphabet <= 'z') {


printf("%c ", alphabet);
alphabet++;
}

return 0;
}

p-p-39. Write a c program to print all alphabets from a to z – using for


loop.

47
Q-40.Write a c program to print of all even numbers between 1 to n.
Solution:
#include <stdio.h>

int main() {
int n;

printf("Enter a positive integer: ");


scanf("%d", &n);

printf("Even numbers between 1 and %d are: ", n);


for (int i = 2; i <= n; i= i+2) {
printf("%d ", i);
}

return 0;
}

p-p-40. Write a c program to print of all odd numbers between 1 to n.

Q-41.Write a c program to print sum of all even numbers between 1 to


n.
Solution:
#include <stdio.h>
int main() {
int n, sum = 0;
printf("Enter a positive integer: ");
scanf("%d", &n);

48
for (int i = 2; i <= n; i = i+2) {
sum =sum+ i;
}
printf("Sum of all even numbers between 1 and %d is %d", n, sum);
return 0;
}

p-p-41.Write a c program to print sum of all odd numbers between 1 to


n.
Q-42.Write a c program to print table of any number.
Solution:
#include <stdio.h>

int main() {
int number;

printf("Enter a positive integer: ");


scanf("%d", &number);

printf("Multiplication table of %d:\n", number);

for (int i = 1; i <= 10; i++) {


printf("%d x %d = %d\n", number, i, number * i);
}

return 0;
}

Q-43.Write a c program to calculate sum of digit of any number.

49
Solution:
#include <stdio.h>

int main() {
int number, digit, sum = 0;

printf("Enter a positive integer: ");


scanf("%d", &number);

while (number > 0) {


digit = number % 10;
number = number/10;
sum = sum+digit;
}

printf("Sum of digits = %d\n", sum);

return 0;
}
Q-44.Write a c program to calculate product of digit of any number.
Solution:

#include <stdio.h>

int main() {
int number, digit, product = 1;

printf("Enter a positive integer: ");


scanf("%d", &number);

50
while (number > 0) {
digit = number % 10;
number = number/10;
product = product*digit;
}

printf("Sum of digits = %d\n", product);

return 0;
}

Q-45.Write a c program to find first and last digit any number.


Solution:

#include<stdio.h>
int main()
{
int n,last_digit;
printf("enter the number:");
scanf("%d",&n);
last_digit =n%10;

while(n>=10){
n=n/10;
}
printf("first digit: %d\n",n);
printf("last_digit: %d\n",last_digit);

51
return 0;
}

Q-46.Write a c program to find the sum of first and last digit any
number.
Solution:
#include<stdio.h>
void main()
{

int last,n,sum=0;
printf("enter the number:");
scanf("%d",&n);
last=n%10;
while(n>=10){
n=n/10;
sum=n+last;
}

printf("the total:%d+%d=%d\n",last,n,sum);

***Basic Idea off ASCII Value:

ASCII (American Standard Code for Information Interchange) is a character


encoding standard that assigns numerical values to each of the 128
characters used in the English language and some control codes.

Each ASCII character is represented by a unique numerical value between 0


and 127, inclusive. For example, the capital letter 'A' is represented by the
value 65, while the lowercase letter 'a' is represented by the value 97.

The ASCII standard includes both printable and non-printable characters.


Printable characters are those that can be displayed on a screen or printed
on paper, such as letters, numbers, and symbols. Non-printable characters

52
are control codes that are used to control devices or formatting, such as
line breaks and tab characters.

Here are a few examples of ASCII values and their corresponding


characters:

 65: 'A'
 97: 'a'
 48: '0'
 32: space character
 9: tab character
 10: newline character

In programming, ASCII values are often used to represent characters in


text-based data, such as strings or input/output operations.

Q-47.Write a c program to print all ASCII character with their value


using while loop.
Solution:
#include <stdio.h>

int main() {
int i = 0;
while(i <= 127) {
printf("%d: %c\n", i, i);
i++;
}
return 0;
}

53
p.p-47. Write a c program to print all ASCII character with their value
using for loop.

Q-48.Write a c program to enter any number and print all factor of


number using for loop.
Solution:
#include <stdio.h>

int main() {
int num, i;
printf("Enter a positive integer: ");
scanf("%d", &num);

printf("Factors of %d are: ", num);


for(i=1; i<=num; i++) {
if(num % i == 0) {
printf("%d ", i);
}
}
return 0;
}
p-p.48.Write a c program to enter any number and print all factor of
number using do while loop.

Q-49.Write a c program to enter any number and calculate its factorial.


Solution:
2! Means 1*2=2
5! Means 1*2*3*4*5=120

#include <stdio.h>

54
int main() {
double num, i;
double factorial = 1;
printf("Enter a positive integer: ");
scanf("%lf", &num);
for(i=1; i<=num; i++) {
factorial =factorial*i;
}
printf("Factorial of %lf = %lf", num, factorial);
return 0;
}
p-p-49.Write a c program to enter any number and calculate its factorial
using while loop.

Q-50.Write a c program to print prime numbers between 1 to n.


**What is prime number?
Ans: A prime number is a positive integer greater than 1 that has no positive integer
divisors other than 1 and itself. In other words, it is a number that is only divisible by
1 and itself. Examples of prime numbers include 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31,
and so on.

Solution:
#include<stdio.h>
int main()
{
int i,n,j;
printf("enter the range:");
scanf("%d ",&n);
for(i=2; i<=n; i++)
{
for(j=2; j<=i; j++)
{

55
if(i%j==0)
break;
}
if(i==j)
printf("%d\n", j);
}
return 0;
}

Q-51.Write a c program to check a number prime or not ?


Solution:
#include<stdio.h>
int main()
{
int i,n;
printf("enter the number:");
scanf("%d" ,&n);
for(i=2; i<n; i++){

if(n%i==0){
printf("%d is not prime",n);
break;
}
}
if(i==n)
printf("%d prime number", n);

return 0;

Q-52.Write a c program to find LCM of two number?


56
Solution:

GCD=greatest common divisor.

LCM= least common multiple.


Num1 * Num2=LCM * GCD

#include<stdio.h>
void main()
{
int n1,n2,num1,num2,r,gcd,lcm;
printf("enter the two number:");
scanf("%d%d",&n1,&n2);
num1=n1;
num2=n2;
while(n2!=0){
r=n1%n2;
n1=n2;
n2=r;
}
gcd=n1;
lcm=num1*num2/gcd;
printf("gcd=%d\n",gcd);
printf("lcm=%d\n",lcm);
}

p-p-52. Write a c program to find GCD of two number?

Q-53.Write a c program to Swap first and last digit of any number


without third veriable.
Solution:
Basic idea of swap number:

57
int a = 10;
int b = 20;
a = a + b; // a now holds the sum of the original values of a and b
b = a - b; // b now holds the original value of a
a = a - b; // a now holds the original value of b
After this code executes, the value of a will be 20 and the value of b will be 10.

#include<stdio.h>
int main()
{
int x,y;
printf("enter the number of x & y:");
scanf("%d%d",&x,&y);
x=x+y;
y=x-y;
x=x-y;
printf("the swap number is x & y:%d %d\n",x,y);
return 0;
}

Q-54. Write a c program to find sum of series 1/1!+2/2!+3/3!+4/4!+……


Solution:

#include<stdio.h>
main()
{
int fact=1,n,i;
float s=0;
printf("enter the number:");
scanf("%d",&n);

58
for(i=1;i<=n;i++){
fact=fact*i;
s= s + i*1.0/fact;

}
printf("the factor:%f", s);
}
Q-55. Write a c program to find sum of series
1+(1+2)+(1+2+3)+(1+2+3+4)+………
Solution:
#include <stdio.h>
int main() {
int n, s=0,s1=0;

printf("Enter the number of terms: ");


scanf("%d", &n);

for (int i = 1; i <= n; i++) {


s =s+i;
s1 =s1+s;
}
printf("Sum of the series: %d\n", s1);
return 0;
}
Q.56.Write a c program to find the sum of the series 1/1!+ 2/2!+ 3/3!+….1/N!.
Solution:
#include<stdio.h>
main()
{
int n,fact=1,i;
float s=0;
printf("enter the number:");

59
scanf("%d",&n);
for(i=1;i<=n;i++){
fact=fact*i;
s=s+(i*1.0)/fact;
}
printf("the sum is:%f",s);
}

Pattern based Problem

Q.57.

*
**
***
****
*****

Solution:
#include<stdio.h>
int main()
{
int i,j,k;
for(i=1;i<=5;i++){
for(j=1;j<=i;j++){
printf("*");
}
printf("\n");
}
}
Q.58.

60
11111
11111
11111
11111
11111

Solution:

#include<stdio.h>
int main(){
int i,j;
for(i=1;i<=5;i++){
for(j=1;j<=5;j++){
printf("1");
}
printf("\n");
}
}

Q.59.

1
12
123
1234
12345

Solution:

61
#include<stdio.h>
void main()
{
int n,row,col;
printf("Enter the Range=");
scanf("%d",&n);
for(row=1;row<=n;row++){
for(col=1;col<=row;col++){
printf("%d",col);
}
printf("\n");
}
}

Array and matrix based problem

In C programming, an array is a collection of elements of the same data type, stored


in contiguous memory locations. Each element in an array can be accessed using an
index, which starts from 0 and goes up to the array size minus one. Arrays are widely
used for storing and manipulating a group of related data items efficiently. Here are
some key points to understand about arrays in C:

Declaration: To declare an array in C, you specify the data type of the elements and
the size of the array. The syntax is as follows:

data_type array_name[array_size];

Q.60-

62

You might also like