5.1
Programming Concept
5.1.1 Introduction to Programming Languages
A programming language is a formal constructed language
designed to communicate instructions to a machine, particularly a computer.
Programming languages are used to create programs that control the behaviour of
a machine, to express algorithms precisely, or as a mode of human-computer
interaction.
They consist of a set of rules for combining symbols
(syntax) and a set of meanings for those combinations (semantics). Different
programming languages are suited for different types of tasks, from web
development and data science to game development and operating systems.
5.1.2 Low-level, High-level, and 4GL
Programming Languages
Programming languages are often categorized by their level
of abstraction from machine code:
1) Low-Level Programming Languages: These languages
are very close to the computer's native language (machine code) and provide
little or no abstraction from the computer's architecture. They offer direct
manipulation of memory and hardware registers, leading to highly optimized and
fast programs, but they are difficult to write and understand.
a) Machine Language (First Generation Language - 1GL):
Consists of binary code (0s and 1s) directly
executable by the CPU. It's the most fundamental level, extremely difficult for
humans to write.
b) Assembly Language (Second Generation Language - 2GL): Uses
mnemonics (short, symbolic codes like ADD, MOV, JMP) to represent machine
instructions. It's more readable than machine language but still
processor-specific and requires an assembler to translate it into machine code.
2) High-Level Programming Languages (3GL): These
languages are more abstract and human-readable, using keywords, syntax, and
structures that are closer to natural language (e.g., English). They are
machine-independent and require a compiler or interpreter to translate them
into machine code. This abstraction makes them easier to learn, use, and debug,
leading to faster development. Examples: C, C++, Java, Python, JavaScript, C#,
Ruby, Fortran, Pascal.
3) Fourth-Generation Languages (4GL): These languages
are even higher-level than 3GLs, designed to be closer to human language and
focused on specific domains or tasks, often with powerful built-in
functionalities. They typically aim to reduce programming effort and time by
enabling users to specify what they want to achieve rather than how to achieve
it. Examples: SQL (for database queries), MATLAB, etc.
Generation |
Full Form |
Type of
Language |
Example
Languages |
Features |
Ease of
Use |
Translation
Required |
Speed |
1GL |
First
Generation Language |
Machine
Language (Binary) |
10110010
(binary codes) |
Directly
executed by CPU; hardware-specific |
Very Low |
Not needed
(already binary) |
Very High
(fastest) |
2GL |
Second
Generation Language |
Assembly
Language |
MOV A, B |
Uses
mnemonics; requires assembler to convert to machine code |
Low |
Assembler |
High |
3GL |
Third
Generation Language |
High-level
Programming Language |
C, C++, Java,
Python |
Closer to
human language; portable and easier to understand |
Moderate to
High |
Compiler or
Interpreter |
Moderate |
4GL |
Fourth
Generation Language |
Very
High-level / Domain-specific |
SQL, MATLAB,
Oracle Reports |
Designed for
specific tasks; non-procedural; fast development |
Very High |
Usually
interpreter/compiler |
Slower than
1GL/2GL |
5.1.3
Compiler, Interpreter, and Assembler
These are software tools that translate source code written
in a programming language into a form that a computer can understand and
execute:
1) Compiler: A compiler translates an entire program
written in a high-level language (source code) into machine code (object code)
or an intermediate code before the program is run. Once compiled, the program
can be executed many times without recompilation (unless the source code
changes).
Advantages: Faster execution, standalone executable files.
Disadvantages: Compilation time can be significant,
difficult to debug during runtime.
Examples: C, C++, Java
2) Interpreter: An interpreter translates and
executes a program line by line. It reads one statement, translates it into
machine code, and executes it immediately before moving to the next statement.
Advantages: Easier debugging (errors are found as the
program runs), platform independence (if the interpreter is available).
Disadvantages: Slower execution compared to compiled code,
requires the interpreter to be present to run the program.
Examples: Python, JavaScript, Ruby, PHP.
3) Assembler: An assembler translates assembly
language (low-level language) into machine code. Each assembly language
instruction typically corresponds to one machine language instruction.
Feature |
Compiler |
Interpreter |
Translation |
Translates
the entire program before execution |
Translates
and executes code line by line |
Speed |
Faster, since
the entire code is pre-translated |
Slower, due
to continuous translation during execution |
Use Case |
Ideal for
repeated execution of the same program |
Best for
interactive or dynamic coding sessions |
Error Handling |
Errors
detected after compilation of the whole program |
Errors
detected as code is executed line by line |
Development |
Harder to
debug due to delayed execution |
Easier to
debug with immediate feedback |
Examples |
C, C++, Java |
Python, Ruby,
JavaScript |
5.1.4 Syntax, Semantic, and Runtime Errors
Errors are an inseparable part of programming. Understanding
different types of errors helps in debugging:
1) Syntax Errors: These are errors that violate the
grammatical rules of the programming language. The compiler or interpreter
catches these errors before the program can run or during the initial parsing
phase. They are like grammatical mistakes in a natural language sentence.
Examples: Missing semicolon, misspelled keyword, unmatched
parentheses, incorrect variable declaration.
Detection: Detected by the compiler/interpreter during
compilation/parsing.
2) Semantic Errors (Logic Errors): These errors occur
when the program is syntactically correct but does not do what the programmer
intended it to do. The program runs, but the output is incorrect or unexpected.
These are the hardest errors to find because the computer doesn't report them.
Examples: Incorrect formula, wrong operator used (+ instead
of −), infinite loop (if not detected as a runtime error), etc.
Detection: Requires careful testing and debugging by the
programmer.
3) Runtime Errors: These errors occur while the
program is executing. They are not detected by the compiler (for compiled
languages) or during the initial parsing (for interpreted languages) because
they depend on conditions that arise only during execution (e.g., user input,
system resources). The program might crash or terminate abnormally.
Examples: Division by zero, accessing an array element out
of bounds, trying to open a file that doesn't exist, insufficient memory.
Detection: Occur during program execution, often leading to
a program crash or an error message.
Aspect |
Syntax Error |
Semantic Error |
Runtime Error |
Definition |
Violation of language grammar or structure |
Code is grammatically correct but does not
do what was intended |
Error occurs during execution despite
syntactically and semantically correct code |
Detection Phase |
Compile-time (or interpretation phase) |
Often compile-time, but may only be noticed
at runtime |
Runtime (during program execution) |
Example |
if (x > 5 → missing closing parenthesis |
int x = "hello"; → type mismatch
or incorrect logic |
int a = 5/0; → division by zero |
Impact |
Prevents code from compiling or running |
Code runs but produces incorrect or
unintended results |
Program crashes or throws exceptions |
Ease of Detection |
Easy; compiler/interpreter flags it |
Hard; requires logical analysis or testing |
Moderate; often flagged by runtime
environment |
Fix Strategy |
Correct the syntax (e.g., punctuation,
keywords) |
Refactor logic or correct type usage |
Add error handling (e.g., try-catch, input
validation) |
5.1.5 Control Structures: Sequence,
Selection, and Iteration
Control structures dictate the flow of execution in a
program:
1) Sequence: This is the most basic control
structure, where instructions are executed one after another in the order they
appear in the program. This is the default flow of execution.
2) Selection (Conditional/Decision): This structure
allows the program to make decisions and execute different blocks of code based
on whether a certain condition is true or false.
3) Iteration (Looping/Repetition): This structure
allows a block of code to be executed repeatedly as long as a certain condition
is met or for a specified number of times.
5.1.6 Program Design Tools – Algorithm,
Flowchart, and Pseudocode
These tools are used to plan and design the logic of a
program before writing the actual code:
1) Algorithm: A step-by-step, unambiguous, and finite
set of instructions for solving a problem or accomplishing a task. Algorithms
are language-independent and focus purely on the logic.
Ø
Characteristics: Unambiguous, input, output,
finiteness, effectiveness.
Ø
Examples:
Q1. Write an algorithm to calculate simple interest.
Step 1: Start
Step 2: Read the value of P, T, R
Step 3: Calculate simple interest by using I =(P*T*R)/100
Step 4: Display simple interest(I)
Step 5: Stop
Q2. Write an algorithm to check greatest number among two
number.
Step 1: Start
Step 2: Read any two-number a, b
Step 3: check if (a>b)
If yes,
Display the greatest number is “a” and go to step 4
If no,
Display the greatest number is “b” and go to step 4
Step 4: Stop
2) Flowchart: A graphical representation of an
algorithm or process, showing the steps as boxes of various kinds, and their
order by connecting them with arrows. Each type of box represents a specific
type of operation (e.g., input/output, processing, decision).
Standard symbols used in Flowchart:
Advantages: Visual representation, easy to understand logic.
Disadvantages: Can become complex for large programs,
difficult to modify.
Examples:
Q1. Draw flowchart to calculate simple interest.
Q2. Draw flowchart to find greatest number among two
numbers.
3) Pseudocode: A high-level, informal description of
an algorithm's logic, using a mixture of natural language and programming-like
constructs. It is not executable code but helps in planning the program's
structure without worrying about the strict syntax of a specific programming
language.
Example (Pseudocode for calculating the sum of two
numbers):
BEGIN
INPUT number1
INPUT number2
SET sum = number1
+ number2
PRINT sum
END
5.1.7 Absolute Binary, BCD, ASCII, and
Unicode
These are different ways to represent data, especially
characters and numbers, in computer systems:
1. Absolute Binary (Pure Binary)
Ø
Represents numbers in base-2 (only 0s
and 1s).
Ø
Directly corresponds to the computer's hardware
representation.
Ø
Used in low-level computing (machine code, CPU
operations).
Ø
Example:
o
Decimal 5 → 0101 in 4-bit
binary.
o
Decimal 13 → 1101 in 4-bit
binary.
2. BCD (Binary-Coded Decimal)
Ø
Encodes each decimal digit (0–9)
into a 4-bit binary.
Ø
Used in financial systems, calculators, and
digital displays where exact decimal representation is crucial.
Ø
Example:
o
Decimal 25 → 0010 0101 (2
→ 0010, 5 → 0101).
Ø
Advantage: Avoids rounding errors in
decimal arithmetic.
3. ASCII (American Standard Code for Information
Interchange)
Ø
A 7-bit character encoding standard
representing 128 characters (letters, digits, symbols, control
codes).
Ø
Extended ASCII uses 8 bits (256
characters).
Ø
Example:
o
'A' → 65 (decimal) → 01000001 (binary).
Ø
Limitation: Only supports English and
basic symbols.
4. Unicode
Ø
A universal character encoding standard supporting over
140,000 characters (languages, emojis, symbols).
Ø
Uses variable-length encoding (UTF-8,
UTF-16, UTF-32):
o
UTF-8: Backward-compatible with ASCII
(1–4 bytes per character).
o
UTF-16: Uses 2 or 4 bytes per character.
o
UTF-32: Fixed 4 bytes per character.
Ø
Example:
o
'A' (ASCII-compatible) → U+0041 → 41 in
UTF-8.
Key Differences
Feature |
Absolute Binary |
BCD |
ASCII |
Unicode |
Purpose |
Numeric (base-2) |
Decimal digit encoding |
Text encoding |
Universal text
encoding |
Bits/Char |
Variable
(e.g., 8-bit) |
4 bits per
digit |
7/8 bits per
character |
1–4 bytes
(UTF-8) |
Coverage |
Numbers only |
Numbers (0–9) |
English + basic
symbols |
All languages + emojis |
Example Use |
CPU
operations |
Calculators,
finance |
Early
computers |
Modern
web/text |
When to Use Which?
- Absolute
Binary: Low-level programming, hardware control.
- BCD:
Financial systems requiring exact decimal precision.
- ASCII:
Legacy systems, minimal English text.
- Unicode (UTF-8): Modern applications, multilingual support.
5.2 C
Programming Language
5.2.1
Introduction and Features of C Language
Introduction:
Ø
C is a procedural, high-level,
and general-purpose programming language developed by Dennis
Ritchie in 1972 at Bell Labs.
Ø
It was designed for system programming (OS,
compilers, drivers) but is also used in application development.
Ø
Influenced languages like C++, Java, Python, and
C#.
Features of C:
- Simple
& Portable: Easy syntax, machine-independent (compiled for
different platforms).
- Fast
& Efficient: Close to hardware (low-level memory access).
- Structured
Language: Supports functions, loops, and modular programming.
- Rich
Library Support: Built-in functions for I/O, math, string handling,
etc.
- Pointers
& Memory Management: Direct memory manipulation using pointers.
- Extensible:
Supports user-defined functions and libraries.
5.2.2
Structure of a C Program
A basic C program has the following structure:
#include <stdio.h> //
Preprocessor directive (header file)
int main() //
Main function (entry point)
{
printf("Hello, World!"); // Statement
return 0; // Exit status
}
Components:
- Preprocessor
Directives (#include): Includes header files.
- Main
Function (int main()): Program execution starts here.
- Statements: Instructions (e.g., printf).
- Return
Statement (return 0): Indicates successful execution.
5.2.3 C Preprocessor and Header Files
Preprocessor
Ø Runs
before compilation.
Ø Processes
directives starting with #.
Ø Examples:
#include <stdio.h>
// Includes standard I/O functions
#define PI 3.14 //
Macro definition
Header Files:
Ø Contain
function declarations and macros.
Ø Common
headers:
a)
stdio.h: Input/output functions
(printf, scanf).
b)
math.h: Math operations (sqrt, pow).
c)
string.h: String handling
(strcpy, strlen).
5.2.4 Character Set used in C
In C programming, the character set means all the letters, digits, and symbols that can be used to write a C program. These characters are used to form C tokens like keywords, identifiers, constants, and operators.
The character set in C mainly includes:
-
Alphabets:
-
Uppercase letters:
A
toZ
-
Lowercase letters:
a
toz
-
Both uppercase and lowercase are treated as different (case-sensitive).
-
-
Digits:
0
to9
(Used to form numbers but cannot be the first character of an identifier). -
Special Characters: Symbols used for operators, punctuation, and other purposes. Examples: + - * / = < > % & | ^ ! ~ ? : ; , . # ( ) { } [ ]
-
White Space Characters:
-
Space, tab (
\t
), new line (\n
), etc. -
Used to separate tokens and improve readability.
5.2.5 Use of Comments
In C programming, comments are notes written in the program to explain the code. The compiler ignores comments, so they do not affect program execution.
They help make the code easier to understand for yourself and others.
Types of comments in C:
-
Single-line comment
-
Starts with
//
and goes till the end of the line. -
Example:
-
-
Multi-line comment
-
Starts with
/*
and ends with*/
. -
Can span across multiple lines.
-
Example:
5.2.6
Identifiers, Keywords, and Tokens
1. Identifiers:
Ø
Identifiers are names given to variables,
functions, arrays, structures, etc. in a C program.
Ø
Rules for naming identifiers:
o
Must begin with a letter or underscore (_).
o
Can contain letters, digits, and underscores.
o
Cannot be a keyword.
o
Case-sensitive (e.g., total and Total are
different).
Ø
Examples: sum, count_1, _totalMarks.
2. Keywords:
Ø Keywords
are pre-defined words that have special meaning in C and are reserved by the
compiler.
Ø Cannot
be used as identifiers.
Ø Examples:
int, float, if, else, return, for, while.
3. Tokens:
Ø Tokens
are the smallest units in a C program that have meaning to the compiler.
Ø Types
of tokens in C:
- Keywords
– e.g., if, return
- Identifiers
– e.g., total, count
- Constants
– e.g., 10, 3.14
- Strings
– e.g., "Hello"
- Operators
– e.g., +, -, *, /
- Punctuators/Special
symbols – e.g., {, }, ;, ,
5.2.7 Basic Data Types in C /5.2.9 Type of Specifier
C supports the following fundamental data types:
Data Type |
Size (bytes) |
Range |
Format Specifier |
Example |
int |
2 or 4 |
-32,768 to 32,767 (16-bit) |
%d |
int x = 10; |
char |
1 |
-128 to 127 (signed) |
%c |
char ch =
'A'; |
float |
4 |
1.2E-38 to 3.4E+38 (6-7
decimal digits) |
%f |
float f =
3.14; |
double |
8 |
2.3E-308 to 1.7E+308 (15-16
decimal digits) |
%lf |
double d =
3.14159; |
void |
- |
No value
(used for functions & pointers) |
- |
void |
5.2.8
Constants and Variables
Variables:
Ø Variables
are named storage locations in memory that can hold different values during the
execution of a program.
Ø The
value stored in a variable can change anytime.
Ø Before
using a variable, it must be declared with a data type.
Ø Example:
int age = 20; // 'age' is a variable that can change
age = 25; // value of 'age' changed to 25
Constants:
Ø Constants
are fixed values that do not change during the program execution.
Ø Once
a constant is assigned a value, it cannot be altered.
Ø Constants
are used when the value must remain the same throughout the program.
Ø In
C, constants can be declared using the const keyword or by using #define
preprocessor directive.
Ø
Examples:
- Using const
keyword:
const int
MAX_AGE = 100;
- Using #define:
#define
PI 3.1416
5.2.10
Simple and Compound Statements
1) Simple Statement:
A simple statement is a single instruction that ends with a semicolon (;). It
tells the computer to perform one action.
Example:
int x = 10;
x = x + 5;
printf("%d", x);
2) Compound Statement (Block):
A compound statement is a group of simple statements enclosed within braces { }.
It is treated as a single statement by the compiler.
Compound statements are used when multiple instructions need to be executed
together.
Example:
{
int x = 10;
x = x + 5;
printf("%d",
x);
}
5.2.11
Operators and Expressions
Operators are special symbols in C used to perform
operations on variables and values.
An expression is a combination of variables,
constants, and operators that produces a value.
Different types of operators are as follows:
1. Arithmetic Operators: Used for mathematical
calculations.
Operator |
Meaning |
Example |
Result |
+ |
Addition |
5 + 3 |
8 |
- |
Subtraction |
10 - 4 |
6 |
* |
Multiplication |
4 * 2 |
8 |
/ |
Division |
10 / 2 |
5 |
% |
Modulus
(remainder) |
10 % 3 |
1 |
2. Relational Operators
Used to compare two values; result is true (1) or false (0).
Operator |
Meaning |
Example |
Result |
== |
Equal to |
5 == 5 |
1 (true) |
!= |
Not equal to |
5 != 3 |
1 (true) |
> |
Greater than |
7 > 3 |
1 (true) |
< |
Less than |
2 < 5 |
1 (true) |
>= |
Greater than
or equal |
5 >= 5 |
1 (true) |
<= |
Less than or
equal |
3 <= 4 |
1 (true) |
3. Logical Operators: Used to combine multiple
conditions.
Operator |
Meaning |
Example |
Result |
&& |
Logical AND |
(5 > 3)
&& (2 < 4) |
1 (true) |
|| |
Logical OR |
(5 > 3) || (2 > 4) |
1 (true) |
! |
Logical NOT
(negation) |
!(5 > 3) |
0 (false) |
4. Assignment Operators
Used to assign values to variables.
Operator |
Meaning |
Example |
Explanation |
= |
Simple
assignment |
x = 5; |
Assigns 5 to
x |
+= |
Add and
assign |
x += 3; |
Same as x = x
+ 3; |
-= |
Subtract and
assign |
x -= 2; |
Same as x = x
- 2; |
*= |
Multiply and
assign |
x *= 4; |
Same as x = x
* 4; |
/= |
Divide and
assign |
x /= 2; |
Same as x = x
/ 2; |
%= |
Modulus and
assign |
x %= 3; |
Same as x = x
% 3; |
5. Unary Operators: Operators with one operand.
Operator |
Meaning |
Example |
Result |
++ |
Increment by
1 |
x++ or ++x |
Increases x
by 1 |
-- |
Decrement by
1 |
x-- or --x |
Decreases x
by 1 |
+ |
Unary plus
(positive) |
+x |
Returns value
of x |
- |
Unary minus
(negative) |
-x |
Returns
negative of x |
! |
Logical NOT |
!x |
Returns
opposite boolean |
6. Conditional (Ternary) Operator: A shorthand for if-else
with three operands:
condition ? expression_if_true : expression_if_false;
Example:
int max = (a > b) ? a : b;
Explanation: If a > b is true, max gets a; otherwise, max
gets b.
5.2.12
Input/output (I/O) Functions
Input/Output (I/O) functions are used to interact
with the user or external devices.
Ø Input
functions: Take data from the user (keyboard, file, etc.) into the program.
Ø Output
functions: Display data from the program to the user (screen, file, etc.).
Common Input Functions are as follows:
Function |
Purpose |
scanf() |
Reads formatted input
from the keyboard |
getchar() |
Reads a
single character from the keyboard |
gets() (unsafe) |
Reads a string until
newline |
fgets() |
Reads a
string safely |
Common Output Functions are as follows:
Function |
Purpose |
printf() |
Displays formatted
output on screen |
putchar() |
Prints a
single character |
puts() |
Prints a string
followed by newline |
5.2.13
Selection Control Statements (Decision Making)
Selection statements allow a program to choose
between different actions based on a condition (true/false).
1. if Statement:
Executes a block of code if a condition is true.
Syntax:
if (condition)
{
// statements
}
Example:
#include <stdio.h>
int main()
{
int a;
printf("Enter a number: ");
scanf("%d",&a);
if(a>0)
{
printf("%d is a positive number",a);
}
return 0;
}
2. if-else Statement:
Executes one block if the condition is true, another block
if false.
Syntax:
if (condition)
{
// statements if
true
}
else
{
// statements if
false
}
Example:
#include <stdio.h>
int main()
{
int a;
printf("Enter a number: ");
scanf("%d",&a);
if(a>0)
{
printf("%d is a positive number",a);
}
else
{
printf("%d is a negative number",a);
}
return 0;
}
3. if-else-if Ladder:
Checks multiple conditions in sequence.
Syntax:
if (condition1)
{
// statements
}
else if (condition2)
{
// statements
}
else
{
// statements
}
Example:
#include <stdio.h>
int main()
{
int a;
printf("Enter a number: ");
scanf("%d",&a);
if(a>0)
{
printf("%d is a positive number",a);
}
else if(a<0)
{
printf("%d is a negative number",a);
}
else
{
printf("%d is a Zero",a);
}
return 0;
}
4. Nested if:
An if statement inside another if. Used for more
specific checks.
Example:
int num ;
printf("Enter a number: ");
scanf("%d",&num);
if (num > 0)
{
if (num % 2 == 0)
{
printf("Positive even number");
}
else
{
printf("Positive
odd number");
}
}
5. switch Statement:
Used for multiple-choice decisions based on a single
variable’s value.
Syntax:
switch(expression)
{
case value1:
// statements
break;
case value2:
// statements
break;
default:
// statements
if no case matches
}
Example:
#include <stdio.h>
int main()
{
int day;
printf("Enter a day:");
scanf("%d",&day);
switch(day)
{
case 1:
printf("Sunday");
break;
case 2:
printf("Monday");
break;
case 3:
printf("Tuesday");
break;
case 4:
printf("Wednesday");
break;
case 5:
printf("Thusday");
break;
case 6:
printf("Friday");
break;
case 7:
printf("Saturday");
break;
default:
printf("Invalid Number, Enter in betwwen 1-7");
return 0;
}
5.2.14
Iteration Control Statements (Looping)
Loops are used to repeat a block of code multiple times
until a condition is met.
1. while Loop:
Repeats a block while the condition is true. Check condition
first, then execute.
Syntax:
while(condition)
{
// statements
}
Example:
int i = 1;
while(i <= 5)
{
printf("%d\n",
i);
i++;
}
2. do-while Loop:
Executes the block at least once, then checks the condition.
Syntax:
do
{
// statements
} while(condition);
Example:
int i = 1;
do
{
printf("%d\n", i);
i++;
} while(i <= 5);
3. for Loop:
Repeats a block for a fixed number of times.
Syntax:
for(initialization; condition; increment/decrement)
{
// statements
}
Example:
4. Nested Loops:
A loop inside another loop. Useful for tables, patterns,
matrices.
Example:
for(int i = 1; i <= 3; i++)
{
for(int j = 1; j
<= 3; j++)
{
printf("%d ", j);
}
printf("\n");
}
Output:
1 2 3
1 2 3
1 2 3
Summary Table(Imp for MCQS):
Loop Type |
Condition Check |
Runs at least once? |
Usage |
while |
Before loop |
No |
Unknown iterations |
do-while |
After loop |
Yes |
At least once
execution |
for |
Before each iteration |
No |
Fixed iterations |
1. Write a C program to input an arbitrary number and find out whether it is positive or negative.
Ans:
#include <stdio.h>
int main()
{
int num;
printf("Enter
a number: ");
scanf("%d", &num);
if (num > 0)
printf("Positive");
else if (num <
0)
printf("Negative");
else
printf("Zero");
return 0;
}
2. For any integer input through the keyboard, write a C
program to find out whether it is an odd number or even number.
Ans:
#include <stdio.h>
int main()
{
int num;
printf("Enter
an integer: ");
scanf("%d", &num);
if (num % 2 == 0)
printf("Even");
else
printf("Odd");
return 0;
}
3. Write a C program that reads three numbers and
displays the largest among them.
Ans:
#include <stdio.h>
int main()
{
int a, b, c;
printf("Enter
three numbers: ");
scanf("%d %d
%d", &a, &b, &c);
if (a >= b
&& a >= c)
printf("Largest = %d", a);
else if (b >= a
&& b >= c)
printf("Largest = %d", b);
else
printf("Largest = %d", c);
return 0;
}
4. Write an algorithm, flowchart, and C program that
checks whether the number entered by the user is exactly divisible by 5 but not
by 11.
Ans:
#include <stdio.h>
int main()
{
int n;
printf("Enter
a number: ");
scanf("%d", &n);
if (n % 5 == 0
&& n % 11 != 0)
printf("Number is divisible by 5 but not by 11");
else
printf("Condition not met");
return 0;
}
5. Write a C program to read any year and check whether
the entered year is a leap or not.
Ans:
#include <stdio.h>
int main()
{
int year;
printf("Enter
a year: ");
scanf("%d", &year);
if ((year % 400 ==
0) || (year % 4 == 0 && year % 100 != 0))
printf("Leap Year");
else
printf("Not a Leap Year");
return 0;
}
6. Write a program to find the commission amount on the
basis of sales amount as per the following conditions:
- Sales amount
(Rs.) 0-1000: 5% commission
- Sales amount
(Rs.) 1001-2000: 10% commission
- Sales amount
(Rs.) >2000: 12% commission
Ans:
#include <stdio.h>
int main()
{
float sales,
commission;
printf("Enter
sales amount: ");
scanf("%f", &sales);
if (sales <=
1000)
commission =
0.05 * sales;
else if (sales
<= 2000)
commission =
0.10 * sales;
else
commission =
0.12 * sales;
printf("Commission amount = %f", commission);
return 0;
}
7. Write a program to display the name of the day on the
basis of entered number 1 to 7. [For example: 1 for Sunday, 2 for Monday, ... 7
for Saturday]
Ans: See from Note’s Switch Case Example
8. Write a program to calculate the area of a circle, a
rectangle or a triangle depending upon the user's choice.
Ans:
#include <stdio.h>
int main()
{
int choice;
float area, r, l,
b, h;
printf("1.
Circle\n2. Rectangle\n3. Triangle\nEnter your choice: ");
scanf("%d", &choice);
switch(choice)
{
case 1:
printf("Enter radius: ");
scanf("%f", &r);
area =
3.1416 * r * r;
printf("Area of Circle = %.2f", area);
break;
case 2:
printf("Enter length and breadth: ");
scanf("%f %f", &l, &b);
area = l *
b;
printf("Area of Rectangle = %.2f", area);
break;
case 3:
printf("Enter base and height: ");
scanf("%f %f", &b, &h);
area = 0.5
* b * h;
printf("Area of Triangle = %.2f", area);
break;
default:
printf("Invalid Choice");
}
return 0;
}
9. Write a program that finds the sum, difference, and
product of 2 numbers using a switch case statement.
Ans:
#include <stdio.h>
int main()
{
int a, b;
char ch;
printf("Enter
two numbers: ");
scanf("%d
%d", &a, &b);
printf("Enter
choice (s=Sum, d=Difference, p=Product): ");
scanf("
%c", &ch);
switch(ch)
{
case 's':
printf("Sum = %d", a + b);
break;
case 'd':
printf("Difference = %d", a - b);
break;
case 'p':
printf("Product = %d", a * b);
break;
default:
printf("Invalid choice");
}
return 0;
}
10. Write a program to display the name of the day in a
week, depending on the number entered through the keyboard using the
switch-case statement.
Ans:
#include <stdio.h>
int main()
{
int day;
printf("Enter
a number (1 or more): ");
scanf("%d", &day);
switch(day % 7)
{
case 1:
printf("Sunday"); break;
case 2:
printf("Monday"); break;
case 3:
printf("Tuesday"); break;
case 4:
printf("Wednesday"); break;
case 5:
printf("Thursday"); break;
case 6:
printf("Friday"); break;
case 0:
printf("Saturday"); break;
}
return 0;
}
[A] Some Practical Questions from “5.2.14 Iteration Control Statements (Looping)”
1. Write a program to find the sum of first 50 natural
numbers.
Ans:
#include <stdio.h>
int main()
{
int i, sum = 0;
for (i = 1; i
<= 50; i++)
{
sum = sum + i;
}
printf("Sum
of first 50 natural numbers = %d", sum);
return 0;
}
or
#include <stdio.h>
int main()
{
int i = 1, sum =
0;
while (i <= 50)
{
sum = sum + i;
i++;
}
printf("Sum
of first 50 natural numbers = %d", sum);
return 0;
}
2. Write a C program to display the sum of 'odd' numbers
from 1 to 10.
Ans:
#include <stdio.h>
int main()
{
int i, sum = 0;
for (i = 1; i
<= 10; i++)
{
if (i % 2 !=
0)
{
sum = sum
+ i;
}
}
printf("Sum
of odd numbers from 1 to 10 = %d", sum);
return 0;
}
or
#include <stdio.h>
int main()
{
int i = 1, sum =
0;
while (i <= 10)
{
if (i % 2 !=
0)
{
sum = sum
+ i;
}
i++;
}
printf("Sum
of odd numbers from 1 to 10 = %d", sum);
return 0;
}
3. Write a program to find the sum of the cubes of the
first 10 numbers. (i.e. 1³ + 2³ + 3³ + 4³ + ... + 10³)
4. Write a C program to display the multiplication table
of a given number.
Ans:
#include <stdio.h>
int main()
{
int n, i;
printf("Enter
a number: ");
scanf("%d", &n);
printf("Multiplication Table of %d\n", n);
for (i = 1; i
<= 10; i++)
{
printf("%d x %d = %d\n", n, i, n * i);
}
return 0;
}
5. Write a program to read a number and display it in
reverse order.
Ans:
#include <stdio.h>
int main()
{
int num, rem, rev
= 0;
printf("Enter
a number: ");
scanf("%d", &num);
while(num != 0)
{
rem = num %
10;
rev = rev * 10
+ rem;
num /= 10;
}
printf("Reversed number = %d", rev);
return 0;
}
6. Write a program to check whether the given number is a
palindrome or not.
Ans:
#include <stdio.h>
int main()
{
int num, rem, rev
= 0, original;
printf("Enter
a number: ");
scanf("%d", &num);
original =
num; // Save the original number
while(num != 0)
{
rem = num %
10;
rev = rev * 10
+ rem;
num /= 10;
}
printf("Reversed number = %d\n", rev);
if(original ==
rev)
printf("%d is a palindrome.", original);
else
printf("%d is not a palindrome.", original);
return 0;
}
7. Write a program to find the factorial of a given
positive number.
Ans:
#include <stdio.h>
int main()
{
int n, i, fact =
1;
printf("Enter
a positive number: ");
scanf("%d", &n);
if (n < 0)
{
printf("Factorial not possible for negative numbers");
}
else
{
for (i = 1; i
<= n; i++)
{
fact =
fact * i;
}
printf("Factorial of %d is %d", n, fact);
}
return 0;
}
8. Write a program to input an integer number and checks
whether it is prime or composite.
Ans:
#include
<stdio.h>
int main()
{
int n, i, count = 0;
printf("Enter a number: ");
scanf("%d", &n);
if (n <= 1)
{
printf("Number is neither prime
nor composite");
}
else
{
for (i = 1; i <= n; i++)
{
if (n % i == 0)
count++;
}
if (count == 2)
printf("%d is Prime", n);
else
printf("%d is Composite",
n);
}
return 0;
}
5.2.15 Array: definition, types (1D and
2D), matrix addition and subtraction
An array in C is a collection of elements of the same
data type stored in contiguous memory locations. It allows us to group and
manage multiple values under a single variable name.
Types of Arrays in C:
There are mainly three types of arrays in C language:
- One –
dimensional arrays (1D Array)
- Two –
dimensional arrays (2D Array)
- Multi
– dimensional arrays
1.
One-Dimensional Array (1D Array)
Definition:
A 1D array is a linear list of elements of the same
type stored in continuous memory.
Declaration:
data_type array_name[size];
Example:
int marks[5];
Initialization:
int marks[5] = {10, 20, 30, 40, 50};
Accessing:
Use index numbers (start from 0).
printf("%d", marks[2]); // prints 60
Simple Example (Printing a list of 5 numbers):
#include <stdio.h>
int main()
{
int i, numbers[5]
= {10, 20, 30, 40, 50};
for(i=0; i<5;
i++)
{
printf("%d\t",numbers[i]);
}
return 0;
}
Output:
10 20 30
40 50
Practical Based Questions using a single dimensional array:
1. Write a C program to ask ten numbers from the user and
display them using array.
Ans:
#include <stdio.h>
int main()
{
int numbers[10],
i;
printf("Enter
10 numbers:\n");
for(i = 0; i <
10; i++)
{
scanf("%d", &numbers[i]);
}
printf("The
number you entered are:\n");
for(i = 0; i <
10; i++)
{
printf("%d", numbers[i]);
}
return 0;
}
2. Write a C program to store 10 numbers in an array and
print out the greatest number among them.
Ans:
#include <stdio.h>
int main()
{
int numbers[10],
i, greatest;
// Input 10
numbers
printf("Enter
10 numbers:\n");
for(i = 0; i <
10; i++)
{
scanf("%d", &numbers[i]);
}
// Assume first
number is greatest
greatest =
numbers[0];
// Compare with
others
for(i = 1; i <
10; i++)
{
if(numbers[i]
> greatest)
{
greatest =
numbers[i];
}
}
// Display
greatest number
printf("The
Greatest number is %d\n", greatest);
return 0;
}
3. Write an algorithm and C program to read the salaries
of 200 employees and count the number of employees getting a salary of 5000 to
10000.
Ans:
#include <stdio.h>
int main()
{
int salary[200],
i, count = 0;
// Read salaries
of 200 employees
printf("Enter
the salaries of 200 employees:\n");
for(i = 0; i <
200; i++)
{
scanf("%d", &salary[i]);
}
// Count employees
with salary between 5000 and 10000
for(i = 0; i <
200; i++)
{
if(salary[i]
>= 5000 && salary[i] <= 10000)
{
count++;
}
}
printf("Number of employees with salary between 5000 and 10000 =
%d\n", count);
return 0;
}
4. Write a C program to enter 10 integers into an array
and sort them in ascending order.
Ans:
#include <stdio.h>
int main() {
int numbers[10],
i, j, temp;
// Input 10
numbers
printf("Enter
10 numbers:\n");
for(i = 0; i <
10; i++)
{
scanf("%d", &numbers[i]);
}
// Sort in
ascending order (simple selection sort)
for(i = 0; i <
10; i++)
{
for(j = i + 1;
j < 10; j++)
{
if(numbers[i] > numbers[j])
{
temp =
numbers[i];
numbers[i] = numbers[j];
numbers[j] = temp;
}
}
}
// Display sorted
numbers
printf("Numbers in ascending order:\n");
for(i = 0; i <
10; i++)
{
printf("%d ", numbers[i]);
}
return 0;
}
2.
Two-Dimensional Array (2D Array)