Programming Concepts and Logics
Computer Science тАУ Grade XI
Unit 5: Programming Concepts and Logics
Topics covered: 5.1 Programming Concepts ┬╖ 5.2 C Programming Language
5.1 Programming Concepts
5.1.1 Program and Programmer
A program is a set of instructions, written in a programming language, that tells the computer how to perform a task or solve a problem.
Programming (coding) is the process of writing, testing and maintaining programs.
A programmer is a person who designs, writes, tests, debugs and maintains computer programs. A programmer needs knowledge of programming languages, algorithms and problem solving.
Features of a Good Program
| Feature | Meaning |
|---|---|
| Integrity | Gives correct and complete output for valid input; data is not corrupted |
| Clarity | Easy to read and understand; no confusing statements |
| Simplicity | Uses the simplest logic that solves the problem |
| Efficiency | Runs fast and uses little memory |
| Maintainability | Easy to modify, update and fix later |
| Reliability | Works correctly every time under the expected conditions |
| Generality | Works for a wide range of inputs and on different platforms |
| Modularity | Divided into small independent parts (modules/functions) |
| Robustness | Handles wrong input and unexpected situations without crashing |
| Documentation | Has comments and a user manual to help users and future programmers |
Difference between Program and Software
| Program | Software |
|---|---|
| A set of instructions to perform one specific task | A collection of programs, data and documentation |
| Smaller in size and scope | Larger and more complex |
| A component (part) of software | Made up of many programs working together |
| Usually written by one programmer | Usually developed by a team |
| Not usually sold with a licence | Usually distributed with a licence |
| Example: a program to find simple interest | Example: MS Word, Photoshop, Windows |
5.1.2 Programming Languages
A programming language is an artificial language with a set of rules (syntax) and symbols used to write programs. A computer actually understands only machine language (0s and 1s), so programs written in other languages must be translated.
A. Low-Level Languages
Languages that are close to the hardware and depend on the computer's architecture (machine-dependent).
1. Machine language (First generation, 1GL)
- Written only in binary (0 and 1); the only language the CPU understands directly.
- Advantages: fastest execution; no translator needed.
- Disadvantages: very hard to write, read and debug; machine-dependent; time-consuming; high chance of errors.
2. Assembly language (Second generation, 2GL)
- Uses mnemonic (symbolic) codes such as
ADD,SUB,MOV,CMPinstead of 0s and 1s. - Needs an assembler to convert it into machine language.
- Advantages: easier than machine language; easier to find and correct errors; fast and gives direct hardware control.
- Disadvantages: machine-dependent; mnemonics must be remembered; needs a translator; harder than high-level languages.
| Machine Language | Assembly Language |
|---|---|
| Written in 0s and 1s | Written in mnemonic codes (ADD, SUB, MOV) |
| Directly understood by the computer | Needs an assembler |
| First-generation language | Second-generation language |
| Very difficult to write and debug | Easier to write and debug |
| Slightly faster execution | Slightly slower (translation needed) |
B. High-Level Languages
Languages that use English-like words and mathematical symbols. They are machine-independent (portable) and need a compiler or interpreter.
- Advantages: easy to learn, write and debug; machine-independent; easier to maintain; better documentation; lower development cost.
- Disadvantages: need translation, so execution is slower; use more memory; less direct control over hardware.
| Generation | Type | Description | Examples |
|---|---|---|---|
| 3GL | Procedural languages | The programmer writes how to solve the problem step by step | C, Pascal, FORTRAN, COBOL, BASIC |
| 4GL | Problem-oriented languages | The programmer states what is required; used for databases and reports | SQL, report generators (some textbooks also list Visual Basic, PHP) |
| 5GL | Natural / AI languages | Based on constraints and logic, used for artificial intelligence | Prolog, Lisp, Mercury |
Some Popular High-Level Languages
| Language | Full form / Use |
|---|---|
| FORTRAN | Formula Translation: first high-level language, for science and engineering |
| COBOL | Common Business Oriented Language: business and data processing |
| BASIC | Beginner's All-purpose Symbolic Instruction Code: for beginners |
| Pascal | Structured programming; used for teaching |
| C / C++ | System software, applications; C++ adds object-oriented features |
| Java | Object-oriented; web and mobile applications |
| Python | General-purpose, easy to learn; data science and AI |
| JavaScript, PHP | Web development (client side / server side) |
| SQL | Database queries |
5.1.3 Language Translators (Language Processors)
A language translator converts a program written in one language (source program) into machine language (object program).
| Translator | Converts | Method |
|---|---|---|
| Assembler | Assembly language тЖТ machine language | Translates assembly code |
| Compiler | High-level language тЖТ machine language | Translates the whole program at once |
| Interpreter | High-level language тЖТ machine language | Translates and executes one statement at a time |
Difference between Compiler and Interpreter
| Compiler | Interpreter |
|---|---|
| Translates the whole program at once | Translates one line at a time |
| Creates a separate object (executable) file | Does not create an object file |
| Shows all errors after compiling the whole program | Stops and shows an error as soon as it finds one |
| Execution is faster after compilation | Execution is slower (translation every time) |
| Debugging takes more effort (errors listed together) | Easier to find the line with the error |
| Needs more memory to store the object code | Needs less memory |
| Examples: C, C++, Pascal | Examples: BASIC, Python, Ruby |
Some languages, such as Java and Python, use both methods (first compile to an intermediate code, then interpret it).
5.1.4 Errors, Testing and Debugging
A bug (error) is a mistake in a program that causes wrong or unexpected behaviour.
Types of Errors
| Error | Meaning | Example |
|---|---|---|
| Syntax error | Breaking the grammar rules of the language. Detected by the compiler/interpreter before the program runs | Missing semicolon, misspelled keyword (pritnf), unmatched bracket |
| Logical (semantic) error | The program runs but gives wrong output because of faulty logic. Not detected by the compiler | Using + instead of *; wrong formula for area |
| Runtime error | Occurs while the program is running and stops it abnormally | Division by zero, reading a missing file, using too much memory |
Difference between Syntax Error and Logical Error
| Syntax Error | Logical Error |
|---|---|
| Violation of the rules (grammar) of the language | Mistake in the logic or formula of the program |
| Detected by the compiler/interpreter | Not detected by the compiler |
| Program cannot run until it is fixed | Program runs but gives wrong results |
| Easy to find (the compiler shows the line) | Difficult to find; needs testing and tracing |
Syntax and semantics: Syntax is the set of rules for writing correct statements; semantics is the meaning of those statements. Example in English: "Aryan eats an apple." (correct syntax and meaning). "Aryan eats a house." (correct syntax, wrong meaning). "Aryan eat a house." (wrong syntax and meaning).
Testing
Testing is the process of running a program with different inputs to check whether it gives the expected output and to find errors.
| Testing stage | Meaning |
|---|---|
| Unit testing | Each small part (module/function) is tested separately |
| Integration testing | Modules are tested after they are joined together |
| System testing | The complete program is tested as a whole |
| User acceptance testing | The user checks whether the program meets the requirements |
Debugging
Debugging is the process of finding and correcting errors (bugs) in a program. Testing finds that an error exists; debugging finds the cause and fixes it.
5.1.5 Data Representation Codes
Computers store everything in binary. Codes assign binary patterns to numbers and characters.
| Code | Description |
|---|---|
| Pure (absolute) binary | Numbers are stored directly in base 2. The leftmost bit can be used as a sign bit (0 = positive, 1 = negative) |
| BCD (Binary Coded Decimal) | Each decimal digit is written separately as 4 bits. Example: 59 тЖТ 0101 1001 (5 = 0101, 9 = 1001) |
| ASCII (American Standard Code for Information Interchange) | 7-bit code with 128 characters (standard ASCII); 8-bit extended ASCII has 256 characters. Each character is stored in 1 byte |
| EBCDIC (Extended Binary Coded Decimal Interchange Code) | 8-bit code (256 characters), used mainly in IBM mainframe computers |
| Unicode | A universal standard that gives a unique number to the characters of all world languages (including Nepali/Devanagari) and symbols/emoji. Stored using encodings such as UTF-8, UTF-16 and UTF-32 |
Useful ASCII values
| Characters | ASCII code |
|---|---|
0 to 9 | 48 to 57 |
A to Z | 65 to 90 |
a to z | 97 to 122 |
| Space | 32 |
Lowercase letter code = uppercase letter code + 32 ('a' = 97, 'A' = 65).
#include <stdio.h>
int main(void)
{
char ch = 'A';
int code = 97;
printf("Character %c has ASCII code %d\n", ch, ch);
printf("ASCII code %d is the character %c\n", code, code);
return 0;
}
Output
Character A has ASCII code 65
ASCII code 97 is the character a
5.1.6 Programming Fundamentals
Data types
A data type tells the computer what kind of data a variable can store and how much memory it needs.
| Data type | Meaning | Example |
|---|---|---|
| Integer | Whole numbers (positive, negative, zero) | 25, тИТ7, 0 |
| Real / Floating point | Numbers with a fractional part | 3.14, тИТ0.5, 2.5e3 |
| Character | A single letter, digit or symbol | 'A', '7', '#' |
| String | A sequence of characters | "Nepal" |
| Boolean | Only two values: true or false | TRUE, FALSE |
Keyword, variable, constant
| Term | Meaning | Example |
|---|---|---|
| Keyword | A reserved word with a fixed meaning for the compiler; cannot be used as a name | int, float, if, while |
| Variable | A named memory location whose value can change during the program | age = 16; then age = 17; |
| Constant | A value that does not change during the program | 3.14, 100, 'A' |
Operation, operand, operator
| Term | Meaning | Example |
|---|---|---|
| Operation | An action performed on data | addition, comparison, input/output |
| Operand | The data (value or variable) on which the operation is done | a, b in a + b |
| Operator | A symbol that performs the operation | +, -, *, /, >, && |
In c = a + b, the operands are a and b, the operator is + (and =), and the whole line is a statement.
Programming statements
| Statement | Meaning | Example |
|---|---|---|
| Simple statement | A single instruction (assignment, calculation, or a test) | L = 10; area = L * B; |
| Compound statement | A group of statements enclosed in { } and treated as one unit | { a = 5; b = 6; sum = a + b; } |
| Control statement | A statement that controls the order of execution (decision and repetition) | if, switch, while, for |
5.1.7 Program Design Tools
Before writing a program, the logic is planned using tools: algorithm, flowchart, pseudocode, decision tree and decision table.
1. Algorithm
An algorithm is a finite, step-by-step set of instructions to solve a problem, written in simple English.
Properties of a good algorithm
- Input: zero or more inputs are given
- Output: produces at least one output
- Definiteness: each step is clear and unambiguous
- Finiteness: ends after a finite number of steps
- Effectiveness: each step is simple enough to be carried out
- Language independent: can be written as a program in any language
Example: algorithm to find simple interest
- Start
- Input P, T and R
- Calculate SI = (P ├Ч T ├Ч R) / 100
- Display SI
- End
2. Flowchart
A flowchart is a graphical (diagram) representation of an algorithm, using standard symbols joined by arrows.
Flowchart symbols
| Symbol | Name | Use |
|---|---|---|
| Oval (rounded) | Terminal | Start or End |
| Parallelogram | Input / Output | Reading input or printing output |
| Rectangle | Process | Calculation or assignment |
| Diamond | Decision | Condition with Yes/No (True/False) branches |
| Circle | Connector | Joins parts of a flowchart (on the same or another page) |
| Arrow | Flow line | Shows the direction of flow |
Flowchart: simple interest
Types of flowchart
| System Flowchart | Program Flowchart |
|---|---|
| Shows the overall flow of data and operations in a whole system | Shows the detailed logic of a single program |
| Gives a general overview | Gives step-by-step detail |
| Used by system analysts | Used by programmers |
Advantages of flowcharts: easy communication, better analysis of the problem, proper documentation, easier coding, easier debugging, easier maintenance. Disadvantages: complex logic makes large and confusing charts; difficult to modify; time-consuming to draw; no standard way to show details of a program.
3. Pseudocode
Pseudocode is an informal description of a program's logic using English-like statements that resemble programming code. It is not a real program and cannot be run.
Input Length, Breadth, Height
Volume = Length * Breadth * Height
Display Volume
Input Marks
IF Marks >= 40 THEN
Display "Pass"
ELSE
Display "Fail"
END IF
4. Decision tree
A decision tree is a tree-like diagram that shows the different possible decisions and their outcomes.
Example: discount decision for a shop
5. Decision table
A decision table lists conditions and the actions to be taken for each combination of conditions.
| Conditions / Actions | Rule 1 | Rule 2 | Rule 3 | Rule 4 |
|---|---|---|---|---|
| Member? | Y | Y | N | N |
| Purchase тЙе 5000? | Y | N | Y | N |
| Discount 20% | тЬФ | |||
| Discount 10% | тЬФ | |||
| Discount 5% | тЬФ | |||
| No discount | тЬФ |
5.1.8 Control Structures
A control structure (control statement) decides the order in which statements are executed. There are three basic structures.
| Structure | Meaning | C statements |
|---|---|---|
| Sequence | Statements run one after another in the order written | (ordinary statements) |
| Selection (decision / branching) | Choose between actions depending on a condition | if, if-else, else-if ladder, nested if, switch |
| Iteration (loop / repetition) | Repeat statements while a condition is true | while, do-while, for |
Selection structures: algorithm and flowchart
(a) if (one condition, one action)
Problem: check whether a number is positive.
Algorithm: 1. Start 2. Input N 3. If N > 0, display "Positive" 4. End
(b) if-else (one condition, two actions)
Problem: find the greater of two numbers.
Algorithm: 1. Start 2. Input X, Y 3. If X > Y display X is greater, else display Y is greater 4. End
(c) else-if ladder (many related conditions)
Problem: find the greatest of three numbers.
Algorithm: 1. Start 2. Input P, Q, R 3. If P > Q and P > R, P is greatest; else if Q > R, Q is greatest; else R is greatest 4. End
(d) Nested if (a condition inside another condition)
Problem: find the greater of two numbers only if both are positive.
Algorithm: 1. Start 2. Input X, Y 3. If X > 0 and Y > 0, then (if X > Y display X, else display Y); else display "not both positive" 4. End
(e) switch-case (one value, many choices)
Problem: input a number from 1 to 7 and display the day (1 = Sunday).
Algorithm: 1. Start 2. Input day 3. Switch on day: case 1 Sunday, case 2 Monday, тАж case 7 Saturday, default "Out of range" 4. End
Iteration structures: algorithm and flowchart
(a) while loop (condition checked first)
Problem: print the numbers 1 to 10.
Algorithm: 1. Start 2. I = 1 3. While I тЙд 10: display I, then I = I + 1 4. Stop
(b) do-while loop (condition checked after the body)
Problem: print the numbers from 100 down to 1.
Algorithm: 1. Start 2. A = 100 3. Do: display A, then A = A тИТ 1, while A тЙе 1 4. Stop
(c) for loop (initialization, condition and counter in one line)
Problem: print the multiplication table of 7.
Algorithm: 1. Start 2. For i = 1 to 10: m = 7 ├Ч i, display m 3. Stop
5.2 C Programming Language
5.2.1 Introduction to C
C is a general-purpose, structured (procedural) programming language developed by Dennis Ritchie at Bell Laboratories (AT&T), USA, around 1972 (developed between 1969 and 1973). It was first used to rewrite the UNIX operating system. It is called C because it came after the language B.
Development of C
- 1978: Brian Kernighan and Dennis Ritchie published the book The C Programming Language (called K&R C).
- 1989: the ANSI C standard was approved (also called C89; adopted by ISO in 1990). Later versions are C99, C11 and C17.
Features of C
- Structured and procedural: programs are divided into functions
- Middle-level language: has both high-level and low-level (bit and memory) features
- Portable: the same program can run on different computers with little change
- Fast and efficient programs
- Small language: only 32 keywords (in ANSI C), with a rich library of functions
- Extensible: users can add their own functions and libraries
- Case sensitive:
Sumandsumare different - Supports pointers and direct memory access
Advantages and Disadvantages
| Advantages | Disadvantages |
|---|---|
| Fast, efficient and portable | No object-oriented features (unlike C++/Java) |
| Easy to learn compared with other system languages | No automatic checking of array limits |
| Used on all kinds of machines, from microcontrollers to supercomputers | Pointers can cause hard-to-find errors |
| Base for many other languages (C++, Java, C#) | Weak error detection at run time |
| Rich set of operators and library functions | Large programs can become hard to manage |
Applications of C
Operating systems (UNIX, Linux kernel, parts of Windows) ┬╖ embedded systems and microcontrollers ┬╖ compilers and interpreters ┬╖ database software ┬╖ device drivers ┬╖ games and graphics ┬╖ network software.
5.2.2 Structure of a C Program
Documentation section тЖТ comments describing the program
Link section тЖТ #include header files
Definition section тЖТ #define constants
Global declaration тЖТ variables used by the whole program
main() function тЖТ the program starts here
declarations
statements
#include <stdio.h>
int main(void)
{
printf("Hello, World!\n");
return 0;
}
Output
Hello, World!
| Line | Explanation |
|---|---|
#include <stdio.h> | Includes the standard input/output header file (needed for printf and scanf) |
int main(void) | The main function; execution of every C program starts here |
{ } | Braces mark the beginning and end of the function body |
printf("..."); | Displays output on the screen |
\n | New-line character |
return 0; | Ends the program and returns 0 to the operating system, meaning success |
; | Every statement ends with a semicolon |
Comments are ignored by the compiler: // single line and /* multiple lines */.
Compiling and running a C program
5.2.3 Preprocessor Directives and Header Files
Preprocessor directives are lines beginning with # that are processed before compilation.
| Directive | Use |
|---|---|
#include | Adds the contents of a header file |
#define | Defines a constant or macro, e.g. #define PI 3.1416 |
#ifdef, #ifndef, #endif | Conditional compilation |
A header file (extension .h) contains declarations of library functions, constants and data types. It is included at the top of the program.
| Header file | Purpose | Common functions |
|---|---|---|
stdio.h | Standard input/output | printf(), scanf(), getchar(), putchar(), gets(), puts() |
conio.h | Console I/O (old Turbo C/DOS compilers only; not standard C) | getch(), clrscr() |
math.h | Mathematical functions | sqrt(), pow(), sin(), cos(), log(), ceil(), floor() |
string.h | String handling | strlen(), strcpy(), strcat(), strcmp() |
ctype.h | Character testing/conversion | toupper(), tolower(), isalpha(), isdigit() |
stdlib.h | General utilities | rand(), exit(), abs(), atoi() |
5.2.4 Character Set and Tokens
The character set of C consists of: alphabets (AтАУZ, aтАУz), digits (0тАУ9), special symbols (+ - * / = ( ) { } [ ] < > ; , . " ' ! # % & _) and white-space characters (blank, tab, new line).
Tokens are the smallest individual units of a C program.
| Token | Meaning | Example |
|---|---|---|
| Keyword | Reserved word with a fixed meaning | int, if, while, return |
| Identifier | Name given to a variable, array or function | sum, marks, main |
| Constant | Fixed value | 100, 3.14, 'A' |
| Operator | Symbol that performs an operation | +, >, && |
| Special symbol | Punctuation with special meaning | ;, { }, ( ), , |
| String | Characters in double quotes | "Nepal" |
Keywords (32 in ANSI C)
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
Rules for naming identifiers (variables)
- Must begin with a letter or underscore (
_), not a digit - May contain letters, digits and underscore only (no spaces or special symbols)
- Case sensitive (
Ageandageare different) - A keyword cannot be used as a name
- Should have a meaningful name (
total, notx1y2)
Valid: sum, _count, total_marks, num1. Invalid: 1num, total marks, int, my-name.
Constants and variables
| Type of constant | Example |
|---|---|
| Integer constant | 25, -8 |
| Real (floating) constant | 3.14, -0.5 |
| Character constant | 'A', '5' (single quotes) |
| String constant | "Hello" (double quotes) |
int age; /* declaration */
age = 16; /* assignment */
float marks = 85.5; /* declaration with initialization */
const float PI = 3.14159; /* constant variable */
5.2.5 Data Types in C
| Data type | Typical size | Format specifier | Use |
|---|---|---|---|
char | 1 byte | %c | A single character |
int | 4 bytes* | %d | Whole numbers |
float | 4 bytes | %f | Real numbers (about 6тАУ7 digits of precision) |
double | 8 bytes | %lf (input), %f (output) | Real numbers (about 15 digits of precision) |
void | none | тАУ | No value (function returns nothing) |
*int is 4 bytes on modern compilers (it was 2 bytes in old Turbo C).
Modifiers: short, long, signed, unsigned change the size or range, e.g. unsigned int (only 0 and positive values), long int, long long.
#include <stdio.h>
int main(void)
{
printf("char : %d byte(s)\n", (int) sizeof(char));
printf("int : %d byte(s)\n", (int) sizeof(int));
printf("float : %d byte(s)\n", (int) sizeof(float));
printf("double : %d byte(s)\n", (int) sizeof(double));
return 0;
}
Output
char : 1 byte(s)
int : 4 byte(s)
float : 4 byte(s)
double : 8 byte(s)
Type conversion: In an expression with mixed types, C converts automatically to the larger type (implicit). A programmer can force a conversion using a type cast, e.g. (float) sum / 5.
5.2.6 Operators and Expressions
An expression is a combination of operands and operators that gives a value.
| Category | Operators | Example |
|---|---|---|
| Arithmetic | + - * / % | 17 % 5 gives 2 |
| Relational | == != > < >= <= | a > b gives 1 (true) or 0 (false) |
| Logical | && (AND), || (OR), ! (NOT) | (a > 5) && (b < 10) |
| Assignment | = += -= *= /= %= | x += 5 means x = x + 5 |
| Increment / Decrement | ++ -- | x++, ++x, x--, --x |
| Conditional (ternary) | condition ? value1 : value2 | max = (a > b) ? a : b; |
| Bitwise | & | ^ ~ << >> | 12 & 10 gives 8 |
| Special | sizeof, , (comma) | sizeof(int) |
Notes
- Division of two integers gives an integer result:
17 / 5is 3. x++(post-increment) uses the value first and then adds 1;++x(pre-increment) adds 1 first and then uses the value.=is assignment;==is comparison.
#include <stdio.h>
int main(void)
{
int a = 17, b = 5;
int x = 5, y, z;
printf("a + b = %d\n", a + b);
printf("a - b = %d\n", a - b);
printf("a * b = %d\n", a * b);
printf("a / b = %d\n", a / b);
printf("a %% b = %d\n", a % b);
printf("a > b : %d\n", a > b);
printf("a == b : %d\n", a == b);
printf("(a > 10) && (b > 10) : %d\n", (a > 10) && (b > 10));
printf("(a > 10) || (b > 10) : %d\n", (a > 10) || (b > 10));
y = x++; /* y gets 5, then x becomes 6 */
z = ++x; /* x becomes 7, then z gets 7 */
printf("x = %d, y = %d, z = %d\n", x, y, z);
printf("Larger of a and b = %d\n", (a > b) ? a : b);
return 0;
}
Output
a + b = 22
a - b = 12
a * b = 85
a / b = 3
a % b = 2
a > b : 1
a == b : 0
(a > 10) && (b > 10) : 0
(a > 10) || (b > 10) : 1
x = 7, y = 5, z = 7
Larger of a and b = 17
Bitwise operators work on individual bits (12 = 1100, 10 = 1010).
#include <stdio.h>
int main(void)
{
int a = 12, b = 10; /* 12 = 1100, 10 = 1010 */
printf("a & b = %d\n", a & b);
printf("a | b = %d\n", a | b);
printf("a ^ b = %d\n", a ^ b);
printf("~a = %d\n", ~a);
printf("a << 1 = %d\n", a << 1);
printf("a >> 1 = %d\n", a >> 1);
return 0;
}
Output
a & b = 8
a | b = 14
a ^ b = 6
~a = -13
a << 1 = 24
a >> 1 = 6
Operator precedence (highest to lowest)
| Order | Operators |
|---|---|
| 1 | ( ) brackets |
| 2 | ! ++ -- (unary) |
| 3 | * / % |
| 4 | + - |
| 5 | < <= > >= |
| 6 | == != |
| 7 | && |
| 8 | || |
| 9 | ?: |
| 10 | = += -= etc. |
5.2.7 Input and Output in C
Output: printf()
printf("format string", variables);
Input: scanf()
scanf("format specifiers", &variable);
The address-of operator & is required before the variable name (not for strings).
| Specifier | Data |
|---|---|
%d | int |
%f | float |
%lf | double (in scanf) |
%c | char |
%s | string |
| Escape sequence | Meaning |
|---|---|
\n | New line |
\t | Tab (horizontal space) |
\\ | Backslash |
\" | Double quote |
\0 | Null character (end of string) |
| Function | Purpose |
|---|---|
getchar() / putchar() | Read / write a single character |
gets() / puts() | Read / write a line of text. (gets() is unsafe and removed from newer C standards; fgets() is preferred.) |
getch() (conio.h) | Read a character without showing it (Turbo C only) |
#include <stdio.h>
int main(void)
{
int a, b, sum;
printf("Enter two numbers: ");
scanf("%d %d", &a, &b);
sum = a + b;
printf("Sum = %d\n", sum);
return 0;
}
Output
Enter two numbers: 10 20
Sum = 30
#include <stdio.h>
int main(void)
{
float p, t, r, si;
printf("Enter principal, time and rate: ");
scanf("%f %f %f", &p, &t, &r);
si = (p * t * r) / 100;
printf("Simple Interest = %.2f\n", si);
return 0;
}
Output
Enter principal, time and rate: 5000 2 10
Simple Interest = 1000.00
#include <stdio.h>
int main(void)
{
int a = 10, b = 20, temp;
printf("Before swapping: a = %d, b = %d\n", a, b);
temp = a;
a = b;
b = temp;
printf("After swapping : a = %d, b = %d\n", a, b);
return 0;
}
Output
Before swapping: a = 10, b = 20
After swapping : a = 20, b = 10
5.2.8 Control Statements in C
A. Selection (decision) statements
Syntax of the forms of if
if (condition) if (condition) if (condition1)
{ { { statements 1; }
statements; statements 1; else if (condition2)
} } { statements 2; }
else else
{ { statements 3; }
statements 2;
}
1. if statement
#include <stdio.h>
int main(void)
{
int n;
printf("Enter a number: ");
scanf("%d", &n);
if (n > 0)
{
printf("%d is positive.\n", n);
}
return 0;
}
Output
Enter a number: 25
25 is positive.
2. if-else statement
#include <stdio.h>
int main(void)
{
int x, y;
printf("Enter two numbers: ");
scanf("%d %d", &x, &y);
if (x > y)
printf("%d is greater.\n", x);
else
printf("%d is greater.\n", y);
return 0;
}
Output
Enter two numbers: 12 25
25 is greater.
#include <stdio.h>
int main(void)
{
int num;
printf("Enter an integer: ");
scanf("%d", &num);
if (num % 2 == 0)
printf("%d is an even number.\n", num);
else
printf("%d is an odd number.\n", num);
return 0;
}
Output
Enter an integer: 27
27 is an odd number.
3. else-if ladder
#include <stdio.h>
int main(void)
{
int p, q, r;
printf("Enter three numbers: ");
scanf("%d %d %d", &p, &q, &r);
if (p > q && p > r)
printf("%d is the greatest.\n", p);
else if (q > r)
printf("%d is the greatest.\n", q);
else
printf("%d is the greatest.\n", r);
return 0;
}
Output
Enter three numbers: 45 78 32
78 is the greatest.
4. Nested if
#include <stdio.h>
int main(void)
{
int x, y;
printf("Enter two numbers: ");
scanf("%d %d", &x, &y);
if (x > 0 && y > 0)
{
if (x > y)
printf("%d is greater.\n", x);
else
printf("%d is greater.\n", y);
}
else
{
printf("One or both numbers are not positive.\n");
}
return 0;
}
Output
Enter two numbers: 15 9
15 is greater.
5. switch statement
switch selects one of many blocks by matching the value of an expression with case labels. break is used to leave the switch after a match; default runs if no case matches.
switch (expression)
{
case value1: statements; break;
case value2: statements; break;
default: statements;
}
#include <stdio.h>
int main(void)
{
int day;
printf("Enter a number (1-7): ");
scanf("%d", &day);
switch (day)
{
case 1: printf("Sunday\n"); break;
case 2: printf("Monday\n"); break;
case 3: printf("Tuesday\n"); break;
case 4: printf("Wednesday\n"); break;
case 5: printf("Thursday\n"); break;
case 6: printf("Friday\n"); break;
case 7: printf("Saturday\n"); break;
default: printf("Out of range\n");
}
return 0;
}
Output
Enter a number (1-7): 3
Tuesday
#include <stdio.h>
int main(void)
{
float a, b;
char op;
printf("Enter number, operator (+ - * /), number: ");
scanf("%f %c %f", &a, &op, &b);
switch (op)
{
case '+': printf("Result = %.2f\n", a + b); break;
case '-': printf("Result = %.2f\n", a - b); break;
case '*': printf("Result = %.2f\n", a * b); break;
case '/':
if (b != 0)
printf("Result = %.2f\n", a / b);
else
printf("Cannot divide by zero.\n");
break;
default:
printf("Invalid operator.\n");
}
return 0;
}
Output
Enter number, operator (+ - * /), number: 12 + 5
Result = 17.00
B. Iteration (looping) statements
A loop repeats a block of statements while a condition is true.
- Entry-controlled loops (
while,for): the condition is checked before the body, so the body may run zero times. - Exit-controlled loop (
do-while): the condition is checked after the body, so the body runs at least once.
while (condition) do for (initialization; condition; update)
{ { {
statements; statements; statements;
update; } while (condition); }
}
| Loop | Checks condition | Minimum executions | Semicolon after condition |
|---|---|---|---|
while | Before the body | 0 | No |
do-while | After the body | 1 | Yes (while (condition);) |
for | Before the body | 0 | No |
1. while loop
#include <stdio.h>
int main(void)
{
int i = 1;
while (i <= 10)
{
printf("%d ", i);
i++;
}
printf("\n");
return 0;
}
Output
1 2 3 4 5 6 7 8 9 10
2. do-while loop
#include <stdio.h>
int main(void)
{
int a = 100;
do
{
printf("%d ", a);
a--;
} while (a >= 1);
printf("\n");
return 0;
}
Output
100 99 98 97 96 95 ... 5 4 3 2 1
3. for loop
#include <stdio.h>
int main(void)
{
int i, m;
for (i = 1; i <= 10; i++)
{
m = 7 * i;
printf("7 x %d = %d\n", i, m);
}
return 0;
}
Output
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
7 x 6 = 42
7 x 7 = 49
7 x 8 = 56
7 x 9 = 63
7 x 10 = 70
Difference between while and do-while loops
while loop | do-while loop |
|---|---|
| Condition is tested before the loop body | Condition is tested after the loop body |
| Entry-controlled loop | Exit-controlled loop |
| The body may never execute | The body executes at least once |
No semicolon after while (condition) | Semicolon needed after while (condition); |
Example: while (i <= 5) { ... } | Example: do { ... } while (i <= 5); |
4. Nested loops
A loop inside another loop. For each pass of the outer loop, the inner loop runs completely.
#include <stdio.h>
int main(void)
{
int i, j;
for (i = 1; i <= 4; i++)
{
for (j = 1; j <= i; j++)
printf("* ");
printf("\n");
}
return 0;
}
Output
*
* *
* * *
* * * *
C. Jump statements
| Statement | Action |
|---|---|
break | Terminates the loop (or switch) immediately and control goes to the statement after it |
continue | Skips the rest of the current iteration and goes to the next iteration of the loop |
goto label | Jumps to a labelled statement (should be avoided because it makes programs hard to follow) |
return | Leaves the function (ends main) |
#include <stdio.h>
int main(void)
{
int i;
for (i = 1; i <= 10; i++)
{
if (i == 6)
break;
printf("%d ", i);
}
printf("\nLoop ended at i = %d\n", i);
return 0;
}
Output
1 2 3 4 5
Loop ended at i = 6
#include <stdio.h>
int main(void)
{
int i;
for (i = 1; i <= 10; i++)
{
if (i % 2 == 0)
continue;
printf("%d ", i);
}
printf("\n");
return 0;
}
Output
1 3 5 7 9
Difference between break and continue
break | continue |
|---|---|
| Ends the whole loop (or the switch) | Skips only the current iteration |
| Control moves outside the loop | Control moves to the next iteration of the same loop |
Can be used in loops and switch | Used only in loops |
| Example: stop searching when an item is found | Example: skip even numbers |
5.2.9 Common Programs (Practice)
1. Reverse of a number
#include <stdio.h>
int main(void)
{
int n, rem, rev = 0;
printf("Enter an integer: ");
scanf("%d", &n);
while (n != 0)
{
rem = n % 10;
rev = rev * 10 + rem;
n = n / 10;
}
printf("Reversed number = %d\n", rev);
return 0;
}
Output
Enter an integer: 1234
Reversed number = 4321
2. Factorial of a number (5! = 5 ├Ч 4 ├Ч 3 ├Ч 2 ├Ч 1)
#include <stdio.h>
int main(void)
{
int n, i;
unsigned long long fact = 1;
printf("Enter a positive integer: ");
scanf("%d", &n);
if (n < 0)
{
printf("Factorial of a negative number does not exist.\n");
}
else
{
for (i = 1; i <= n; i++)
fact = fact * i;
printf("Factorial of %d = %llu\n", n, fact);
}
return 0;
}
Output
Enter a positive integer: 5
Factorial of 5 = 120
3. Fibonacci series (each term is the sum of the previous two)
#include <stdio.h>
int main(void)
{
int n, i, a = 0, b = 1, next;
printf("Enter number of terms: ");
scanf("%d", &n);
printf("Fibonacci series: ");
for (i = 1; i <= n; i++)
{
printf("%d ", a);
next = a + b;
a = b;
b = next;
}
printf("\n");
return 0;
}
Output
Enter number of terms: 8
Fibonacci series: 0 1 1 2 3 5 8 13
4. Armstrong number (a 3-digit number equal to the sum of the cubes of its digits: 153 = 1┬│ + 5┬│ + 3┬│)
#include <stdio.h>
int main(void)
{
int num, temp, rem, sum = 0;
printf("Enter a three-digit number: ");
scanf("%d", &num);
temp = num;
while (temp != 0)
{
rem = temp % 10;
sum = sum + rem * rem * rem;
temp = temp / 10;
}
if (sum == num)
printf("%d is an Armstrong number.\n", num);
else
printf("%d is not an Armstrong number.\n", num);
return 0;
}
Output
Enter a three-digit number: 153
153 is an Armstrong number.
5. Prime number (divisible only by 1 and itself)
#include <stdio.h>
int main(void)
{
int n, i, flag = 0;
printf("Enter a positive integer: ");
scanf("%d", &n);
if (n < 2)
flag = 1;
for (i = 2; i <= n / 2; i++)
{
if (n % i == 0)
{
flag = 1;
break;
}
}
if (flag == 0)
printf("%d is a prime number.\n", n);
else
printf("%d is not a prime number.\n", n);
return 0;
}
Output
Enter a positive integer: 29
29 is a prime number.
6. Palindrome number (reads the same forwards and backwards)
#include <stdio.h>
int main(void)
{
int n, temp, rem, rev = 0;
printf("Enter an integer: ");
scanf("%d", &n);
temp = n;
while (temp != 0)
{
rem = temp % 10;
rev = rev * 10 + rem;
temp = temp / 10;
}
if (rev == n)
printf("%d is a palindrome.\n", n);
else
printf("%d is not a palindrome.\n", n);
return 0;
}
Output
Enter an integer: 121
121 is a palindrome.
7. Sum of digits
#include <stdio.h>
int main(void)
{
int n, sum = 0;
printf("Enter an integer: ");
scanf("%d", &n);
while (n != 0)
{
sum = sum + n % 10;
n = n / 10;
}
printf("Sum of digits = %d\n", sum);
return 0;
}
Output
Enter an integer: 1234
Sum of digits = 10
5.2.10 Arrays
An array is a collection of elements of the same data type stored in continuous memory locations under one name. Elements are accessed by an index (subscript), which starts from 0.
data_type array_name[size];
int marks[5]; /* declaration */
int marks[5] = {70, 85, 60, 90, 75}; /* declaration with initialization */
| Index | 0 | 1 | 2 | 3 | 4 |
|---|---|---|---|---|---|
| marks | 70 | 85 | 60 | 90 | 75 |
marks[0] is 70 and the last element is marks[4]. If the array has n elements, the indexes run from 0 to n тИТ 1.
One-dimensional array
#include <stdio.h>
int main(void)
{
int marks[5], i, sum = 0, max;
float avg;
printf("Enter 5 marks: ");
for (i = 0; i < 5; i++)
scanf("%d", &marks[i]);
max = marks[0];
for (i = 0; i < 5; i++)
{
sum = sum + marks[i];
if (marks[i] > max)
max = marks[i];
}
avg = (float) sum / 5;
printf("Sum = %d\n", sum);
printf("Average = %.2f\n", avg);
printf("Largest = %d\n", max);
return 0;
}
Output
Enter 5 marks: 70 85 60 90 75
Sum = 380
Average = 76.00
Largest = 90
Two-dimensional array (matrix)
A two-dimensional array has rows and columns: data_type name[rows][columns];
int a[2][3] = {{1, 2, 3}, {4, 5, 6}};
| Column 0 | Column 1 | Column 2 | |
|---|---|---|---|
| Row 0 | a[0][0] = 1 | a[0][1] = 2 | a[0][2] = 3 |
| Row 1 | a[1][0] = 4 | a[1][1] = 5 | a[1][2] = 6 |
#include <stdio.h>
int main(void)
{
int a[2][3] = {{1, 2, 3}, {4, 5, 6}};
int b[2][3] = {{1, 1, 1}, {2, 2, 2}};
int c[2][3], i, j;
for (i = 0; i < 2; i++)
for (j = 0; j < 3; j++)
c[i][j] = a[i][j] + b[i][j];
printf("Sum of the matrices:\n");
for (i = 0; i < 2; i++)
{
for (j = 0; j < 3; j++)
printf("%d ", c[i][j]);
printf("\n");
}
return 0;
}
Output
Sum of the matrices:
2 3 4
6 7 8
5.2.11 Strings
A string is a sequence of characters. In C, a string is a character array that ends with the null character '\0'.
char name[10] = "Nepal"; /* stored as N e p a l \0 */
| Index | 0 | 1 | 2 | 3 | 4 | 5 |
|---|---|---|---|---|---|---|
| name | N | e | p | a | l | \0 |
scanf("%s", name);reads one word (stops at a space).fgets(name, size, stdin);reads a full line including spaces.printf("%s", name);orputs(name);displays the string.
String handling functions (<string.h>)
| Function | Purpose | Example | Result |
|---|---|---|---|
strlen(s) | Length of the string (without \0) | strlen("Hello") | 5 |
strcpy(s1, s2) | Copies s2 into s1 | strcpy(s1, "Hi") | s1 = "Hi" |
strcat(s1, s2) | Joins s2 to the end of s1 | strcat("Hello", "World") | "HelloWorld" |
strcmp(s1, s2) | Compares two strings | strcmp("abc", "abc") | 0 (equal) |
strrev(s) | Reverses the string | strrev("abc") | "cba" |
strupr(s) / strlwr(s) | Converts to upper / lower case | strupr("abc") | "ABC" |
strcmp() returns 0 if the strings are equal, a negative value if s1 is smaller than s2, and a positive value if s1 is larger.
Note:
strrev(),strupr()andstrlwr()are not part of standard C; they exist in Turbo C and some old compilers. In standard C use a loop (ortoupper()/tolower()fromctype.h), as shown below.
#include <stdio.h>
#include <string.h>
int main(void)
{
char s1[20] = "Hello";
char s2[20] = "World";
char s3[20];
printf("Length of s1 : %d\n", (int) strlen(s1));
strcpy(s3, s1);
printf("s3 after strcpy : %s\n", s3);
strcat(s1, s2);
printf("s1 after strcat : %s\n", s1);
if (strcmp(s3, s2) == 0)
printf("s3 and s2 are equal.\n");
else
printf("s3 and s2 are not equal.\n");
return 0;
}
Output
Length of s1 : 5
s3 after strcpy : Hello
s1 after strcat : HelloWorld
s3 and s2 are not equal.
Reverse a string without strrev()
#include <stdio.h>
#include <string.h>
int main(void)
{
char str[50], rev[50];
int i, len;
printf("Enter a string: ");
scanf("%49s", str);
len = (int) strlen(str);
for (i = 0; i < len; i++)
rev[i] = str[len - 1 - i];
rev[len] = '\0';
printf("Reversed string: %s\n", rev);
return 0;
}
Output
Enter a string: computer
Reversed string: retupmoc
Convert a string to uppercase using toupper()
#include <stdio.h>
#include <ctype.h>
int main(void)
{
char str[] = "nepal";
int i;
for (i = 0; str[i] != '\0'; i++)
str[i] = toupper(str[i]);
printf("Uppercase: %s\n", str);
return 0;
}
Output
Uppercase: NEPAL
Count the vowels in a string
#include <stdio.h>
#include <ctype.h>
int main(void)
{
char str[] = "Education";
int i, count = 0;
for (i = 0; str[i] != '\0'; i++)
{
char ch = tolower(str[i]);
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u')
count++;
}
printf("Number of vowels in %s = %d\n", str, count);
return 0;
}
Output
Number of vowels in Education = 5
Quick Revision
- Program = instructions; software = programs + data + documents.
- Low-level: machine (0/1), assembly (mnemonics + assembler). High-level: 3GL, 4GL, 5GL (compiler/interpreter).
- Compiler: whole program at once, creates object file. Interpreter: line by line, stops at first error.
- Errors: syntax (grammar, found by compiler), logical (wrong output), runtime (during execution).
- Algorithm = steps in words; flowchart = diagram; pseudocode = code-like English.
- Control structures: sequence, selection (
if,switch), iteration (while,do-while,for). - C: created by Dennis Ritchie (Bell Labs, 1972); ANSI standard 1989; case sensitive; 32 keywords.
- Structure:
#include,main(),{ }, statements end with;. while/formay run 0 times;do-whileruns at least once.breakleaves the loop;continueskips one iteration.- Array: same type, index from 0. String: char array ending with
'\0'. strlen,strcpy,strcat,strcmpare standard string functions.
Practice Questions
Short Answer
- What is a program? Differentiate between program and software.
- What is a programming language? Explain its types with merits and demerits.
- Differentiate between compiler and interpreter.
- What is an error? Briefly explain its types.
- Differentiate between syntax error and logical (semantic) error.
- Define algorithm and flowchart with suitable examples.
- What is a control structure? Differentiate between
breakandcontinuewith examples. - What is looping? Differentiate between
whileanddo-whileloops with examples. - What is a data type? Explain the types of operators in C with examples.
- Define array. What is a string? Explain any four string handling functions with examples.
- Write short notes on: (a) pseudocode (b) decision table (c) ASCII and Unicode (d) preprocessor directive.
Long Answer
- What is C? Write its features, advantages and applications.
- Explain the control structures with algorithms and flowcharts.
Programming Practice
Write a C program to: (a) check whether a number is even or odd; (b) find the factorial of a number; (c) display the Fibonacci series; (d) check Armstrong, prime and palindrome numbers; (e) find the sum and average of array elements; (f) reverse a string without using strrev().
End of Unit 5 notes.