0% found this document useful (0 votes)
147 views30 pages

C Programming Notes - Module1

Module 1 provides an introduction to computing, focusing on computer languages, particularly C, which is characterized as a middle-level, structured, and programmer-friendly language. It covers the creation and execution of C programs, system development principles, and the history and features of C, including its portability and efficiency. Key topics include data types, expressions, identifiers, and the structure of C programs, emphasizing modular design and the use of libraries.
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)
147 views30 pages

C Programming Notes - Module1

Module 1 provides an introduction to computing, focusing on computer languages, particularly C, which is characterized as a middle-level, structured, and programmer-friendly language. It covers the creation and execution of C programs, system development principles, and the history and features of C, including its portability and efficiency. Key topics include data types, expressions, identifiers, and the structure of C programs, emphasizing modular design and the use of libraries.
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/ 30

25PSC151 Module 1

Module 1

Introduction to Computing: Computer languages, Creating and Running Programs,


System Development. Overview of C: A Brief History of C, C Is a Middle-Level
Language, C Is a Structured Language, C Is a Programmer's Language, Compilers Vs.
Interpreters, The Form of a C Program, The Library and Linking, Separate
Compilation, Compiling a C Program, C's Memory Map. Expressions: The Basic Data
Types, Modifying the Basic Types, Identifier Names, Variables, The Four C Scopes,
Type Qualifiers, Storage Class Specifiers, Variable Initializations, Constants,
Operators, Expressions.

1. Computer Languages

1. A computer language allows humans to communicate instructions to a computer.

Categories of languages:

a.Low-level languages (Assembly): Machine-specific, uses symbolic hardware


instructions.
b. Middle-level languages (C): Combines low-level control with high-level
structure and portability.
c. High-level languages (Pascal, BASIC, Java): Focus on problem-solving,
easier to learn, machine-independent.
2. Structured vs. Non-structured Languages:
a. Structured (C, Pascal) → modular, clear, maintainable.
b. Non-structured (old BASIC, FORTRAN) → unorganized, prone to errors.
3. Compilers vs. Interpreters:
a. Compiler: Translates entire program into machine code once (used by C).
b. Interpreter: Executes program line-by-line (used by BASIC, early Java).
4. Portability: C programs can run on different systems with minimal changes.

2. Creating and Running Programs

Steps in writing and executing a C program:

1. Creating the Program:

a. Write the source code using a text editor.


5. Compiling:
a. The compiler converts the source code into object code (machine language).
6. Linking:
a. The linker combines your object code with library functions to create an
executable file.
7. Executing:
a. The executable file runs under the OS; memory regions include code, global
variables, stack, and heap.
8. Separate Compilation:
a. Large programs can be split into multiple files, compiled separately, and then
linked together — saves time and supports teamwork.
NCET, Bengaluru
25PSC151 Module 1

9. Library and Linking:


a. Predefined functions (e.g., printf(), scanf()) are stored in libraries; linking
connects them with your code.

3. System Development

1. Software development in C follows principles of software engineering for reliability


and maintainability.
2. Top-Down Design:
a. Divide the main problem into smaller, manageable modules
(functions).
3. Choosing Data Structures:
a. Select efficient structures (arrays, lists, stacks) for better performance.
4. Bulletproof Functions:
a. Functions should be reliable, self-contained, and have minimal side
effects.
5. Development Tools:
a. MAKE utility: Automates compilation of only changed files.
b. IDE (Integrated Development Environment): Combines editor, compiler,
and debugger in one tool.
6. Efficiency:
a. Optimize code using registers, pointers, and modular design.
7. Portability & Debugging:
a. Use #define and standardized code to ease cross-platform compatibility.
b. Debug systematically to remove logical and runtime errors.

Overview of C

1. A Brief History of C

1. C was developed by Dennis Ritchie in the early 1970s at Bell Labs while working on
the UNIX operating system.
2. It evolved from earlier languages: BCPL (Martin Richards) → influenced B (Ken
Thompson) → led to C (Dennis Ritchie).
3. Originally used to write the UNIX OS, making UNIX the first OS written in a high-
level language.
4. The first C description appeared in The C Programming Language (1978) by Brian
Kernighan and Dennis Ritchie.
5. In 1983, ANSI formed a committee to standardize C → resulting in ANSI C (C89),
adopted in 1989, later by ISO.
6. Amendment 1 (1995) added new library functions.
7. C99 Standard (1999) introduced new features such as:
1. Variable-length arrays
2. inline keyword
3. restrict pointer qualifier
4. New data types: _Bool, _Complex, _Imaginary.
8. Despite C++ and Java, C remains vital for system-level programming, embedded
systems, and portability.

NCET, Bengaluru
25PSC151 Module 1

2. C Is a Middle-Level Language

1) C is called a middle-level language because it combines the power of low-level


(assembly) and simplicity of high-level languages.
2) Low-level features:
1. Direct access to memory, bits, and bytes.
2. Efficient and close to hardware.
3) High-level features:
1. Use of data types, control structures, and functions.
2. Portable and machine-independent code.
4) Supports bitwise operations and pointer arithmetic, useful in system programming.
5) Has a small set of keywords (32 in C89, +5 in C99).
6) C allows type conversions and gives programmers control — no automatic runtime
error checking (like array bounds).
7) Provides portability, making C programs easily adaptable to new systems.

Languages

* In machine level language computer only understand digital numbers i.e.in the
form of 0 and 1. So, instruction given to the computer is in the form binary digit,
which is difficult to implement instruction in binary code

* The assembly language is on other hand modified version of machine level


language. Where instructions are given in English like word as ADD, SUM, MOV
etc. It is easy to write and understand but not understand by the machine.

* High level languages are machine independent, means it is portable. The language
in this category is Pascal, Cobol, Fortran etc. High level languages are understood by
the machine. So it need to translate by the translator into machine level. A translator is
software which is used to translate high level language as well as low level language
in to machine level language

3. C Is a Structured Language

1) Structured programming means dividing a program into smaller, logical modules.


2) C encourages modular design using functions and code blocks {}.
3) Each block or function can operate independently with local variables (no side effects
on other parts of the code).
4) Discourages global variables to avoid bugs.
5) C provides structured control constructs — if, while, for, switch, and avoids heavy
use of goto.
6) Each function performs a specific task, improving readability and reusability.
7) Structured design makes programs easier to test, debug, and maintain.
8) Hence, C supports clarity, modularity, and discipline in programming.

NCET, Bengaluru
25PSC151 Module 1

4. C Is a Programmer’s Language

1) C was created by programmers for programmers, focusing on flexibility and control.


2) Unlike BASIC or COBOL, which were meant for non-programmers, C gives the
programmer full control over system resources.
3) Offers powerful low-level access (e.g., pointer operations) combined with high-level
structured features.
4) Allows writing efficient and portable programs.
5) Provides freedom with fewer restrictions, enabling both system and application
development.
6) C enables programmers to achieve near assembly-level performance with structured
design.
7) Initially used for system software (compilers, OS, editors), now used for any
application area.
8) Remains a foundation language for C++, Java, and modern programming.

Features of C Programming Language:

* C is one of the most popular languages used today.

* C is a robust programming with an impressive set of built-in functions and a variety of


operators which you can use to write any complex program.

* C programs are fast and efficient. This is because C uses a powerful set of data types and
operators.

* C combines the power and capability of assembly language with the user friendly features
of a high-level language.

* C is the most widely used older programming language. It continues to go strong while
older programming languages such as BASIC and COBOL have been virtually forgotten.

* C is very much portable, which means programs written on a machine using C can be used
on other machines as well without any modification.

* A C program consists of a number of functions that are supported by C library. In fact, you
can create your own function, which can then be added to the C library.

Characteristics of C Language:

* C is a General Purpose Programming Language. This means C can be used to write a


variety of applications. It is often referred to as a “system programming language.”

• C is a middle level language, which means it combines the features of high level language
with the functionality of an assembly language.

• C is a structured programming language, which means as a programmer, you are required to


divide a problem into a several different modules or functions.

NCET, Bengaluru
25PSC151 Module 1

• C is renowned for its simplicity and is easy to use because of its structured approach. It has
a vast collection of keywords, operators, built-in functions and data types which make it
efficient and powerful.

• C is portable, which means a C program runs in different environments. C compilers are


available for all operating systems and hardware platforms. Additionally, you can easily write
code on one system and port it to another.

• C is popular not just because it can be used as a standalone programming language, but also
as it can be used as an interface to other more visual languages.

5. Compilers vs. Interpreters

6. The Form of a C Program

1) All C programs consist of one or more functions.


2) The function main() is mandatory — execution starts there.
3) A C program may include:
1. Preprocessor directives (#include, #define)
NCET, Bengaluru
25PSC151 Module 1

Global declarations (variables, constants, prototypes)


2.
Function definitions
3.
4) General structure:

a) The documentation section is used for displaying any information about the
program like the purpose of the program, name of the author, date and time
written etc, and this section should be enclosed within comment lines. The
statements in the documentation section are ignored by the compiler.
b) The link section consists of the inclusion of header files.
c) The definition section consists of macro definitions, defining constants etc,.
d) Anything declared in the global declaration section is accessible throughout
the program, i.e. accessible to all the functions in the program.
e) main() function is mandatory for any program and it includes two parts, the
declaration part and the executable part.
f) The last section, i.e. sub-program section is optional and used when we require
including user defined functions in the program.

5) C is case-sensitive – main ≠ Main.


6) Each program must end with a main() function even if multiple other functions exist.

8. The Library and Linking

1) C has a Standard Library containing pre-written functions (e.g., printf(), scanf()).


2) Libraries provide I/O, math, string handling, etc.
3) The compiler records library function names used in your code.
4) During linking, these references are resolved —
the linker combines your program’s object code with library object code.
NCET, Bengaluru
25PSC151 Module 1

5) This process produces a single executable file.

Linkers can be:

1. Built into the compiler, or


2. Provided by the operating system.
3. Library files are in relocatable format (addresses defined at link time).
4. Programmers can also create their own user-defined libraries for reuse.

9. Separate Compilation

1) Large programs can be divided into multiple source files.


2) Each file is compiled separately into its own object file.
3) Later, all object files are linked together with required library code.
4) Advantages:
1. Saves time — only changed files need recompilation.
2. Multiple programmers can work on different modules simultaneously.
3. Improves program organization and readability.
5) Example:

file1.c → file1.obj
file2.c → file2.obj
Link all → program.exe
Shortcut keys to compile and run in TC++ environment

**Compile** Alt + F9` | Compiles the program and checks for syntax errors.
**Run / Execute** Ctrl + F9` | Runs the last compiled program.
**View Output Screen* Alt + F5` Displays the output (DOS window) after running the
program. |

10. Compiling a C Program

1) Creating the program


NCET, Bengaluru
25PSC151 Module 1

1. Write source code (.c) using a text editor.


2. Must be a plain text file (not a word-processor file).
2) Compiling
1. Compiler checks for syntax errors and converts code into object code.
3) Linking
1. The linker combines your object file with library functions to produce an
executable file.
4) Executing
1. The OS loads the executable into memory and runs it.
5) Integrated Development Environments (IDEs) simplify this by automating all
steps (Edit → Compile → Link → Run).
C’s Memory Map

A compiled C program creates and uses four logically distinct regions of memory. The first
region is the memory that actually holds the program's executable code. The next region is
memory where global variables are stored. The remaining two regions are the stack and the
heap. The stack is used for a great many things while your program executes. It holds the
return addresses of function calls, arguments to functions, and local variables. It will also
save the current state of the CPU. The heap is a region of free memory that your program can
use via C's dynamic memory allocation functions. Although the exact physical layout of each
of the four regions of memory differs among CPU types and C implementations, the diagram
in Figure 1-2 shows conceptually how your C programs appear in memory

Expressions in C

1. The Basic Data Types

In C programming, data types classify the type of data a variable can hold, determining the
memory allocated and the operations that can be performed on it.

NCET, Bengaluru
25PSC151 Module 1

2. Modifying the Basic Types

1. Type modifiers alter the size or sign of the base data type.
2. Available modifiers:
i. signed, unsigned, long, short
3. Examples:
i. short int, long int, unsigned int, long double
4. long was added in C99 for 64-bit integers.
5. Signed vs Unsigned:
i. Signed integers can store both positive and negative values.
NCET, Bengaluru
25PSC151 Module 1

Unsigned integers can store only non-negative values but have a higher
ii.
positive range.
6. When a modifier is used alone, int is assumed.
i. Example: unsigned → means unsigned int.

3. Identifier Names

Identifiers refer to the names of variables, constants, functions and arrays. These are user-
defined names is called Identifiers. These identifier are defined against a set of rules.
Rules for an Identifier
1. An Identifier can only have alphanumeric characters ( a-z , A-Z , 0-9 ) and underscore( _ ).
2. The first character of an identifier can only contain alphabet ( a-z , A-Z ) or underscore (
_).
3. Identifiers are also case sensitive in C. For example name and Name are two different
identifier in C.
4. Keywords are not allowed to be used as Identifiers.
5. No special characters, such as semicolon, period, whitespaces, slash or comma are
permitted to be used in or as Identifier.
6. C‟ compiler recognizes only the first 31 characters of an identifiers.

4. Variables

A variable is a name of memory location. It is used to store data. Variables are


changeable, we can change value of a variable during execution of a program. . It can
be reused many times.

Note: Variable are nothing but identifiers.

Rules to write variable names:

1. A variable name contains maximum of 30 characters/ Variable name must be upto


8 characters.

2. A variable name includes alphabets and numbers, but it must start with an alphabet.

3. It cannot accept any special characters, blank spaces except under score( _ ).

4. It should not be a reserved word.

Syntax to declare a variable

datatype variable_name1, variable_name2,……..variable_nameN;

Example: int sum, max, number;


NCET, Bengaluru
25PSC151 Module 1

float value; char ch;

Types of variables based on scope:

i. Local variables → inside functions or blocks.


ii. Global variables → outside all functions.
iii. Formal parameters → variables used to receive function arguments.

 Keywords are predefined or reserved words that have special meanings to the
compiler. These are part of the syntax and cannot be used as identifiers in the
program. Keywords are not allowed to be used as identifiers. No special character, such as
semicolon, period, white spaces, slash or comma are permitted to be used in or as identifiers.
Keyword: Keywords are the reserved words of a language. Identifier: Identifiers are the user-
defined names of variables, functions, and labels.

5. The Four C Scopes

C defines four levels of scope (visibility of identifiers):

Scope Description

Applies to identifiers declared outside all functions. Visible


File scope
throughout the file.

NCET, Bengaluru
25PSC151 Module 1

Scope Description

Begins with { and ends with }. Includes local variables and function
Block scope
parameters.

Function prototype
For identifiers used in function prototypes (temporary).
scope

Function scope For labels used with goto; valid only inside the same function.

6. Type Qualifiers

Type qualifiers modify how variables are accessed or changed.

1) Common qualifiers:
1. const – value cannot be changed once assigned.
2. volatile – tells the compiler that a variable’s value may change unexpectedly
(e.g., hardware register).
2) Example:

const int x = 10;


volatile int timer;

3) Help optimize or control how variables behave during program execution.

7. Storage Class Specifiers

Define the lifetime, visibility, and memory location of variables.

1) Specifiers:
1. auto – default for local variables; stored on the stack.
2. register – stored in CPU register (faster access).
3. static – retains value between function calls.
4. extern – refers to a global variable defined elsewhere (in another file).
2) Example:
3) static int count = 0;
4) extern int total;

8. Variable Initializations

Variables can be initialized at the time of declaration.

Syntax:
int a = 10;
float rate = 2.5;

i. Local variables → reinitialized each time the block runs.


NCET, Bengaluru
25PSC151 Module 1

ii. Static variables → retain their value between calls.


iii. Global variables → initialized only once before program execution.

/*2. Write a program to demonstrate the use of printf statement to print values of
variables of different data types.*/

#include <stdio.h>
main()
{
// Declare and initialize variables
int num = 7;
float amt = 123.45;
char code = 'A';
double pi = 3.1415926536;
long int population_of_india = 10000000000;
char msg[] = "Hi";
// Print the values of variables
printf("\n NUM = %d \t AMT = %f \t CODE = %c \n PI = %e \t POPULATION OF INDIA
= %ld \n MESSAGE = %s", num, amt, code, pi, population_of_india, msg);
return 0;
}

/*3. Write a program to demonstrate the use of printf and scanf statements to read and
print values of variables of different data types.*/

#include <stdio.h>
main()
{
int num;
float amt;
char code;
double pi;
long int population_of_india;
char msg[10];
printf("\n Enter the value of num : ");
scanf("%d", &num);
printf("\n Enter the value of amt : ");
scanf("%f", &amt);
printf("\n Enter the value of pi : ");
scanf("%e", &pi);
printf("\n Enter the population of india : ");
scanf("%ld", &population_of_india);
printf("\n Enter the value of code : ");
scanf("%c", &code);
printf("\n Enter the message : ");
scanf("%s", msg);
printf("\n NUM = %d \n AMT = %f \n PI = %e \n POPULATION OF INDIA = %ld \n
CODE = %c \n MESSAGE = %s", num, amt, code, pi, population_of_india, msg);
return 0;
NCET, Bengaluru
25PSC151 Module 1

9. Constants

1) Constants are fixed values that do not change during execution.


2) Types of constants:
i. Integer constants: 10, 255, -34
ii. Floating-point constants: 3.14, 0.001
iii. Character constants: 'A', '9'
iv. String constants: "Hello"
v. Hexadecimal and octal constants: 0xFF, 077
3) Escape sequences:
i. \n (newline), \t (tab), \\ (backslash), \' (single quote).
4) const keyword makes variables constant.
5) const float PI = 3.14159;

10. Operators

C provides a rich set of operators for building expressions.

1) Arithmetic operators: +, -, *, /, %
2) Increment/Decrement: ++, --
3) Relational: <, >, <=, >=, ==, !=
4) Logical: &&, ||, !
5) Bitwise: &, |, ^, ~, <<, >>
6) Assignment: =, +=, -=, etc.
7) Pointer operators: & (address), * (value at address)
8) Conditional operator: ?: (ternary operator)
9) Sizeof: returns memory size of data type/variable.
10) Comma operator (,): used to separate expressions.
11) Dot (.) and Arrow (->): used to access structure members.

C Operators with Explanation and Examples


Arithmetic Operators (+, -, *, /, %)
Used to perform basic mathematical operations.
Example:
int a = 10, b = 3;
printf("%d", a + b); // Output: 13
printf("%d", a % b); // Output: 1
Increment/Decrement Operators (++ , --)
Used to increase or decrease the value of a variable by 1.
Example:
int x = 5;
x++; // x becomes 6
x--; // x becomes 5
NCET, Bengaluru
25PSC151 Module 1

Relational Operators (<, >, <=, >=, ==, !=)


Used to compare two values. Returns 1 (true) or 0 (false).
Example:
int a = 5, b = 10;
printf("%d", a < b); // Output: 1
Logical Operators (&&, ||, !)
Used to perform logical operations on boolean expressions.
Example:
int a = 1, b = 0;
printf("%d", a && b); // Output: 0
printf("%d", a || b); // Output: 1
printf("%d", !a); // Output: 0
Bitwise Operators (&, |, ^, ~, <<, >>)
Used to perform bit-level operations.
Example:
int a = 5, b = 3;
printf("%d", a & b); // Output: 1
printf("%d", a | b); // Output: 7
printf("%d", a << 1); // Output: 10
Assignment Operators (=, +=, -=, etc.)
Used to assign values to variables.
Example:
int a = 10;
a += 5; // a = a + 5 => 15
Pointer Operators (&, *)
'&' gives the address of a variable, '*' gives the value at the address.
Example:
int a = 10;
int *p = &a;
printf("%d", *p); // Output: 10
Conditional (Ternary) Operator (?:)
Used to replace simple if-else statements.
Example:
int a = 10, b = 20;
int max = (a > b) ? a : b; // max = 20
Sizeof Operator
Returns the memory size (in bytes) of a data type or variable.
Example:
printf("%lu", sizeof(int)); // Output: 4 (on most systems)

NCET, Bengaluru
25PSC151 Module 1

Comma Operator (,)


Allows multiple expressions to be separated and evaluated from left to right.
Example:
int a = (1, 2, 3); // a = 3
Dot (.) and Arrow (->) Operators
Used to access structure members directly or via pointers.
Example:
struct Student { int id; } s1;
s1.id = 10;
struct Student *ptr = &s1;
printf("%d", ptr->id); // Output: 10

11. Expressions

1) An expression is a combination of variables, constants, and operators that produces a


value.
2) Example:
3) int sum = a + b * c;
4) Expressions are evaluated according to operator precedence and associativity.

Type conversion:

oAutomatic conversions occur when operands differ in type (implicit casting).


oExplicit conversions use type casting:
o (float) a / b;
5) Parentheses can override default precedence and make code clearer.

NCET, Bengaluru
25PSC151 Module 1

Example 1: Basic Arithmetic Precedence


Expression: 10 + 5 * 2
Step 1: Multiplication (*) has higher precedence than addition (+)
=> 10 + (5 * 2)
=> 10 + 10
=> Result = 20
Example 2: Using Parentheses
Expression: (10 + 5) * 2
Step 1: Parentheses evaluated first

NCET, Bengaluru
25PSC151 Module 1

=> (15) * 2
=> Result = 30
Example 3: Combination of Relational and Arithmetic Operators
Expression: 10 + 5 > 12
Step 1: '+' has higher precedence than '>'
=> (10 + 5) > 12
=> 15 > 12
=> Result = 1 (True)
Example 4: Logical Operators
Expression: (5 > 3) && (8 < 10)
Step 1: Relational operators are evaluated first
=> (1) && (1)
=> 1 && 1 => Result = 1 (True)
Example 5: Assignment and Arithmetic
Expression: int a = 10; int b = 5; int c = a + b * 2;
Step 1: Multiplication (*) first => b * 2 = 10
Step 2: Addition => a + 10 = 20
=> c = 20
Example 6: Mixed Operators
Expression: int x = 10; int y = 5; int z = x++ + --y * 2;
Step 1: Pre-decrement (--y) => y = 4
Step 2: Post-increment (x++) uses current value => 10
Step 3: Multiplication (*) => 4 * 2 = 8
Step 4: Addition => 10 + 8 = 18
After evaluation: x = 11, y = 4, z = 18
Example 7: Conditional Operator
Expression: int a = 10, b = 20; int max = (a > b) ? a : b;
Step 1: (a > b) is false
=> max = b => 20
Example 8: Comma Operator
NCET, Bengaluru
25PSC151 Module 1

Expression: int x = (1, 2, 3);


Step 1: Expressions evaluated left to right, result of last expression is assigned
=> x = 3
Difference Between Pre-Increment and Post-Increment in C
In C, increment operators are used to increase the value of a variable by 1. However, the
placement of the operator determines when the increment happens — before or after the
value is used.
1. Pre-Increment (++x)
In pre-increment, the variable is incremented first, and then the updated value is used in the
expression.
Example:
#include <stdio.h>
int main() {
int x = 5;
int y = ++x; // Pre-increment: x is incremented first
printf("x = %d, y = %d", x, y);
return 0;
}
Step-by-step:
- x starts as 5
- ++x increments x to 6
- The new value (6) is assigned to y
Output:
x = 6, y = 6
2. Post-Increment (x++)
In post-increment, the current value of the variable is used first, and then it is incremented.
Example:
#include <stdio.h>
int main() {
int x = 5;
int y = x++; // Post-increment: x is used first, then incremented
NCET, Bengaluru
25PSC151 Module 1

printf("x = %d, y = %d", x, y);


return 0;
}
Step-by-step:
- x starts as 5
- The current value (5) is assigned to y
- Then x is incremented to 6
Output:
x = 6, y = 5
Comparison Summary
Type Operation Order Example Expression Result (x=5 initially) Output (x, y)
Pre-increment Increment first, then use the value y = ++x; x becomes 6, y = 6 x =
6, y = 6
Post-increment Use the value first, then increment y = x++; y = 5, x becomes 6
x = 6, y = 5.

Sample Programs to Practice


/*5. Write a program to calculate the distance between two points.*/
#include <stdio.h>
#include <conio.h>
#include <math.h>
int main()
{
int x1, x2, y1, y2;
float distance;
printf("\n Enter the x and y coordinates of the first point : ");
scanf("%d %d", &x1, &y1);
printf("\n Enter the x and y coordinates of the second point :");
scanf("%d %d", &x2, &y2); // sqrt and pow are mathematical functions defined in math.h
header file
distance = sqrt(pow((x2-x1), 2)+pow((y2-y1), 2));
printf("\n Distance = %f", distance);
return 0;
}

/*6. Write a program to perform addition, subtraction, division, integer division,


multiplication, and modulo division on two integer numbers.*/

NCET, Bengaluru
25PSC151 Module 1

#include <stdio.h>
#include <conio.h>
int main()
{
int num1, num2;
int add_res=0, sub_res=0, mul_res=0, idiv_res=0, modiv_res=0; float fdiv_res=0.0;
clrscr();
printf("\n Enter the first number : ");
scanf("%d", &num1);
printf("\n Enter the second number : ");
scanf("%d", &num2);
add_res= num1 + num2;
sub_res= num1 - num2;
mul_res = num1 * num2;
idiv_res = num1/num2;
modiv_res = num1%num2;
fdiv_res = (float)num1/num2;
printf("\n %d + %d = %d", num1, num2, add_res);
printf("\n %d - %d = %d", num1, num2, sub_res);
printf("\n %d ¥ %d = %d", num1, num2, mul_res);
printf("\n %d / %d = %d (Integer Division)", num1, num2, idiv_res);
printf("\n %d %% %d = %d (Moduluo Division)", num1, num2, modiv_res);
printf("\n %d / %d = %.2f (Normal Division)", num1, num2, fdiv_res);
return 0;
}

/*9. Write a program to show the use of relational operators.*/


#include <stdio.h>
Int main()
{
int x=10, y=20;
printf("\n %d < %d = %d", x, y, x<y);
printf("\n %d == %d = %d", x, y, x==y);
printf("\n %d != %d = %d", x, y, x!=y);
printf("\n %d > %d = %d", x, y, x>y);
printf("\n %d >= %d = %d", x, y, x>=y);
printf("\n %d <= %d = %d", x, y, x<=y);
return 0;
}

/*12. Write a program two find the largest of two numbers using ternary operator.*/
#include <stdio.h>
#include <conio.h>
int main()
{
int num1, num2, large;
NCET, Bengaluru
25PSC151 Module 1

clrscr();
printf("\n Enter the first number: ");
scanf("%d", &num1);
printf("\n Enter the second number: ");
scanf("%d", &num2);
large = num1>num2?num1:num2;
printf("\n The largest number is: %d", large);
return 0;
}

/*13. Write a program two find the largest of three numbers using ternary operator.*/

#include <stdio.h>
#include <conio.h>
int main()
{
int num1, num2, num3, large;
clrscr();
printf("\n Enter the first number: ");
scanf("%d", &num1);
printf("\n Enter the second number: ");
scanf("%d", &num2);
printf("\n Enter the third number: ");
scanf("%d", &num3);
large = num1>num2?(num1>num3?num1:num3):(num2>num3?num2:num3);
printf("\n The largest number is: %d", large);
return 0;
}

/*14. Write a program to demonstrate the use of assignment operators.*/

#include <stdio.h>
Int main()
{
int num1 = 3, num2 = 5;
printf("\n Initial value of num1 = %d and num2 = %d", num1, num2);
num1 += num2 * 4 - 7;
printf("\n After the evaluation of the expression num1 = %d and num2 = %d", num1, num2);
return 0;
}

/*15. Write a program to calculate the area of a circle.*/

#include <stdio.h>
#include <conio.h>
int main()
{
float radius;
double area, circumference;
NCET, Bengaluru
25PSC151 Module 1

clrscr();
printf("\n Enter the radius of the circle: ");
scanf("%f", &radius);
area = 3.14 * radius * radius;
circumference = 2 * 3.14 * radius;
printf(" Area = %.2le", area);
printf("\n CIRCUMFERENCE = %.2e", circumference);
return 0;
}

/*16. Write a program to print the ASCII value of a character.*/

#include <stdio.h>
#include <conio.h>
int main()
{
char ch;
clrscr();
printf("\n Enter any character: ");
scanf("%c", &ch);
printf("\n The ascii value of %c is: %d",ch,ch);
return 0;
}

/*17. Write a program to read a character in upper case and then print it in lower
case.*/

#include <stdio.h>
#include <conio.h>
int main()
{
char ch;
clrscr();
printf("\n Enter any character in uppercase: ");
scanf("%c", &ch);
printf("\n The character in lower case is: %c", ch+32);
return 0;
}

/*19. Write a program to swap two numbers using a temporary variable.*/

#include <stdio.h>
#include <conio.h>
int main()
{
int num1, num2, temp;
clrscr();
printf("\n Enter the first number: ");
scanf("%d",&num1);
NCET, Bengaluru
25PSC151 Module 1

printf("\n Enter the second number: ");


scanf("%d",&num2);
temp = num1;
num1 = num2;
num2=temp;
printf("\n The first number is %d", num1);
printf("\n The second number is %d", num2);
return 0;
}

/*20. Write a program to swap two numbers without using a temporary variable.*/

#include <stdio.h>
#include <conio.h>
int main()
{
int num1, num2;
clrscr();
printf("\n Enter the first number: ");
scanf("%d",&num1);
printf("\n Enter the second number: ");
scanf("%d",&num2);
num1 = num1 + num2;
num2= num1 - num2;
num1 = num1 - num2;
printf("\n The first number is %d", num1);
printf("\n The second number is %d", num2);
return 0;
}

/*21. Write a program to calculate average of two numbers. Also print their deviation.*/

#include <stdio.h>
#include <conio.h>
main()
{
int num1, num2;
float avg, dev1, dev2;
printf("\n Enter the two numbers: ");
scanf("%d %d", &num1, &num2);
avg = (num1 + num2) / 2;
dev1 = num1 - avg;
dev2 = num2 - avg;
printf("\n AVERAGE = %.2f", avg);
printf("\n Deviation of first number = %.2f", dev1);
printf("\n Deviation of second number = %.2f", dev2);
return 0;
}

NCET, Bengaluru
25PSC151 Module 1

/*22. Write a program to convert degrees Fahrenheit into degrees celsius.*/

#include <stdio.h>
#include <conio.h>
main()
{
float fahrenheit;
float celsius;
printf("\n Enter the temperature in fahrenheit: ");
scanf("%f", &fahrenheit);
celsius = (0.56) * (fahrenheit - 32);
printf("\n Temperature in degrees celsius = %f", celsius);
return 0;
}

/*23. Write a program that displays the size of every data type.*/

#include <stdio.h>
#include <conio.h>
int main()
{
clrscr();
printf("\n The size of short integer is: %d", sizeof(short int));
printf("\n The size of unsigned integer is: %d", sizeof(unsigned int));
printf("\n The size of signed integer is: %d", sizeof(signed int));
printf("\n The size of integer is: %d",
sizeof(int));
printf("\n The size of long integer is: %d", sizeof(long int));
printf("\n The size of character is: %d", sizeof(char));
printf("\n The size of unsigned character is: %d", sizeof(unsigned char));
printf("\n The size of signed character is: %d", sizeof(signed char));
printf("\n The size of floating point number is: %d", sizeof(float));
printf("\n The size of double number is: %d", sizeof(double));
return 0;
}

/*24. Write a program to calculate the total amount of money in the piggybank, given
the coins of Rs 10, Rs 5, Rs 2, and Re 1.*/

#include <stdio.h>
#include <conio.h>
int main()
{
int num_of_10_coins, num_of_5_coins, num_of_2_coins, num_of_1_coins;
float total_amt = 0.0;
clrscr();
printf("\n Enter the number of Rs10 coins in the piggybank: ");
scanf("%d", &num_of_10_coins);
printf("\n Enter the number of Rs5 coins in the piggybank: ");
NCET, Bengaluru
25PSC151 Module 1

scanf("%d", &num_of_5_coins);
printf("\n Enter the number of Rs2 coins in the piggybank: ");
scanf("%d", &num_of_2_coins);
printf("\n Enter the number of Re1 coins in the piggybank: ");
scanf("%d", &num_of_1_coins);
total_amt = num_of_10_coins * 10 + num_of_5_coins * 5 + num_of_2_coins * 2 +
num_of_1_coins;
printf("\n Total amount in the piggybank = %f", total_amt);
getch();
return 0;
}
/*25. Write a program to calculate the bill amount for an item given its quantity sold,
value, discount, and tax.*/

#include <stdio.h>
#include <conio.h>
main()
{
float total_amt, amt, sub_total,
discount_amt, tax_amt, qty, val,
discount, tax;
printf("\n Enter the quantity of item sold: ");
scanf("%f", &qty);
printf("\n Enter the value of item: ");
scanf("%f", &val);
printf("\n Enter the discount percentage: ");
scanf("%f", &discount);
printf("\n Enter the tax: ");
scanf("%f", &tax);
amt = qty * val;
discount_amt = (amt * discount)/100.0;
sub_total = amt - discount_amt;
tax_amt = (sub_total * tax) /100.0;
total_amt = sub_total + tax_amt;
printf("\n\n\n ****** BILL ******");
printf("\n Quantity Sold: %f", qty);
printf("\n Price per item: %f", val);
printf("\n -------------");
printf("\n Amount: %f", amt);
printf("\n Discount: - %f", discount_amt);
printf("\n Discounted Total: %f", sub_total);
printf("\n Tax: + %f", tax_amt);
printf("\n -------------");
printf("\n Total Amount %f", total_amt);
return 0;
}

NCET, Bengaluru
25PSC151 Module 1

Exercise Questions to be Solved


1)

NCET, Bengaluru
25PSC151 Module 1

3)

NCET, Bengaluru
25PSC151 Module 1

4)

/*5. Find the output of the following program.*/

#include <stdio.h>
main()
{
NCET, Bengaluru
25PSC151 Module 1

int a, b;
printf("\n Enter two four digit numbers : ");
scanf("%2d %4d", &a, &b);
printf("\n The two numbers are : %d and %d", a, b);
return 0;
}

NCET, Bengaluru

You might also like