Programming Concept
Computer Program
- Set of instructions for specific tasks.
- Written in programming language.
- Compiled to machine code or interpreted.
- Software includes programs, libraries, data.
Characteristics of a Good Computer Program:
- Portability: Runs on different platforms with minimal changes.
- Readability: Clear logic, easy for programmers to understand.
- Efficiency: Uses processing time and memory effectively.
- Structural: Divides tasks into independent subtasks.
- Flexibility: Handles changes without full rewrite.
- Machine Independence: Runs on different systems.
- Cost Effectiveness: Measures overall cost and human effort.
Introduction to Programming Language
- Designing, writing, testing, and maintaining code.
- Creating instructions for computers to interpret and execute.
- Developing software applications, websites, games, etc.
- Involves algorithms, logic, and commands for specific tasks.
- Language used by human is natural language, and language used by computer is programming language or computer language.
- Writing a program is known as programming or coding.
- Formal system for communicating instructions to computers.
- Intermediary between human understanding and machine execution.
- Enables software creation through written code.
- Wide range of syntax, features, and paradigms.
- Example of programming language are:
- Python
- Java
- C/C#
- C++
- Ruby
- JavaScript, etc.
Low level, High level, 4 GL Programming Language (Types of Programming Language)
- Classified to two Categories: High Level and Low Level Language.
- Internally using language by computer itself is low level language
- Mathematical expression and structure close to English is a high level language.
1. Low Level Language
- Close to machine codes (0s and 1s).
- Programs in binary form.
- Requires hardware-specific knowledge.
- Classified into two groups:
a) Machine Language
b) Assembly Language
- Closest to machine language, uses alphabets and numbers.
- Uses MNEMONIC codes for instructions.
- Assembler translates symbolic code to machine instructions.
- Source code written in symbolic language.
- Object code generated by the assembler.
- Examples: CLA (Clear and Add), STA (Store), ADD, SUB.
- Easier than machine language, yet cumbersome.
- Error detection and fixing is easier than machine code.
- Still more challenging than high-level languages.
Merit of Assembly Language:
- Easier to understand and use than machine language.
- Easier to locate and remove the errors.
- It is easier to modify.
- It is easy to re-locatable.
Demerit of Assembly Language:
- It is machine dependent.
- Detailed knowledge of hardware is required.
- It uses machine level coding.
- Language processor (Assembler) is required to translate the coding.
2. High Level Language
- Closer to human language, it follows syntax rules.
- Converted to machine-readable format.
- Source code in high-level language.
- Object code after conversion.
- Compilation done by compiler/interpreter.
- High-level languages are usually machine independent.
- Easier to learn and faster to write than symbolic.
- Better documentation and easier maintenance.
Merit of High level language:
- Machine independent.
- Easy to write and learn then low level language.
- Easy to find out and remove the mistakes.
- High level programs are easy to maintain.
- Better documentation.
Demerit of High level language:
- Execute very slowly.
- Need language processor (Compiler, Interpreter) to translate the program.
- Some programs cannot be solved with these languages.
- Lower efficiency.
- Less flexibility.
a) Third Generation Language (3GL)
- Procedure-oriented for solution steps.
- Sequential instructions needed.
- Vocabulary: keywords and symbols.
- Programs written using words, symbols, rules.
- Also known as Procedure-oriented Languages
Merit of third generation language are:
- English-like statements, user-friendly.
- Faster program development.
- Ease of understanding and modification.
- Simple syntax error detection and debugging.
- Standardized and machine-independent.
- Examples: C, COBOL, FORTRAN, PASCAL, etc.
Demerit of third generation language are:
- Complexity for beginners
- Learning curve
- Hardware dependency
- Limited abstraction
- Efficiency concerns
- Challenging debugging
- Less control over hardware
- Limited portability
- Performance trade-offs
b) Fourth Generation Language (4GL)
- Closer to natural language than 3GLs.
- No detailed step-by-step instructions.
- Descriptive approach for results.
- Often database-oriented.
- Users can create own applications.
- English-like syntax.
- Examples: SQL PLUS, HTML, PHP.
- Application-specific and problem-solving.
- Known as Problem-oriented Languages.
Merit of fourth generation language are :
- No need to know machine details.
- Variety of languages available.
- Easy bug detection and debugging.
- English-like syntax, user-friendly.
- Faster and easier coding.
- Supports OOP and code reusability.
Demerit of fourth generation language are :
- Needs a compiler/interpreter for conversion.
- Conversion and execution time.
- Less efficiency than machine language.
- Inefficient resource usage.
Difference between 3GLs and 4GLs
Basis |
3GLs |
4GLs |
Focus |
Emphasize procedure and algorithms. |
Emphasize on end-user outcomes and data handling. |
Nature |
Low-level languages, closer to machine code. |
High-level languages, abstracted from machine code. |
Abstraction |
Moderate level of abstraction. |
High level of abstraction. |
Syntax |
Complex syntax requiring detailed coding. |
User-friendly, more natural language-like. |
Syntax |
Suitable for system-level programming and complex applications. |
Designed for database querying, reporting, and rapid application development. |
Examples |
C, C++, Java, Fortran. |
SQL, Python (in certain contexts), visual programming tools. |
c) Fifth Generation Language (5GL)
- Known as Natural language, artificial language.
- Natural languages: Human languages like Nepali, English.
- Artificial languages: C, C++, Java, used by computers.
- Fifth generation computers: Aim to understand human languages.
- Fifth generation language: For natural interaction, AI, neural networks, expert systems.
- LISP and PROLOG: Examples of present-day natural languages.
Merit of fifth generation language are:
- Ease of Use
- Wide Adoption
- Rich Expression
- Contextual Understanding
- Flexibility
- Inclusivity
- Cognitive Load Reduction
- Natural Interaction
- Efficiency for Certain Tasks
- Communication with Non-Programmers
Demerit of fifth generation language are:
- Complexity
- Limited Precision
- Learning Curve
- Performance Overhead
- Dependency on AI
- Resource Intensive
- Potential Ambiguity
- Limited Optimization
- Compatibility
- Reliance on Infrastructure
Compiler, Interpreter and Assembler (Language Translator)
- Language translator: Converts text or speech between languages.
- Maintains meaning and context.
- Bridges language barriers in various areas like business, travel, etc.
- Human or machine-based translation.
- Enables effective cross-cultural communication.
Assembler
- Translates assembly language to machine language.
- Takes assembly language program as input.
- Produces machine language program as output.
- Converts human-readable code to binary.
- Essential for programming in low-level languages.
Interpreter
- Translate one line at a time.
- Execute each line immediately.
- No object program generated.
- Slower and less efficient.
- Suitable for testing and learning.
- Ideal for logical correctness checks.
- Compilation is postponed.
- Beneficial for beginners and learners.
Compiler
- Translates high-level programs to machine codes.
- Converts entire programs, not just single statements.
- Source program becomes object program.
- Errors must be fixed before translation.
- Specific to the language it’s designed for.
- Different compilers for different languages.
- Produces binary codes for execution.
Difference Between Compiler and Interpreter
Compiler |
Interpreter |
Translates the entire program before execution. |
Translates one line at a time, executing immediately. |
Generates an object program (machine code). |
No separate object program generated. |
Detected errors only after compilation. |
Detects errors line by line during execution. |
Produces faster execution as code is pre-translated. |
Slower execution due to on-the-fly translation. |
Used for languages like C, C++, Java. |
Used for languages like Python, JavaScript. |
Syntax, Semantic and Runtime errors
- Vocabulary and rules define syntax.
- Syntax is the grammar of the language.
- Specifies allowed instruction structures.
- Semantics assigns meaning to words/symbols.
- Types of programming errors.
Syntax Error:
- Deviation from correct syntax leads to errors.
- Detected by the compiler during compilation.
- Program terminates, displays error messages.
- Examples: Misspelled names, missing semicolons, wrong brackets, incorrect statement formats.
Semantic Error:
- Related to program logic.
- Causes incorrect program operation.
- Program doesn’t terminate abnormally.
- Example: Incorrect formula like I = (P * T + R) / 100 for simple interest.
- Also called logical errors.
Runtime Error:
- Detected during program execution.
- Program compiles and runs but produces wrong results.
- Caused by data type mismatches.
- Challenging to identify and fix.
- Examples: Dividing by zero, accessing non-existent files.
Program Design tools
- Aid in planning software before coding.
- Include flowchart, pseudocode, UML, and interface tools.
- Enhance structure, logic, and user interface design.
- Contribute to efficient development and collaboration.
Algorithm:
- Step-by-step problem instructions.
- Written using programmer’s language.
- Not directly computer-tested.
- Vital documentation role.
Characteristic of algorithm are:
- An algorithm must be simple and in easy language.
- An algorithm should have finite number of steps.
- The algorithm can be easily modified.
- The algorithm should be able to produce accurate result.
Advantages
- Efficiency: Optimized solutions.
- Accuracy: Minimized errors.
- Reusability: Applicable to similar problems.
- Scalability: Works for varying input sizes.
- Logic Clarity: Step-by-step understanding.
- Problem Solving: Systematic approach for complexity.
- Communication: Facilitates sharing and collaboration.
- Savings: Reduces time and resource usage.
Disadvantages
- Complexity: Some algorithms can be intricate.
- Not Universal: Not all problems have efficient algorithms.
- Resource Intensive: High computing resources required.
- Expertise Needed: Designing advanced algorithms demands skill.
- Input Dependency: Performance varies with input.
- Inflexibility: Might not adapt to dynamic changes.
- Implementation Challenges: Converting algorithms to code can be complex.
- Lack of Creativity: Might not accommodate creative solutions.
- Learning Curve: Understanding complex algorithms can be demanding.
Flowchart:
- Graphical algorithm representation
- Uses various shapes for different instructions (input, logic, processing, output, etc.)
- Instructions written in boxes using English
- Vital for programming, aiding understanding of complex problems
- Helpful for visualizing logic in lengthy and intricate problems
Feature of Flowchart are:
- Visual representation
- Sequential steps
- Decision points
- Connectors and arrows
- Symbolic notations
- Easy-to-understand
- Process visualization
- Logic illustration
- Hierarchical structure
- Language-agnostic
Example:
Advantages:
- It provides a clear overview of the entire problem.
- It is easy to draw and understand.
- It is independent of any programming languages.
- It serves as a guide for program coding.
Disadvantages:
- It is time consuming work.
- It is difficult to translate flowchart into a program.
- It is difficult to later time modification.
- Some time it may be miscommunication.
Pseudocode
- ‘Pseudo’ means ‘fake’ or ‘false’
- Pseudo code is like a “fake” code for planning before actual coding
- It’s used after algorithm and flowchart creation
- Resembles program code but might not be syntactically correct
- Also referred to as ‘structured code’ or ‘structured English’
- Helpful in planning and organizing program logic before actual coding
Advantages:
- Clarity: Clear representation of program logic.
- Language-agnostic: Not tied to a specific programming language.
- Focus on Logic: Concentrates on problem-solving rather than syntax.
- Planning: Enhances program structure planning.
- Simplicity: Simplifies complex concepts.
- Collaboration: Facilitates teamwork and discussion.
- Time-Efficient: Reduces errors, saves coding time.
- Debugging: Easier error spotting and correction.
- Documentation: Serves as program design documentation.
- Learning: Useful for teaching programming concepts.
- Flexibility: Easily adaptable to changing requirements.
Disadvantages:
- Ambiguity: Can be imprecise, leading to different interpretations.
- Lack of Standards: No strict guidelines, causing confusion.
- Syntax Ignored: Syntax errors might be overlooked.
- Implementation Gap: Challenges translating into actual code.
- Limited Detail: Might not capture all complexities.
- Skill Required: Requires programming understanding.
- Simplicity Trap: Oversimplification of complex problems.
- Non-executable: Cannot be directly executed.
- Validation Lacking: No syntax validation or testing.
- Imagination Needed: Requires visualizing behavior for accuracy.
Control Structure: Sequence, Selection and Iteration
- Programs have standard structures.
- Programs consist of statements executed sequentially.
- Power increases with controlled statement execution.
- Execution can deviate from sequential order.
- Repetition and conditions need control structures.
- Control structures enable decision-making.
- Control structures can be categorized as
Sequence
- Executes statements sequentially.
- Order matters for successful execution.
- Previous step before next step.
Selection
- Based on condition, choose between paths.
- True outcome: one action; false outcome: another.
- Decision depends on a true or false condition.
- Known as Branching statement
Iteration
- Iteration is known as looping and involves repeated execution of instructions until a condition is satisfied.
- Loops have three components: initialization, condition, and counter.
- Initialization sets the loop’s starting point, condition determines when it stops, and the counter tracks iterations.
- Increment and decrement operators serve as counters.
- Infinite loops occur if the condition is always true.
- Three loop types: while, do while, and for loops.
Absolute binary, BCD, ASCIL, and Unicode (Code)
Absolute Binary:
- Representation of data using fixed binary values.
- Each bit directly represents a specific value.
- No encoding or special meanings associated.
BCD:
- Represents decimal digits (0-9) using 4 binary digits.
- Developed by IBM.
- Converts each digit to its binary equivalent.
- Allows coding of letters and special characters.
- Advantage: No size limit; easy to add digits.
- Contrast to binary format limits (8, 16, 32, 64 bits).
- Fast conversion from decimal to binary.
- Insufficient for business due to limited symbol representation (16, 24 symbols).
ASCII:
- Originally a seven-bit code, later expanded to eight bits.
- Developed for data transmission and processing.
- IBM introduced ASCII-8 with 256 symbols.
- Kept original 128 codes for compatibility.
- Common in data communication and micro-computers.
- Used for representing internal data.
- Table represents ASCII codes for symbols.
EBCDIC:
- Extended Binary Coded Decimal Interchange Code.
- Character encoding standard used mainly on IBM mainframes.
- Represents characters using 8-bit binary codes.
- Predecessor to ASCII and Unicode.
Unicode:
- Universal character encoding standard.
- Represents characters in text, web pages, etc.
- Supports all languages globally.
- ASCII supports 128 characters, Unicode supports 1,000,000+.
- Unicode uses up to 4 bytes per character.
- UTF-8 and UTF-16 common encodings.
- UTF-8 is efficient for English, others use more bytes.
- Used for diverse character representation.
C Programming Language
Introduction and Feature of C Language
- Developed by Dennis Ritchie at Bell Labs (mid 1970s).
- Initially for systems programming, but versatile.
- Used in various applications from business to engineering.
- Popular for personal computers due to small memory requirements.
- First major use: UNIX operating system.
- Linked with UNIX historically, but now independent.
- Close to assembly language for efficiency.
- Enables writing efficient code.
- Can be challenging for certain application types.
Facts About C:
- Created for UNIX OS development.
- Successor of B language (early 1970s).
- Formalized by ANSI in 1988.
- Entire UNIX OS written in C.
- Widely used for System Programming.
- Many software and Linux OS use C.
- MySQL RDBMS developed in C.
Feature of C:
- Easy learning due to the small command set.
- Follows structured programming.
- Provides machine independence.
- Supports modular programming.
- Acts as a bridge between high and low-level languages.
- Faster execution than other languages.
- Offers various data types and declarations.
- Includes numerous built-in functions.
- Powerful for commercial and hardware programming.
- Programs independent of CPU used.
Advantage of C:
- Machine independent and portable.
- Considered the foundation of modern languages.
- Compiler widely accessible.
- Combines high-level and low-level capabilities.
- Known for fast execution.
Disadvantage of C:
- Lacks runtime checking.
- Challenging to fix errors in large programs.
- Doesn’t support object-oriented programming.
- Complexity may be difficult for beginners.
Structure of C program
- Several building blocks known as function.
- Function task independently.
- Basic structure of C program: Preprocessor and Header Files, void main function(), Comments, Compiling Process.
Preprocessor and Header Files
-
-
- Pre-compilation phase.
- Processes directives starting with ‘#’.
- Handles tasks like macro substitution and conditional compilation.
-
- Contain declarations and sometimes definitions.
- Modularize and organize code.
- Included using ‘# include’ directive.
- Commonly have ‘.h’ extensions.
Void main function ()
- Contain main () function.
- Written inside the scope {}.
- Actual program code are written in the executable part
Comments
- Comment are not internal part of program code.
- Writing comments helps to understand the flow of program.
- Practice for internal documentation of programmer.
- Use for further modification and program testing.
Compiling Process
- Process of converting source file into executable files.
- Automatically performed by the C compiler.
C Preprocessor and Header Files
- Header files, standard library file of C programming language.
- Detailed information about variables, constant, operators, etc.
- Files included program code before compilation.
- Preprocessor directives, include or link of header files to program codes
- List of header files are:
- #include<stdio.h>
- #include<conio.h>
- #include<math.h>
- #include<string.h >
Character Set used in C
- Define a group of letters, words, numbers, symbols, expressions used in C language.
- Some of them are:
- Letters: uppercase A to Z and lowercase a to z.
- Digits: 0 to 9
- Special Characters: listed in the table.
Special Characters:
Use of Comments
- Arbitrary text between /* and */.
- Enhance readability and understanding.
- Explain the program’s purpose.
- Not executable; ignored by compiler.
- Can be inserted almost anywhere except in constants.
- Aid in documentation, debugging, and testing.
- No impact on execution speed or program size.
- Helpful for programmers and users.
- Good practice for program clarity.
- Written in two form:
- //Single Line Comments
- /*Multi-Line………………………..comments*/
Identifiers, Keywords and Tokens
- Smallest part is called C tokens.
- Written by using these tokens
- Types of C tokens are:
Keywords:
- Reserved by the C compiler
- Known as Keywords
- Identifiers in the program.
Identifiers:
- Name given to program units like: variables, structure, function, etc.
- Not define in programmer language
- But define by programmer
- Some rules are:
- Must start with an alphabet or underscore.
- Can consist of letters, digits, and underscore.
- Cannot be a standard C keyword.
- No spaces are allowed.
- Both uppercase and lowercase characters are valid.
Valid Identifiers
A1 B34 FIRST_NAME x_1
Invalid Identifiers
1A 34AB int void First-NAME X.1
Basic Data Types in C
- Form of number, character, string or record are known as data types.
- Provide two data types: Primary data types and Secondary data types.
Primary Data Types:
- Known as fundamental data types
- Used to build other data types
Constants and Variables
Variables:
- Variables are named memory locations to store values of the same datatype.
- They are storage containers for values during program execution.
- Variables are declared before being used.
- Each variable must have a specified datatype.
- Data Type determines value range, type, and memory size.
- Rules of choosing variables name:
-
- Can include uppercase and lowercase letters (A-Z, a-z).
- Can include digits (0-9) and underscore (_).
- Must start with a letter or underscore.
- Blank spaces are not allowed.
- Special characters like # and $ are not allowed.
- C keywords cannot be used as variable names.
- Variable names are case-sensitive.
- Values can be numeric or alphabetic.
- Variable types can be char, int, float, double, or void.
- Two main variable types:
Numeric Variable:
-
-
- Stored only numeric data
- Maybe a whole number or a fractional number.
- Example: integer, floating point, double
String Variable:
-
-
- Stored only character data
- May be single character or string
- Example: table of string, character, array of character(string)
Constant:
-
- Value don’t change during execution of program.
- Has several types of constant.
- Types of constant are:
- Integer Constant
-
-
- Sequence of digits
- Decimal integer, octal integer, hexadecimal are types
- Example:
Decimal Integer 123 -31 0 +78
Octal Integer O26 O O347 O676
Hexadecimal Integer OX2 OX8C OXbcd OX
2. Character Constant
-
-
- Stores only character
- Enclosed by single quotation mark
- Example:
‘A’ ‘B’ ‘h’ ‘2’ ‘6’
3. String Constant
-
-
- Set of character enclosed by double quotation mark
- May be alphabet, number, special character and blank space.
- Example:
“VISHAL” “1234” “God Bless” “!…?”
4. Symbolic Constant
-
-
- Substitute the value or expression to the constant name.
- Using the pre-processor #define.
- Example:
#define PI 3.14
#define name “HSEB”
#define area 100
5. Escape Sequence Constant
-
- Non-printing character starts with slash(\)
- Special character used in output function
- Table and meaning of escape sequence are:
Difference between Variable and Constant
Variable |
Constant |
Holds a value that can be modified during program execution. |
Holds a fixed value that cannot be changed during program execution. |
Declared using a data type and an identifier (name). |
Declared using the const keyword. |
Values can be assigned and reassigned as needed. |
Values must be assigned at the time of declaration. |
Used to store and manipulate changing data. |
Used to represent unchanging data. |
Types of Specifier
- Known as format specifier.
- Types and format of value to be print or entered.
- Begins with % and ends with conversion character.
- Datatypes of the corresponding argument.
Simple and Compound Statements
- Terminated by semicolon.
- Cause the computer to carry out some action.
Simple Statement:
- An expression followed by a semicolon.
- Causes the expression to be evaluated.
Compound Statement:
- Several individual statements enclosed in a pair of braces { }.
- Capability for embedding statements within other statements
Operators and Expressions
- Symbols carry out specific calculations or logical comparison.
- Variable or constant that holds data operation.
- Combination of operators and operands.
- Wide variety of operators
Arithmetic Operators:
- Perform simple arithmetic calculations like: additions, subtraction, multiplication, etc
- Uses two operands so that it is called binary operator
- Types of arithmetic operators are:
Relational Operators:
- Compare two expressions.
- Bring out the decision accordingly
- Known as Comparison operator
Logical Operators:
- Used to give logical value i.e. true or false
- Compare or evaluate logical and relational expressions
Assignment Operators:
- Assign the value of expression into a variable.
- Written form: variable = expression
Unary Operators:
- Increment and Decrement operators are useful.
- Extensively used in loops
- Syntax of Operators are:
- ++variable name (increment prefix)
- variable name ++ (increment prefix)
- – -variable name (decrement prefix)
- variable name – – (decrement prefix)
Ternary Operator (? : operator):
- Known as conditional operator
- Check the conditional to make a decision.
- Uses two symbol : (?) and (:)
The Comma Operator:
- Used to link related expressions together.
- Evaluated left to right and expression value of right
Expressions:
- Expressions combine variables, constants, and operators.
- Each expression evaluates to a value with a specific data type.
- Operators perform operations on operands within expressions.
- Type promotion and conversion ensure compatibility.
- Order of evaluation and side effects are important considerations.
- Expressions can be assigned to variables using the assignment operator.
- Parentheses control the order of evaluation.
- Function calls can be considered expressions if they return values.
Type Casting and Conversions
Implicit Type Conversion:
- Mixing of constants and variable of different types in expression
- Automatically converts any intermediate values to proper types.
- Evaluates without losing any significance
Explicit Type Conversion:
- Forcing type conversion differently from automatic.
- Called explicit conversion or casting.
- Used to change data types deliberately.
Introduction to Library Functions
- Function that pre-defined in programming language
- Used for input/output operations
- Function can perform specific tasks and return specific values.
Input/output (I/O) Functions
- Provided by C compiler or C library.
- Collectively called Standard I/O Library functions.
- Used for input and output operations.
- Embedded in the stdio.h header file.
- Two main categories: Input and Output functions.
Other Input/Output Functions
- ‘getchar()’: Reads a single character.
- ‘putchar()’: Displays a character.
- Operate on individual characters.
- Used for character input/output
Selection Control Statement: Decisions (if, if-else, if-else-if, nested and switch)
Introduction to Control Statement
- Program execution is typically sequential, line by line.
- Not suitable for all scenarios, like making decisions.
- Decision-making statements verify conditions.
- Determine whether a block of code is executed.
- Used to solve problems where choices are needed.
Branching Statement
- Selection is made based on condition.
- Option to go when the given condition is true or false
- Totally directed by the result obtained from checking condition.
- Using selective control structure are called conditional statement
- Types of control used for decision making
- Two Categories are: Conditional Branching statement, switch-case statement
- Program executive based on the condition checked
- Used in different forms are:
- If statement
- If else statement
- If else if statement
- Nested if else statement
If statement:
- Verifies a given condition.
- Executes a block of statements if the condition is true.
- Skips the block if the condition is false.
If else statement:
- Verifies a given condition.
- Executes one of two blocks based on condition.
- If the condition is true, execute the true block.
- If the condition is false, execute the false block.
If else if statement:
- Used when multiple conditions need to be evaluated.
- Handles more than two possible actions.
- Provides a sequence of condition checks.
- Each condition is followed by a corresponding action.
- Only the action corresponding to the first true condition is executed.
nested if else statement:
- If statement inside another if statement.
- Referred to as a “nested if.”
- Helps create hierarchical conditions.
- Increases complexity for more intricate logic.
Switch case Statement:
- Suitable for selecting one option from many.
- Solves problems with multiple options efficiently.
- Simpler alternative to nested if statements.
- Compares a given value with values associated with options.
- Execution starts from the matched option (case).
Iteration Control Statement: Looping (while, do while, for nested)
Looping
- Repeatedly executing a set of instructions.
- Controlled by a specific number or condition.
- Part of control statements in C.
- Iteration statements are also called loops.
- Loops enable repetition in C programming.
- Types of looping are:
while loop:
- Repeats a statement or block while a condition is true.
- Executes as long as the condition remains true.
- Also known as “Entry control” looping statement.
- Rules of while loop are:
- Use the keyword “while” in lowercase.
- If the condition involves a variable, assign a value before using it.
- Modify the variable value within the ‘while’ block as needed.
- The condition can be a direct integer value, variable, or a condition.
do while loop:
- Repeats a statement or block while a condition is true.
- Executes at least once before checking the condition.
- Also known as “Exit control” looping statement.
Difference between while loop and do while loop
while loop |
do while loop |
Condition is checked before entering the loop |
Condition is checked after executing the loop body. |
If the condition is false initially, the loop might not execute at all. |
The loop body always executes at least once, even if the condition is false. |
Execution might not enter the loop body if the condition is false from the beginning. |
Execution enters the loop body before the condition is checked. |
for loop:
- Pre-tested loop for a known number of iterations.
- Consists of three parts: initialization, condition, and update.
- Control variable is initialized first.
- Condition is tested, and the loop continues if true.
- If the condition is false, the loop terminates.
- Statements in the loop body are executed.
- Control variable is updated and the condition re-evaluated.
- Loop continues until the condition becomes false.
Nested Loop:
- Nested loop: loop within a loop.
- Outer loop triggers the inner loop.
- Inner loop executes completely.
- Outer loop triggers inner loop for each iteration.
- Process repeats until the outer loop finishes.
Infinite Loop:
- Repeats program statements endlessly.
- Lacks a termination condition.
Jumping Statement
- Used to control program flow.
- Execute or skip program statements.
- Three types: break, continue, and goto.
break Statement:
- Terminates ‘switch’ case statements.
- Terminates looping statements: ‘while’, ‘do-while’, and ‘for’.
continue Statement:
- Used inside loops.
- Jumps to the loop’s beginning for the next iteration.
- Skips the execution of statements within the loop for the current iteration.
goto Statement:
- Used to jump between lines in a program.
- Enables jumping top-to-bottom or bottom-to-top.
- Requires a label as the target destination.
- Label is a name for an instruction or line.
- Execution control jumps directly to the labelled line.
Array: definition, types (1D and 2D), matrix addition and subtraction
Introduction to Array
- Used for managing large numbers of similar data values.
- Provides a single variable to store multiple values of the same type.
- Offers easier handling and organization of data.
- Stores values in continuous memory locations.
- Enhances efficiency in accessing and managing data.
Characteristics of Array:
- Collection of elements of the same data type.
- Elements stored in contiguous memory locations.
- Accessed using an index or position.
- Fixed size determined during declaration.
- Elements can be accessed and manipulated efficiently.
- Can be used to represent lists, tables, matrices, etc.
Advantages of Array:
- Random Access: Elements can be accessed directly using array indices.
- Code Efficiency: Requires fewer lines of code for multiple elements.
- Simplified Access: Provides easy access to all elements.
- Efficient Traversal: Can be traversed easily using a single loop.
- Simplified Sorting: Sorting is easier with fewer lines of code.
Disadvantage of Array:
- Fixed Size: Array size is determined during declaration and cannot be changed.
- Limited Dynamic Behavior: Unlike linked lists, arrays are not dynamic in nature.
- Costly Insertion and Deletion: Inserting and deleting elements can be inefficient due to memory reallocation and shifting.
- Memory Management: Array elements need to be managed explicitly with new memory allocation.
- Static Structure: Array structure is static, making it less flexible for changing data requirements.
Types of Arrays
- Arrays are classified into two types.
- Single Dimensional Array / One Dimensional Array
- Multi Dimensional Array
One Dimensional Array:
- Used to store a list of values of the same data type.
- Store data in a linear, sequential form.
- Often referred to as one-dimensional arrays or linear arrays.
- Suitable for representing a row of values.
Array Initialization
- Arrays can be initialized during declaration using curly braces {}.
- Use commas to separate the initialization values within the curly braces.
- Partial initialization is allowed; remaining elements will be set to zero.
- For complete initialization, the array’s dimension is not needed; the compiler will adjust it based on the provided data.
Multi Dimensional Array:
- Multi-dimensional arrays consist of arrays within arrays.
- They have more than one dimension or size.
- Examples include two-dimensional, three-dimensional, and higher-dimensional arrays.
- Two-dimensional arrays are commonly used to store tabular data and matrices.
String: Definition and String Function: strlen(), strcat(), strcamp(), strrev(), strcpy(), strlwr(), strupr()
Introduction to string
- Strings are sets of characters enclosed in double quotes.
- Strings are created using one-dimensional arrays of the character data type.
- Strings are terminated with a NULL character (‘\0’).
- The C compiler automatically appends a NULL character at the end of a string.
- Strings in C are represented as character arrays of a single dimension.
String Handling Functions
- Pre-defined functions for working with string values.
- Defined in the string.h header file.
- Need to include string.h before using these functions.
- Example:
- strrev() function
- strcpy() function
- strcat() function
- strcmp() function
Array of Strings:
- Array of strings is a dimensional array of characters.
- Also called a table of strings.
- Useful for sorting string-related problems.
- Can be treated like a two-dimensional array.