0% found this document useful (0 votes)
16 views54 pages

Unit 1 (Notes)

Uploaded by

nickluck64
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views54 pages

Unit 1 (Notes)

Uploaded by

nickluck64
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 54

UNIT 1: Introduction to Problem Solving and C Programming

→ Programs and Algorithms


→ Computer Problem Solving Requirements
→ Phases of Problem Solving
→ Problem Solving Strategies
→ Top-Down Approach
→ Algorithm Designing
→ Introduction of C programming
→ Structure of C program
→ Primitive Data Types
→ Variables and Constants
→ Basic Input and Output
→ Operators
→ Expression Evaluation
→ Type Conversion

 Programs and Algorithms:

What is a Program?
A program is a set of instructions that are executed by the computer to perform a particular
task.
Programs are written using programming languages such as C, C++, JAVA, PYTHON
and are executed by the computer.

What is a Programming?
The process of writing, testing and maintaining those instructions.

Types (Categories) of Programming Language:


1. Low-Level Programming Language: A low-level language is close to machine
language and directly understood by the computer’s CPU.
Types of Low-Level Programming Languages:
→ Machine Language (0s and 1s)
→ Assembly Language (uses mnemonics like MOV, ADD)

2. High-Level Programming Language: A High-Level Language is a programming


language that is closer to human language (English-like syntax). They must be
translated into machine language using compilers or interpreters before execution.
Types of High-Level Programming Languages:
→ Procedural Programming Language (C, Pascal, Fortran)
→ Object-Oriented Programming Language (C++, Java, Python)
→ Scripting Programming Language (JavaScript, PHP, Perl)
What is an algorithm?
An algorithm is a step-by-step procedure or set of well-defined rules or instructions to
solve a given problem or accomplish to perform a specific task.

What is problem solving?


The process of finding solution to the given problem and implementing with effective
solution is known as problem solving.

 Computer Problem Solving Requirements:


1. Analytical Thinking (Understanding):
Analytical thinking involves finding what is the root cause of the problem and
identifying probable solutions to the problem and if a complex problem is there, then
break it down to small components so that we can solve the problem easily.

2. Information Gathering:
To solve many problems, we need to gather or collect relevant data, information, facts
and resources about the problem so that it can help in understanding the problem better.
3. Creative Thinking:
Solving problems often require creative thinking to come up with new and innovative
solutions.

4. Decision Making:
When there are multiple solutions to a given problem, we need to find the pros
(advantages) and cons (disadvantages) of all solutions and then make a decision to pick
the best solution. Selecting the most effective and practical solution from the options
available.

5. Algorithm Design:
Develop a clear and efficient algorithm to solve the problem.

6. Test Cases:
A test case is set of actions that can be done on different inputs given to the
problem and test how the output is generated, works correctly or not for the given
input.
Test cases are specific conditions or sets of inputs used to test whether a software
application or system behaves as expected.
 Phases of Problem Solving:
1. Problem Definition:
Before solving any problem, first we need to know the exact nature of the problem or
understand what the problem is?
We need to extract the problem statement (identifying and clearly defining the exact
problem). If the problem statement isn’t specified correctly, then we don’t know where
to begin from? to resolve the problem, which will result in wrong solution.

2. Design The Algorithm:


Develop an algorithm that describes the detailed steps to solve the problem. An
algorithm can be written in pseudo code (consists of simple English sentences written
step by step to solve the problem).

3. Getting Started on The Problem:


There are many ways to solve a given problem and hence many solutions exist for the
given problem, only some of them will be correct solutions and others will be wrong
solutions. So, we have to judge solution wisely(correctly).

4. Evaluating and selecting best solution:


In trying to get a best solution for the problem, programmers may choose forward
approach or backward approach to solve the problem, we have to choose the wise
approach.
Forward Approach: The "forward approach" in problem-solving, involves starting
from the initial conditions or base state and systematically working towards
generating the desired output or solution.
Backward Approach: The "backward approach" in problem-solving, involves
starting with the final solution or end goal and work backwards to determine the
necessary steps to reach that state from the initial conditions.

5. Implementation:
This phase involves coding (writing programs using a programming language like C).

6. Testing:
We should test whether our solution to a problem is correct or not by providing
different inputs and getting the outputs or results correctly.
 Problem solving Strategies:
Number of strategies can be applied in computer science field to solve the problem and
measure how efficiently the solution is working. Probably the most and widely used
strategy is top-down approach (Divide and Conquer).

Top-down approach (Divide and Conquer):


The basic idea with this strategy is divide the original problem (large problem) into
two or more sub problems and then solve the sub problems to get the solution for the
given original problem.
This way of breaking down the solution to a problem is widely used in sorting
techniques and searching techniques.

Bottom-Up approach:
This is the exact opposite of the Divide and Conquer approach (top-down approach).
In this approach, we begin by solving smaller or sub-problems first and then we
integrate or combine these small sub-problems to find the solution to the large problem
or the original problem.

 Top-Down Approach:
Top-Down approach of solving a problem can be implemented by using the following
steps:

1. Breaking a problem into sub problems:


This step involves break down the given task into sub tasks and then further divide the
sub task into smaller sub tasks and continue this fashion of splitting. For most
algorithms we need two or three levels of splitting the problem.

2. Choice of suitable data structure:


Sometimes, while solving a problem we need to select appropriate data structure for
solving the problem. For instance, if you need to store a collection of values (e.g., set
of names of students in a class, set of roll numbers of students in a problem, etc.) or
matrix values in a problem, then choose a data structure like array.

3. Construction of loops:
→ A looping construct is a programming structure that allows tasks to be repeated a
specific number of times or until a certain condition is met.
→ Many problems that need to solved requires loops in programming, so we have to
use or construct loop to solve the problem.
→ For example, to create a sequence of numbers such as 1, 2, 3, 4, 5 ........or to generate
even numbers like 2, 4, 6, 8, 10..... , we need to use the idea of loops to solve these
types of problems.
 Algorithm Designing:
When designing an algorithm, it is important to be very careful and consider the following
factors.

1. The algorithm steps should be short and very clear.


2. Test the efficiency of the algorithm. i.e., check how good the algorithm works for the
given inputs?
3. Algorithm should be cost effective in terms of amount of time it takes to solve the
problem and computer storage(memory) it requires.

 Flowchart:
A flowchart is a graphical / diagrammatic used to represent an algorithm, that visually
explains about the process or workflow using standardized symbols and definitions.

Flowchart symbols:

Terminal (Oval):
An oval in a flowchart represents the terminal. It is used to represent the start or end of
a process / sequence. It is used to show the beginning or the termination point of the
flowchart.

Input/Output (Parallelogram):
The parallelogram represents data input to or output from the process. It is used to show
the way it takes input (e.g., user input, data entry) or give output (e.g., displaying results,
printing).

Process (Rectangle):
The rectangle represents a process or action step in the flowchart. It is used to show any
step in the process, such as calculations, data processing, or other tasks.
Decision Making (Rhombus/Diamond):
The diamond represents a decision point or a conditional branch. It is used to indicate
that a choice must be made between different paths based on certain conditions or
criteria.

Flowline (Arrow):
The arrow represents the direction of flow from one step to the next step. Connects
symbols to show the sequence of steps.

Example to understand an algorithm and flowchart:


1. Write an algorithm and flowchart to print the text message “Hello World”.
Sol:
Algorithm:
Step1: start/begin the algorithm.
Step2: print text message “Hello World” on the screen.
Step3: stop/end the algorithm.

Flowchart:

start

print “Hello World”

stop
2. Write an algorithm and flowchart to perform the addition of two numbers.
Sol:
Algorithm:
Step1: start algorithm
Step2: declare num1, num2 and add.
Step3: input/read num1 and num2. // Input
Step4: add = num1 + num2 // Process
Step5: display the result (add). // Output
Step6: stop algorithm

Flowchart:

start

declare num1,
num2 & add

input/read num1,
num2

add = num1 + num2

print/display add

stop
3. Write an algorithm and flowchart to find area of rectangle.
Sol:
Algorithm:
Step1: start algorithm
Step2: declare length, breadth and area.
Step3: input/read length and breadth. // Input
Step4: area = length * breadth // Process
Step5: display the result (area). // Output
Step6: stop algorithm

Flowchart:

start

declare length,
breadth and area

input/read length
and breadth

area = length * breadth

print/display area

stop
4. Write an algorithm and flowchart to find area of circle.
Sol:
Algorithm:
Step1: start algorithm
Step2: declare pi, radius and area.
Step3: input/read pi and radius. // Input
Step4: area = pi * radius *radius // Process
Step5: display the result (area). // Output
Step6: stop algorithm

Flowchart:

start

declare pi, radius


and area

input/read pi and
radius

area = pi * radius *radius

print/display area

stop
5. Write an algorithm and flowchart to check whether the given number is even or odd.
Sol:
Algorithm:
Step1: start algorithm
Step2: declare num.
Step3: input/read num.
Step4: check num%2==0
print “even number”
Step5: otherwise
print “odd number”
Step6: stop algorithm

Flowchart:

start

declare num

input/read num

check NO
num%2==
0

YES

print even number print odd number

stop
6. Write an algorithm and flowchart to check whether the given year is leap year or not.
Sol:
Algorithm:
Step1: start algorithm
Step2: declare year.
Step3: input/read year.
Step4: check year%4==0
print “leap year”
Step5: otherwise
print “not leap year”
Step6: stop algorithm

Flowchart:

start

declare year

input/read year

check NO
year%4==0

YES

print leap year print not leap year

stop
7. Write an algorithm and flowchart to find largest among the two numbers.
Sol:
Algorithm:
Step1: start algorithm
Step2: declare num1 and num2.
Step3: input/read num1 and num2.
Step4: check num1>num2
print “num1 is greater”
Step5: otherwise
print “num2 is greater”
Step6: stop algorithm

Flowchart:

start

declare num1 and num2

input/read num1 and num2

Check NO
num1>num
2

YES

print num1 is greater print num2 is


greater

stop
 Introduction of C programming:
C programming is a general-purpose, procedural programming language was developed
by Dennis M. Ritchie in the year 1972 at the location bell laboratories (AT &T - American
Telephone and Telegraph) labs.

Why should we Learn C Program?


1. C is easy to learn and simple to understand the fundamentals.
2. C is a structured programming language. Learning C can help developers better
understand programming concepts such as an array, functions, structures, pointers.
3. It is used to develop standalone applications (desktop applications) because C is a
platform dependent.
4. C is extensively used in embedded programming. Embedded programming is also
referred to as micro-controller programming, where C program is used to control
micro-controllers.
5. Programs written and compiled in C execute much faster than compared to any other
programming language.
6. It is used in system programming development, operating system, scientific
computing, game, multimedia development and networking.

Facts about C Programming:


1. C was mainly developed as a system programming language to write the UNIX
operating system.
2. C is a successor of B language which was introduced around the early 1970s.
3. The language was formalized in 1988 by the American National Standard Institute
(ANSI).
4. Dennis M. Ritchie developed C using the features, fundamentals of BCPL (Basic
Combined Programming Language) and B language.
5. C is a compiled programming language, C programs are typically written in human-
readable source code and then compiled into machine code using a compiler.

 Structure of C Program:
→The structure of the C program is divided into several key components and elements
which makes it easy to read, modify, document and understand how well a C program
is organized.
→C program is a collection of one or more functions.
→Every function is a collection of statements that performs some specific tasks.

C program typically has the following structure:


1. Documentation (Comments)
2. Preprocessor Directives (Header Files and Macro Definitions)
3. Global Declarations
4. main() Function
{
Local Declarations
Statements (Executable Part)
}
5. Functions (pre-defined and user-defined)

1. Documentation (Comments):
→ Comments are used for documentation and clarification.
→ In any C program, comments won’t be considered for compilation and execution.
→ C supports both the single-line comments (//) & the multi-line comments (/* ... */).

2. Preprocessor Directives:
→Preprocessor directives in C are the commands used by the preprocessor, that tell
the compiler to process the source code before beginning the actual compilation
process. All the preprocessor directives begin with a ‘#’ (hash) symbol. The
commonly used preprocessor directives are #include and #define.

#include is used for including header file in the source code program.

Syntax for file inclusion directive:


#include “filename” or #include

Example:
#include<stdio.h>: It is used to include contents of the standard input/output (I/O)
library header file “stdio.h” in a c program. The functions like printf(), scanf(),
fprintf(), fscanf(), fgets(), fputs() allows you to perform input and output operations in
your C program.

#include<conio.h>: It is used to include contents of the console input/output library


header file “conio.h” in a c program. The functions like clrscr(), getch(), textcolor(),
gotoxy() allows you to perform console input and output operations in your C program.

#include<math.h>: It is used to include contents of the math header file “math.h” in


a c program. The functions like sqrt(), pow(), sin(), cos(), abs(), fabs() allows you to
perform mathematical calculation in your C program.

#include<string.h>: It is used to include contents of the string header file “string.h”


in a c program. The functions like strcpy(), strcat(), strlen(), strcmp() allows you to
perform string manipulation in your C program.

#include<stdlib.h>It is used to include contents of the standard library header file


“stdlib.h” in a c program. The functions like malloc(), calloc(), realloc(), free() allows
you to perform memory allocation, type conversion in your C program.
#define is used to define symbolic constants and macros.

Syntax:
#define macro_name value

Example:
#define PI 3.14159
Here, PI is a symbolic constant that represents the value of pi (3.14159). Once defined,
the value of PI cannot be changed during program execution.
Note: Remember that the # symbol only provides a path to the preprocessor.

3. Global Declarations: Variables, constants or functions declared outside the main( )


function. Accessible throughout the program.

4. main( ) function:
→ Every C program must have one main( ) function, where program execution begins.
→ Statements in the main( ) function are executed one by one.
→ Statements typically end with a semicolon (;).
Note:
void main( ) tells the compiler that the program will not return any value.
int main( ) tells the compiler that the program will return an integer value.

Inside main( ) function:


Local Declarations: Variables declared inside main( ) function.
Statements: An instruction that tells the computer to perform a specific action.

5. Functions (Pre-defined and User-defined):


→Functions are blocks of code that perform specific tasks. They can be defined and
called within the program.
Types of Functions:
Pre-defined (Library or Inbuilt) Functions: Functions already written and
provided by the C standard library. You can directly use them by including the proper
header file.
User-defined functions: Functions written by the programmer to divide a program
into smaller tasks. They improve readability and reusability.
Example to understand the structure of C program:
/* C program to understand the concept of
structure of C program */
#include<stdio.h> // Preprocessor Directive
#define a 10 // Macros / Symbolic Constants (optional)

void display(); // Function Prototype/Declaration

int main()
{
printf("%d\n", a); // Print the value of the constant 'a'
display(); // Function Call
return 0; // return 0 to indicate successful execution
}

// Function Definition
void display()
{
printf("Learning C Programming");
}

 Elements in C:
→ Every programming language has some basic elements and grammatical rules.
→ Before understanding the programming, a programmer must to know the basic
elements of C language.
→The basic elements in C are Character Set, Identifiers, Keywords (Reserved Words),
Datatypes, Variables, Constants, Operators, Expressions, Statements and so on, all
these are used to construct a C program.

Note: In the C programming language, C Tokens are the smallest individual units in
the source code. C Tokens are used to represent the various elements of a program.

1. C Character Set:
→ In C programming, a character set refers to the collection of valid characters that
can be used to write source code.
→ These characters include alphabets, digits, special symbols, whitespace and escape
sequence character.

Types of Character Sets in C:


→ Alphabets: Uppercase (A–Z) and Lowercase (a–z)
→ Digits: 0 – 9
→ Special Characters: ~ ! @ # % ^ & * ( ) - _ = + { } [ ] | \ : ; " ' < >
, . ? /
→ Whitespace: space, tab space and newline
→ Escape Sequence Character: \n, \t, \\, \", \', \a, \b, \?, \0

Note:
→ Semicolon (;) is used to terminate statements in C.
→ Comma (,) is used to separate multiple statements.
→ Braces{ } is used to define block of code and to enclose the body of functions, loops
and conditional statements.
→ Parentheses ( ) is used for function calls and function parameters.
→ Quotes ' and " is used to define character (') and string literals (").

2. C Keywords (Reserved Words):


→ In C Programming, Keywords are predefined and reserved words used by the
compiler to perform a specific task.
→ They cannot be used as identifiers (variable names, function names, etc.).
→ Always written in lowercase.
Total 32 keywords in C (ANSI C standard).
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

3. C Identifiers:
→ Identifiers are user-defined names given to program elements such as variables,
arrays, functions, structures, etc. They make the code more readable and
manageable.

Rules for Naming Identifiers:


→ Can contain alphabets (a–z, A–Z), digits (0–9) and underscore (_) only.
→ The first character must be an alphabet or underscore (_).
→ Keywords cannot be used as identifiers.
→ It must not contain whitespaces (spaces and tabs).
→ C is case-sensitive language.
→ For example, "code", "Code" and "CODE" are three different identifiers.

Example of Valid Identifiers:


x
_rollno
num1
Sum
totalmarks
max_value
area
rec12
data1_
Example of Invalid Identifiers:
123var (The first character should be an alphabet or underscore)
rec@1 (The '@' character is not allowed)
my$var (The '$' character is not allowed)
for (Because "for" is a keyword/looping in C)
int (Because "int" is a keyword/ datatype in C)
switch (Because "switch" is a keyword/condition in C)
student name (Blank spaces are not permitted in identifier names)

4. C Data Types:
→ A data type defines the type and size of data that a variable can store.

In C, data types are mainly divided into:


1. Primitive (Fundamental/Pre-defined) data types are used to store single values.

void: The void data type has no values and no operations, used in functions and
pointers.
Key Point: In standard C, sizeof(void) is invalid and results in a compilation error
because void is an incomplete type. Some modern compilers may allow it as an
extension and return 1 byte, but this is non-standard behaviour.

char: The char data type is used to store a single character.


Size: 1 byte (8 bits)
Example: 'A', '9', '$'

int: An Integer data type is used to store numbers (positive, negative, or zero)
without fraction part.
Size: 2 bytes (16 bits) or 4 bytes (32 bits)
Example: 10, -25, 0

float: The float data type is used to store decimal values (fractional numbers).
Size: 4 bytes (32 bits)
Example: 3.14, -0.001, 2.71828

double: The double data type is used to store decimal values with higher precision
than float.
Size: 8 bytes (64 bits)
Example: 3.14159265358979, -0.0000001, 3.579e-13 (3.579*10-13)
Example1: C program to display size of data types.
Code:
#include<stdio.h>
int main()
{
printf("Size of char: %zu byte\n", sizeof(char));
printf("Size of int: %zu bytes\n", sizeof(int));
printf("Size of float: %zu bytes\n", sizeof(float));
printf("Size of double: %zu bytes\n", sizeof(double));
return 0;
}

Example2: C program to display size of variables.


Code:
#include<stdio.h>
int main()
{
char a;
int b;
float c;
double d;
printf("Size of a: %zu byte\n", sizeof(a));
printf("Size of b: %zu bytes\n", sizeof(b));
printf("Size of c: %zu bytes\n", sizeof(c));
printf("Size of d: %zu bytes\n", sizeof(d));
return 0;
}

Note: The sizeof operator in C is used to find the size (in bytes) of a data type or
variable. It’s very useful for beginners to understand how much memory each type
takes.

2. Non-Primitive (Derived/User-defined) Data Types are used to store multiple values


or define customized data structures.

Example: arrays, structures, strings, functions, pointers, union, enum

Data Type Qualifiers in C:


→ Type qualifiers can be used with these basic data types to create more specific types.
There are two main types of type qualifiers:
→ Size Qualifiers: These include short and long, which affect the size of the data type.

→ Sign Qualifiers: These are signed and unsigned. When the unsigned qualifier is
used, the number is always positive. When signed qualifier is used, the number can
be either positive or negative. If no sign qualifier is mentioned, by default, the signed
qualifier is assumed.

The following table describes about datatype with type qualifiers, format
specifiers, size and range:

Size(bytes)
With Type Format
Datatype on Range
Qualifiers Specifier
64-bit
char %c 1 byte -128 to 127
char signed char %c, %hhd 1 byte -128 to 127
unsigned char %c, %hhu 1 byte 0 to 255
signed short int
%hd 2 bytes -32768 to 32767
or short int
unsigned short int %hu 2 bytes 0 to 65535
-2,147,483,648 to
signed int or int %d 4 bytes 2,147,483,647
int
unsigned int %u 4 bytes 0 to 4,294,967,295
signed long int or -2,147,483,648 to
%ld 4 bytes
long int 2,147,483,647
unsigned long int %lu 4 bytes 0 to 4,294,967,295
1.2E-38 to
float float %f 4 bytes
3.4E+38
2.3E-308 to
double %lf 8 bytes 1.7E+308
double
3.4E-4932 to
long double %Lf 16 bytes
1.1E+4932
5. C Variables:
→ In C programming, a variable is a named memory location used to store data that
your program can manipulate. Each variable has a type, which determines what kind
of data it can hold (like integers, floating-point numbers, or characters).

Rules for Naming Variables:


→ Names must start with alphabet or underscore (_).
→ Names can contain alphabets, digits, and underscores.
→ Names are case-sensitive (age and Age are different).
→ Cannot use C keywords (like int, for, return) as variable names.

Variable Declaration: Before using a variable, you must declare it by specifying its
data type and name.
Syntax: datatype variable_name;
or
datatype variable_name1, variable_name2, variable_nameN;

Example:
int width, height;
char grade;
float area;
double salary;

C program to understand how to declare a variable.


Code:
#include<stdio.h>
int main()
{
int age; // integer variable
float salary; // floating-point variable
char grade; // character variable
printf("%d\n", age);
printf("%f\n", salary);
printf("%c", grade);
return 0;
}

Note: If you try to print a local variable without initializing it, it will show a garbage
value (random numbers or characters from memory).
Variable Initialization: Assigning an initial value to a variable at the time of
declaration.

Syntax: datatype variable_name=value;


Or
datatype variable_name1=value1, variable_name2=value2, variable_nameN=valueN;

Example:
int n = 5;
int x = 10, y = 20, z = 30;
char grade = ‘A’;
float age = 34.5;
double salary = 96570.75;
double num = 0.15197e-7;

C program to understand how to initialize a value to variable before


compilation (compile-time).
Code:
#include<stdio.h>
int main()
{
int num=10; // num is intialized the value 10
printf("Entered Number: %d\n", num); // prints the value of num
return 0;
}

C program to understand how to initialize a value to variable during program


execution (run-time).
Code:
#include<stdio.h>
int main()
{
int num; // declare an integer variable named num.
printf("Enter a Number: "); // Prompt the user to enter a number.
scanf("%d", &num); // Read the user's input and store it in num.
printf("Entered Number: %d\n", num); // Print the value entered by the user.
return 0;
}
6. C Constants:
→ In C programming, a constant is a value that cannot be altered or modify by the
program during execution. Once defined, its value remains fixed throughout the
lifetime of the program.

Types of Constants in C:
Char Constants:
→ A single character enclosed in single quotes.
Example: 'A', '1', '\n'

Integer Constants:
→Whole numbers without a fractional part.
→Can be written in different number systems.

Binary (base2):
Prefix: 0b or 0B
Digits allowed: 0 and 1 only
Example:
int bin = 0b1010;
Octal (base 8):
Prefix: 0 (zero at the beginning)
Digits allowed: 0–7
Example:
int oct = 021;

Decimal (base 10):


Default number system (if no prefix is given).
Digits allowed: 0–9
Example:
int a=10;
int b=-199;
int c=0;

Hexadecimal (base 16):


Prefix: 0x or 0X
Digits allowed: 0–9, A–F or a–f
Example:
int hex = 0x1AD5;
C program to understand the concept of integer constants with different
number system.
Code:
#include<stdio.h>
int main()
{
int bin = 0b10101010; // binary
int oct = 0752; // octal
int dec = 916; // decimal
int hex = 0x11bA; // hexadecimal
printf("%d\n", bin);
printf("%d\n", oct);
printf("%d\n", dec);
printf("%d\n", hex);
return 0;
}

Suffixes used in C to explicitly control the type of integer constants.

Type Suffix Example Value Explanation


int none 100 Default integer
Large value that doesn’t fit in
unsigned int U or u 4000000000U
signed int
Value bigger than signed 32-bit
long int L or l 2147483648L
int
unsigned long Large positive value for
UL or ul 4000000000UL
int unsigned long
long long int LL or ll 9223372036854775807LL Max signed 64-bit value
unsigned long
ULL or ull 18446744073709551615ULL Max unsigned 64-bit value
long int

C program to demonstrate integer constants with different types of suffixes.


Code:
#include<stdio.h>
int main()
{
int a=100; // default int
unsigned int b=4000000000U; // unsigned int
long int c=2147483648L; // long int
unsigned long d=4000000000UL; // unsigned long
long long int e=9223372036854775807LL; // long long int
unsigned long long f=18446744073709551615ULL; // unsigned long long int
printf("a = %d\n", a);
printf("b = %u\n", b);
printf("c = %ld\n", c);
printf("d = %lu\n", d);
printf("e = %lld\n", e);
printf("f = %llu\n", f);
return 0;
}

Real (floating point) Constants:


→ A floating-point constant (also called a floating-point literal) is a numeric constant
that represents a real number. It can have:

1. Fractional form
→ A number with a decimal point.
Examples:
0.5, 5.3, -4000.0, 0.0073, -5597.0, 39.0807, 735.0

2. Exponent (scientific) form


→ Used to represent very large or very small numbers.
Examples:
2.3 e5 // 2.3 × 10^5 = 230000.0 (type double by default)
2.4 e-9L // 2.4 × 10^-9 (type long double)

Suffix Type
f or F float
l or L long double
none double (default)

C program to understand the concept of floating Constants with different types


and suffixes.
Code:
#include<stdio.h>
int main()
{
float m = 3.52F;
double n = 2.3e5;
long double p = 2.4e-9L;
printf("%f\n", m);
printf("%lf\n", n);
printf("%Lf\n", p);
return 0;
}
String Constants:
→ A string constant is a sequence of a character enclosed within double quotes (" ").
→ At the end of string, \0 is 'automatically placed by the compiler.
→ A string constant has zero, one or more than one character.

Some examples of string constants are: "C Programming", "59.7", "8", " ", "A"

Note: "A" and 'A' are different, the first one is a string constant which consists of
character A. While the second one is a character constant which represents integer
value 65.

C program to understand the concept of String Constants and how to declare.


Code:
#include<stdio.h>
int main()
{
char text1[20]="C Programming";
printf("%s\n", text1);
return 0;
}
 C Operators:
→ An operator is a symbol that instructs the compiler to perform a specific operation on
operands.
→ Operand means a data item (variable or constant value) on which the operator acts.

→ Unary Operators act on one operand only.


Example: -a, !b, ++x, --y

→Binary Operators act on two operands only.


Examples: +, -, *, /, %, ==, !=, <, >, &&, ||

→Ternary Operator act on three operands.


Example: ?:

Types of Operators in C:
1. Arithmetic operators
2. Relational operators
3. Assignment operators
4. Logical operators
5. Bitwise operators
6. Conditional operator
7. Comma operator
8. sizeof operator
9. Increment and Decrement operators

1. Arithmetic Operators
→ Arithmetic operators are used to perform mathematical calculation.

Operator Description Example


+ Addition a+b
- Subtraction a-b
* Multiplication a*b
/ Division a/b
% Modulus (remainder) a%b

C program to perform arithmetic operations on two operands.


Code:
#include<stdio.h>
int main()
{
int a, b, sum, sub, mul, div, mod;
printf("Enter value of a and b: ");
scanf("%d %d", &a, &b);
sum = a + b;
printf("Addition = %d\n", sum);
sub = a - b;
printf("Subtraction = %d\n", sub);
mul = a * b;
printf("Multiplication = %d\n", mul);
div = a/b;
printf("Division(Quotient) = %d\n", div);
mod = a % b;
printf("Modulus(Remainder) = %d\n", mod);
return 0;
}

2. Relational Operators:
→ Compare two values and return 1 (true) or 0 (false).

Operator Description Example


== Equal to a == b
!= Not equal a != b
> Greater than a>b
< Less than a<b
>= Greater than or equal a >= b
<= Less than or equal a <= b

C program to perform relational operations.


Code:
#include<stdio.h>
int main()
{
int x = 15, y = 20;
printf("%d==%d: %d\n", x, y, x==y); // Equal to
printf("%d!=%d: %d\n", x, y, x!=y); // Not equal to
printf("%d>%d: %d\n", x, y, x>y); // Greater than
printf("%d<%d: %d\n", x, y, x<y); // Less than
printf("%d>=%d: %d\n", x, y, x>=y); // Greater than or equal
printf("%d<=%d: %d\n", x, y, x<=y); // Less than or equal
return 0;
}
3. Assignment Operators:
→ Assign values to variables.

Operator Description Example


= Assign a=b
+= Add and assign a += b → a = a + b
-= Subtract and assign a -= b → a = a - b
*= Multiply and assign a *= b → a = a * b
/= Divide and assign a /= b → a = a / b
%= Modulus and assign a %= b → a = a % b

C program to understand assignment operators.


Code:
#include<stdio.h>
int main()
{
int a=10, b=50;
printf("Initial values of a=%d, b=%d\n", a, b);
printf("a=%d\n", a=b);
printf("b=%d\n", b+=a);
return 0;
}

4. Logical Operators:
→ Operate on Boolean values (true / false).

Operator Symbol Description


AND && Returns true if both operands are true
OR || Returns true if single operand is true
NOT ! Returns the opposite Boolean value

C program to understand logical operators.


Code:
#include<stdio.h>
int main()
{
int a=15, b=15, c=20, res1, res2, res3;
res1= (a==b)&&(c>b);
printf("%d\n", res1);
res2= (a!=b)||(c<=b);
printf("%d\n", res2);
res3= !(a==b);
printf("%d\n", res3);
return 0;
}

Example2:
#include<stdio.h>
int main()
{
int a = 15, b = 15, c = 20, res1, res2;
res1 = (a==b)||(c>b)&&(a<b);
printf("%d\n", res1);
res2 = (a!=b)&&(c<=b)||(a>b);
printf("%d\n", res2);
return 0;
}

5. Bitwise Operators:
→ Operate on individual bits of integers.

Operator Symbol Description


& Performs AND on each bit. Result bit is 1 only if
Bitwise AND
both bits are 1.
| Performs OR on each bit. Result bit is 1 only if at
Bitwise OR
least one bit is 1.
^ Performs XOR on each bit. Result bit is 1 if the bits
Bitwise XOR
are different.
Bitwise ~ Inverts all bits (1 → 0, 0 → 1). Works as one’s
complement complement.
<< Shifts bits to the left, filling with zeros on the right.
Shift left
Equivalent to multiplying by 2^n.
>> Shifts bits to the right. For positive numbers, fills
Shift right
left bits with 0. Equivalent to dividing by 2^n.

p Q p&q p|q p^q


0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
Example:
#include<stdio.h>
int main()
{
int a = 12, b = 25;
printf("Output = %d\n", a & b); // 8 as result
printf("Output = %d\n", a | b); // 29 as result
printf("Output = %d\n", a ^ b); // 21 as result
printf("Output = %d\n", a << 2); // 48 as result
printf("Output = %d\n", b >> 3); // 3 as result
return 0;
}

Explanation:
a = 12 // 12 integer value converted into binary value 00001100
b = 25 // 25 integer value converted into binary value 00011001

a & b means 00001100


00011001

00001000 // 8

a | b means 00001100
00011001

00011101 // 29

a ^ b means 00001100
00011001

00010101 // 21

a << 2 means 00001100 (Shifting two bits left side)


00110000 // 48

b >> 3 means 00011001 (Shifting three bits right side)


00000011 // 3

6. Conditional Operator (?:)


→ The conditional operator is the only ternary operator in C (it works on three
operands).
→ It is a shorthand form of the if...else statement.

Syntax: (condition)? expression1:expression2;


→ If condition is true (non-zero) → expression1 is executed.
→ If condition is false (zero) → expression2 is executed.

Example1:
#include<stdio.h>
int main()
{
int a=10, b=20;
int max;
max=(a>b)? a:b; // if a > b, max = a; else max = b
printf("Maximum = %d\n", max);
return 0;
}

Example2:
#include<stdio.h>
int main()
{
int a = 29, b = 15, result;
result = (a==b)? (a+b) : (a-b);
printf("result = %d", result);
return 0;
}

Example3:
#include<stdio.h>
int main()
{
int num1, num2;
printf("Enter Num1 & Num2:");
scanf("%d %d", &num1, &num2);
(num1>num2)? printf("%d is Largest", num1) : printf("%d is Largest", num2);
return 0;
}

7. Comma Operator:
→ The comma operator (,) is used to separate expressions in various contexts.
→ It evaluates each of its operands (from left to right) and returns the value of the
rightmost operand.
→ The comma operator has the lowest precedence among C operators.

8. sizeof Operator:
→ The sizeof operator is used to determine the size, in bytes, of a data type or a
variable.
Syntax: sizeof(type);
Or
sizeof(expression);

Example:
#include<stdio.h>
int main()
{
printf("Size of int: %zu bytes\n", sizeof(int));
printf("Size of float: %zu bytes\n", sizeof(float));
printf("Size of char: %zu bytes\n", sizeof(char));
return 0;
}

9. Increment and Decrement Operators:


→ There are two operators increment (++) and decrement (--), these are unary
operators because they operate on a single operand.
→ The increment operator (++) increments the value of the variable by 1 and
decrement operator (--) decrements the value of the variable by 1.

++x or x++ is equivalent to x = x + 1


--x or x-- is equivalent to x = x – 1
Note:
→ These operators should be used only with variables; they can't be used with
constants or expressions.
→ For example, the expressions ++5 or ++(x + y + z) are invalid.

These operators are of two types


a) Prefix increment / decrement operator is written before the operand.
(e.g. ++x or --x)
b) Postfix increment / decrement operator is written after the operand.
(e.g. x++ or x--)
Example1:
#include<stdio.h>
int main()
{
int x=5, y;
y = ++x;
printf("x=%d\ty=%d", x, y);
return 0;
}
Explanation:
Here first the value of variable x is increment then the new value is used in the
operation.
Initially x = 5
x=x+1
x=5+1
x=6
Then, the value of x is assigned to y.
y=x
y=6
Hence now value of x is 6 and value of y is 6.

Example2:
#include<stdio.h>
int main()
{
int x=5, y;
y = --x;
printf("x=%d\ty=%d", x, y);
return 0;
}
Explanation:
Here first the value of variable x is decrement then the new value is used in the
operation.
Initially x = 5
x=x-1
x=5-1
x=4
Then, the value of x is assigned to y.
y=x
y=4
Hence now value of x is 4 and value of y is 4.
Example3:
#include<stdio.h>
int main()
{
int x=5, y;
y = x++;
printf("x=%d\ty=%d", x, y);
return 0;
}
Explanation:
Here first the value of variable x is used in the operation and then increment is
performed.
Initially x = 5
First, the value of x is assigned to y.
y=x
Then x is incremented,
x=x+1
x=5+1
Hence now value of x is 6 and value of y is 5.

Example4:
#include<stdio.h>
int main()
{
int x=5, y;
y = x--;
printf("x=%d\ty=%d", x, y);
return 0;
}
Explanation:
Here first the value of variable x is used in the operation and then decrement is
performed.
Initially x = 5
First, the value of x is assigned to y.
y=x
Then x is decrement,
x=x-1
x=5-1
Hence now value of x is 4 and value of y is 5.
 Type Conversion (type casting) in C:
→ Converting the value of one data type to another data type is known as type
conversion.
→ For example, if you try to divide two integers, 5 by 2, you would expect the result to
be 2.5. But since we are working with integers (and not floating-point values), the
following example will just output 2:
int x = 5;
int y = 2;
int sum = 5 / 2;
printf("%d", sum); // Outputs 2

→ To get the right result, you need to know how type conversion works.

There are two types of conversion in C:


Implicit Conversion (automatically)
Explicit Conversion (manually)

Implicit Conversion (automatically)


→ Implicit conversion is done automatically by the compiler when you assign a
value of one type to another.

Example1:
If you assign an int value to a float type:
#include<stdio.h>
int main()
{
float a = 50; // Automatic conversion: int to float
printf("%f", a); // 50.000000
return 0;
}

Example2:
#include<stdio.h>
int main()
{
int a = 10;
float b = 4.7;
float result = a + b; // 'a' (int) is implicitly converted to 'float'
printf("%.2f", result); // 14.70 is result
return 0;
}
Example3:
#include<stdio.h>
int main()
{
char a = 10;
short b = 20;
int result = a + b; // 'a', 'b' is implicitly converted to 'int' before the addition.
printf("%d", result); // 30
return 0;
}

Example4:
#include<stdio.h>
int main()
{
double value = 41.25e1;
printf("Double Value: %.2lf\n", value);
int number = value;
printf("Integer Value: %d", number);
return 0;
}

Explicit Conversion (manually)


→ In explicit type conversion, user manually convert values of one data type to
another type.
Example1:
#include<stdio.h>
int main()
{
int num1=5;
int num2=2;
float div = (float)num1/num2;
printf("%f", div); // 2.500000
return 0;
}

Example2:
#include<stdio.h>
int main()
{
float x = 9.99;
int y = (int)x; // Convert float to int, truncating the decimal part.
printf("%d", y); // Output: 9
return 0;
}
Example3:
#include<stdio.h>
int main()
{
char c = 'A';
int asciiValue = (int)c; // Convert char to int to get its ASCII value.
printf("%d", asciiValue); // Output: 65
return 0;
}

Note:
→ When converting from higher data type to lower data type, there will be data loss.
Example:
long double type is converted to double type; long double type is converted to int
type.

→ When converting from lower data type to higher data type, there will be no data
loss.
Example:
If char is converted to int, int is converted to float.
 Expression Evaluation:
→ For evaluation of expressions having more than one operator, there are certain
operator precedence and associativity rules defined in C.
→The operator precedence determines which operator is executed first if there is more
than one operator in an expression.
→ The associativity determines the direction in which an expression is evaluated.

Complete Operator Table (C/C++/Java/JavaScript):

Precedence Operator Description Associativity


1 (Highest) () parentheses
[] array
-> subscript
Left-to-Right
. member access
a++ postfix increment
a-- postfix decrement
2 ++a prefix increment
--a prefix decrement
+a unary plus
-a unary minus
! logical NOT
Right-to-Left
~ bitwise NOT
(type) cast
*ptr dereference
&var address-of
sizeof sizeof
3 * multiplication
/ division Left-to-Right
% modulus
4 + addition
Left-to-Right
- subtraction
5 << bitwise left shift
Left-to-Right
>> bitwise right shift
6 < less than
<= less than or equal to
Left-to-Right
> greater than
>= greater than or equal to
7 == equal to
Left-to-Right
!= not equal to
8 & bitwise AND Left-to-Right
9 ^ bitwise XOR Left-to-Right
10 | bitwise OR Left-to-Right
11 && logical AND Left-to-Right
12 || logical OR Left-to-Right
13 ?: ternary conditional Right-to-Left
14 (Lowest) = simple assignment
Right-to-Left
*= assign product
/= assign quotient
%= assign remainder
+= assign sum
-= assign difference
&= assign bitwise AND
^= assign bitwise XOR
|= assign bitwise OR
<<= assign left shift
>>= assign right shift

Example: Let us take an a + b - c + d * 3 % e + f / 9 expression and evaluate


according the precedence, associativity and parentheses rules.
Consider a = 8, b = 4, c = 2, d = 1, e = 5, f = 20
Sol:
a+b-c+d*3%e+f/9
8 + 4 – 2 + 1 * 3 % 5 + 20 / 9
8 + 4 – 2 + 3 % 5 + 20 / 9
8 + 4 – 2 + 3 + 20 / 9
8+4–2+3+2
12 – 2 + 3 + 2
10 + 3 + 2
10 + 5
15

Example: Let us take an a + b - (c + d) * 3 % e + f / 9 expression and evaluate


according the precedence, associativity and parentheses rules.
Consider a = 8, b = 4, c = 2, d = 1, e = 5, f = 20
Sol:
a + b – (c + d) * 3 % e + f / 9
8 + 4 – (2 + 1) * 3 % 5 + 20 / 9
8 + 4 – 3 * 3 % 5 + 20 / 9
8 + 4 – 9 % 5 + 20 / 9
8 + 4 – 4 + 20 / 9
8+4–4+2
12 – 4 + 2
8+2
10
 Basic Input and Output:
→ The input operation involves movement of data from an input device (generally
keyboard) to computer memory.
→ The output operation the data moves from computer memory to the output (generally
screen).

Standard I/O Library


→ Input and output in C are performed through a set of inbuilt library functions.
→ These functions are provided by the Standard I/O library.
→ To use them, the header file must be included:
#include <stdio.h>

Input (scanf):
→ Used to read data from user (keyboard → memory).
→ Defined in <stdio.h>.
Syntax:
scanf("format_string", &var1, &var2, ...);

Examples:
int n;
scanf("%d", &n);

int a; float b;
scanf("%d %f", &a, &b);

int day, month, year;


scanf("%d-%d-%d", &day, &month, &year);

Output (printf):
→ Used to display data (memory → screen).
→ Defined in <stdio.h>.
Syntax:
printf("control_string", var1, var2, ...);

Examples:
int a = 5, b = 10;
printf("a=%d, b=%d\n", a, b); // prints values
printf("Hello World!\n"); // prints string
Format Specifiers (Conversion Specifications):

Specifier Meaning
%c Single character
%d Decimal integer
%f Floating-point number
%e Floating-point (scientific notation)
%lf Double precision floating-point
%h Short integer
%o Octal integer
%x Hexadecimal integer
%s String
%u Unsigned integer

Formatted Input:
Format:
%wd (for integers), %wf (for floats).
w = field width (max number of characters read).

Example:
int a;
scanf("%2d", &a);
Input: 20 → stores 20.
Input: 206 → stores 20 (extra digits ignored).

Multiple fields:
scanf("%2d %3d", &a, &b);
Input: 269 3845 → a=26, b=9.

Formatted Output:
Format:
%wd (integer), %w.pf (float).
w = min field width
p = precision (digits after decimal).
Values are right-justified if shorter than width.

Integer Example:
int a=6, b=39;
printf("a=%3d, b=%4d", a, b);
Output:
a= 6, b= 39
Format For Integer Output:
%wd
→ Here w is the integer number specifying the minimum field width of the output data.
→ If the length of the variable is less than the specified field width, then the variable is
right justified with leading blanks.

Example:
printf("a=%3d, b=%4d", a, b );

Floating-Point Example:
float x=5.3, y=65.87;
printf("x = %4.1f, y = %7.2f", x, y);
Output:
x = 5.3, y = 65.87

Format For Floating Point Numeric Output:


Example:
printf("x = %4.1f, y = %7.2f ", x, y);
 List of Programs:

1) C program to print/display the text message “Hello World” on the screen.


Code:
#include<stdio.h>
int main()
{
printf("Hello World");
return 0;
}

2) C program to print/display name of the student, branch and college in three lines
using \n.
Code:
#include<stdio.h>
int main()
{
printf("Name: Anirudh\n"); // \n moves cursor to the next line
printf("Branch: CSC\n");
printf("College: Raghu Engineering College");
return 0;
}

3) C program to print the sentence with double quotes using \".


Code:
#include<stdio.h>
int main()
{
printf("Hi.\"I am Learning C.\"");
return 0;
}

4) C program to show a file path using \\.


Code:
#include<stdio.h>
int main()
{
printf("c:Users\\Documents\\Pictures");
return 0;
}
5) Write a C program to display the following output using escape sequences:
C Programming:
"Easy to Learn"
\Procedural Language\
Code:
#include<stdio.h>
int main()
{
printf("C Programming:\n");
printf("\t\"Easy to Learn\"\n");
printf("\t\\Procedural Language\\");
return 0;
}

6) Write a C program to display the following output using \t:


Name Age Branch
Anirudh 18 CSC
Rahul 17 CSC
Code:
#include<stdio.h>
int main()
{
printf("Name\tAge\tBranch\n");
printf("Anirudh\t18\tCSC\n");
printf("Rahul\t17\tCSC\n");
return 0;
}

7) C program to add two integer numbers.


Code:
#include<stdio.h>
int main()
{
int num1=10, num2=20, sum;
sum=num1+num2;
printf("Sum= %d", sum);
return 0;
}
or
#include<stdio.h>
int main()
{
int num1, num2, sum;
printf("Enter 1st Number: ");
scanf("%d", &num1);
printf("Enter 2nd Number: ");
scanf("%d", &num2);
sum=num1+num2;
printf("Sum= %d", sum);
return 0;
}

8) C program to subtraction two integer numbers.


Code:
#include<stdio.h>
int main()
{
int num1=100, num2=20, sub;
sub=num1-num2;
printf("Subtraction=%d", sub);
return 0;
}
or
#include<stdio.h>
int main()
{
int num1, num2, sub;
printf("Enter 1st & 2nd Number: ");
scanf("%d%d", &num1, &num2);
sub=num1-num2;
printf("Subtraction=%d", sub);
return 0;
}

9) C program to multiply two floating point numbers.


Code:
#include<stdio.h>
int main()
{
float a=4.5, b=9.36, product;
product=a*b;
printf("Product = %.2f", product);
return 0;
}
or
#include<stdio.h>
int main()
{
float a, b, product;
printf("Enter Two Numbers: ");
scanf("%f %f", &a, &b);
product=a*b;
printf("Product = %.2f", product);
return 0;
}

10) C program to find division and modulus of two numbers.


Code:
#include<stdio.h>
int main()
{
int n1=100, n2=20, div, mod;
div=n1/n2;
mod=n1%n2;
printf("Division=%d\n", div);
printf("Modulus=%d\n", mod);
return 0;
}
or
#include<stdio.h>
int main()
{
int n1, n2, div, mod;
printf("Enter value of n1 & n2: ");
scanf("%d %d", &n1, &n2);
div=n1/n2;
mod=n1%n2;
printf("Division=%d\n", div);
printf("Modulus=%d\n", mod);
return 0;
}

11) C program to find area and perimeter of rectangle.


Code:
#include<stdio.h>
int main()
{
int length=10, breadth=20;
int area_rect, perimeter_rect;
area_rect=length*breadth;
perimeter_rect=2*(length+breadth);
printf("Area of rectangle is: %d", area_rect);
printf("\nPerimeter of rectangle is: %d", perimeter_rect);
return 0;
}
or
#include<stdio.h>
int main()
{
float length, breadth, area_rect, perimeter_rect;
printf("Enter length and breadth: ");
scanf("%f %f", &length, &breadth);
area_rect=length*breadth;
perimeter_rect=2*(length+breadth);
printf("Area of rectangle is: %.2f", area_rect);
printf("\nPerimeter of rectangle is: %.2f", perimeter_rect);
return 0;
}

12) C Program to find area and circumference of circle.


Code:
#include<stdio.h>
#define pi 3.14
int main()
{
float radius=7.5, area, ci;
area=pi*radius*radius;
ci=2*pi*radius;
printf("Area of Circle= %.2f\n",area);
printf("Circumference of Circle= %.2f", ci);
return 0;
}
or
#include<stdio.h>
int main()
{
float pi=3.14, radius, area, ci;
printf("Enter Radius of Circle: ");
scanf("%f",&radius);
area=pi*radius*radius;
printf("Area of Circle= %.2f\n", area);
ci=2*pi*radius;
printf("Circumference of Circle= %.2f", ci);
return 0;
}
13) C Program to find the simple interest.
Code:
#include<stdio.h>
int main()
{
float p=100000.45, t=4, r=3.5, si;
si=p*t*r/100.0;
printf("Simple Interest: %.2f", si);
return 0;
}
or
#include<stdio.h>
int main()
{
float p, t, r, si;
printf("Enter p t r:");
scanf("%f%f%f", &p,&t,&r);
si=p*t*r/100.0;
printf("Simple Interest: %.2f", si);
return 0;
}

14) C program to find square root of a given number.


Code:
#include<stdio.h>
#include<math.h>
int main()
{
double number, result;
printf("Enter a number: ");
scanf("%lf", &number);
result=sqrt(number);
printf("Square root= %.2lf\n", result);
return 0;
}

15) Write a C program that take a base (floating number) and an exponent (integer)
from the user and calculates the power.
Code:
#include<stdio.h>
#include<math.h>
int main()
{
float base, result;
int exponent;
printf("Enter base: ");
scanf("%f", &base);
printf("Enter exponent: ");
scanf("%d", &exponent);
result=pow(base, exponent);
printf("Result is %.2f\n", result);
return 0;
}

16) C program to convert a temperature from Celsius to Fahrenheit.


Code:
#include<stdio.h>
int main()
{
double celsius, fahrenheit;
printf("Enter temperature in Celsius: ");
scanf("%lf", &celsius);
fahrenheit=(celsius*9/5)+32;
printf("%.2lf Celsius = %.2lf Fahrenheit\n", celsius, fahrenheit);
return 0;
}

17) C program to convert a temperature from Fahrenheit to Celsius.


Code:
#include<stdio.h>
int main()
{
double fahrenheit, celsius;
printf("Enter temperature in Fahrenheit: ");
scanf("%lf", &fahrenheit);
celsius=(fahrenheit-32)*5/9;
printf("%.2lf Fahrenheit = %.2lf Celsius\n", fahrenheit, celsius);
return 0;
}

18) C program to convert a temperature from Fahrenheit to Celsius and vice versa.
Code:
#include<stdio.h>
int main()
{
float t, f, c;
printf("Enter Temperature: ");
scanf("%f", &t);
c=(t-32.0)*0.56;
f=(t*1.8)+32.0;
printf("celsius=%.2f\tfahrenheit=%.2f", c,f);
return 0;
}

19) C program to find sum and average of 3 numbers.


Code:
#include<stdio.h>
int main()
{
int n1, n2, n3, sum;
float avg;
printf("Enter n1, n2, n3: ");
scanf("%d %d %d", &n1, &n2, &n3);
sum=n1+n2+n3;
avg=(float)sum/3;
printf("Sum=%d \t Average=%.2f", sum,avg);
return 0;
}
20) C program to find compound interest.
Code:
#include<stdio.h>
#include<math.h>
int main()
{
float amount, principle, rate, time, ci;
printf("Enter Principle, Rate & Time:\n");
scanf("%f%f%f", &principle, &rate, &time);
amount=principle*pow((1+rate/100), time);
ci=amount-principle;
printf("Amount=%.2f\n", amount);
printf("Compund Interest is %.2f", ci);
return 0;
}

21) C program to find distance travelled by an object.


Code:
#include<stdio.h>
int main()
{
float dt, time, speed;
printf("Enter the value of speed(m/s) & time(s):");
scanf("%f%f", &speed, &time);
dt=speed*time;
printf("Distance travelled=%.2f meters\n", dt);
return 0;
}
or
#include<stdio.h>
int main()
{
double u, a, t, dt;
printf("Enter initial velocity(u): ");
scanf("%lf", &u);
printf("Enter acceleration(a): ");
scanf("%lf", &a);
printf("Enter time(t): ");
scanf("%lf", &t);
dt=u*t + 0.5*(a*t*t);
printf("Distance travelled = %.2f meters\n", dt);
return 0;
}

22) C program to find area of a triangle using heron’s formulae


Code:
#include<stdio.h>
#include<math.h>
int main()
{
float a, b, c, s, area_triangle;
printf("Enter the lengths of sides a, b and c:");
scanf("%f%f%f", &a, &b, &c);
s=(a+b+c)/2;
area_triangle=sqrt(fabs(s*(s-a)*(s-b)*(s-c)));
printf("Area of Triangle(Heron's formula)=%.2f", area_triangle);
return 0;
}

You might also like