ScholarQuill logoScholarQuillUniversity Notes
My Semester
Explore Notes
Past Papers12 New
Video CoursesNew
Search
Settings
Study Tools
GPA/CGPA Calculator
Schedule & To-Do
Student Portal
Contact
Contact
ScholarQuill logo
My Semester
Explore Notes
Past Papers12 New
Video CoursesNew
Search
Settings
GPA/CGPA Calculator
Schedule & To-Do
Student Portal
Contact
ScholarQuill logoScholarQuillUniversity Notes
Study PortalCC-112Random Numbers Scope R…
Ctrl + K
Login
Explore
Search
Semester
Papers
CGPA
    CC-112

    Programming Fundamentals

    Progress0 / 39 done
    Topics39
    1Introduction to Problem Solving, Algorithms, Programming, and C Language2Problem Solving, a brief review of Von-Neumann Architecture3The C Programming Language, Pseudo-code, Concept of Variable4Data types in Pseudo-code, The C Standard Library and Open Source5Input/Output, Arithmetic expressions, Assignment statement, Operator precedence6Concept of Integer division, Flowchart and its notations7Typical C Program Development Environment, Role of Compiler and Linker8Test Driving C Application
    9A Simple C Program: Printing Text, Adding Two Integer10Memory Concepts, Arithmetic in C, Operators
    11Equality and Relational Operators
    12The if, if...else, while Nested Control Statements
    13for, switch, do...while, break, continue, Logical Operators
    14Modularizing Program in C, Math Library Functions15Function Definitions and Prototypes, Function-Call Stack and Stack Frames16Stack rolling and unrolling, Headers, Passing Arguments by Value and by Reference17Random Number Generation, Scope Rules, Recursion, Recursion vs Iteration
    18Defining Arrays, Character Arrays, Static and Automatic Local Arrays19Passing Arrays to Function, Sorting and Searching Arrays20Multidimensional and Variable Length Arrays
    21Pointer Definitions and Initialization, Pointer Operators22Passing Arguments to Function by Reference, Using the const and sizeof Operator23Pointer Expressions and Arithmetic, Pointers and Arrays, Array of Pointers24Function Pointers
    25Strings and Characters, Character Handling Library26String Functions, Library Functions
    27Streams, Formatted Output with printf, Formatted Input with scanf
    28Defining Structures, Accessing Structure Member, Structures and Functions29typedef, Unions
    30Bitwise Operators, Bit Fields, Enumeration Constants
    31Files and Streams, Creating, Reading and Writing data to a Sequential and a Random-Access File
    32#include, #define, Conditional Compilation, #error and #pragma33# and ## Operators, Predefined Symbolic Constants, Assertions
    34Variable Length Argument List, Using Command Line Arguments35Compiling Multiple-Source-File Programs, Program Termination with exit and atexit36Suffixes for Integer and Floating-Point Literals, Signal Handling
    37calloc and realloc, goto
    38Self-Referential Structures, Linked Lists39Efficiency of Algorithms, Selection and Insertion Sort
    8 min read
    Topic 17 of 39
    Topic Study Note Illustration
    17

    Random Number Generation, Scope Rules, Recursion, Recursion vs Iteration

    In C programming, random number generation, scope rules, and recursion are critical concepts that help in problem-solving and code organization. Additionally, understanding the difference between recursion and...

    Random Number Generation, Scope Rules, Recursion, and Recursion vs Iteration in C

    In C programming, random number generation, scope rules, and recursion are critical concepts that help in problem-solving and code organization. Additionally, understanding the difference between recursion and iteration is essential for optimizing programs. Let’s delve into these topics in detail.


    1. Random Number Generation in C

    Random numbers are often needed in programs for various purposes like simulations, games, cryptography, and more. In C, the standard library provides functions to generate random numbers.

    Using the rand() Function

    The rand() function in C generates pseudo-random numbers. The numbers generated by rand() are not truly random but are determined by a seed value. By default, this function generates the same sequence of random numbers every time the program is run, unless we change the seed.

    Syntax:

    int rand(void);
    
    • The rand() function returns a random integer between 0 and RAND_MAX, where RAND_MAX is a constant defined in stdlib.h (usually 32767).

    Seeding the Random Number Generator

    To get different random numbers each time a program runs, we need to seed the random number generator. This can be done using the srand() function, which seeds the random number generator with an initial value (often the current time).

    Syntax:

    void srand(unsigned int seed);
    
    • A common approach is to use the current time as the seed with time(NULL).

    Example: Generating Random Numbers

    #include <stdio.h>
    #include <stdlib.h>
    #include <time.h>
    
    int main() {
        // Seed the random number generator using the current time
        srand(time(NULL));
    
        // Generate 5 random numbers between 0 and RAND_MAX
        for (int i = 0; i < 5; i++) {
            int random_num = rand();  // Generate a random number
            printf("Random Number %d: %d\n", i + 1, random_num);
        }
    
        return 0;
    }
    

    Example: Generating Random Numbers in a Range

    To generate a random number within a specific range (for example, between low and high), we can use the modulus operator.

    int random_num = low + rand() % (high - low + 1);
    

    This generates a random number between low and high, inclusive.


    2. Scope Rules in C

    Scope in programming refers to the region of the program where a variable or function is accessible. In C, there are different types of variable scopes, and understanding these rules is crucial for managing variable lifetime and visibility.

    Types of Scope in C:

    1. Local Scope:

      • Variables declared inside a function or block (denoted by {}) are accessible only within that function or block. These variables are called local variables.
      • They are created when the function or block is entered and destroyed when it is exited.

      Example:

      void myFunction() {
          int x = 10;  // 'x' has local scope within myFunction
          printf("%d\n", x);  // Accessible inside the function
      }
      
    2. Global Scope:

      • Variables declared outside all functions, typically at the top of the file, have global scope. They are accessible from any function within the same file (or even across files if declared as extern).
      • Global variables remain in memory throughout the lifetime of the program.

      Example:

      int globalVar = 20;  // Global variable
      
      void myFunction() {
          printf("%d\n", globalVar);  // Can access global variable
      }
      
    3. Block Scope:

      • Variables declared within a block of code (such as inside loops or conditional statements) have block scope. These are usually considered local variables to the block in which they are declared.

      Example:

      for (int i = 0; i < 5; i++) {
          int j = i * 2;  // 'j' has block scope
          printf("%d\n", j);
      }
      
    4. Function Scope:

      • This applies to labels used in goto statements. Labels have function scope, meaning they are visible throughout the function.

    3. Recursion in C

    Recursion is a technique in programming where a function calls itself in order to solve a problem. Recursion is used when a problem can be broken down into smaller sub-problems that are similar to the original problem.

    How Recursion Works:

    • A recursive function must have at least one base case to stop the recursion and prevent an infinite loop.
    • The function reduces the problem to a simpler version of itself with each recursive call.

    Example: Factorial Using Recursion

    #include <stdio.h>
    
    int factorial(int n) {
        if (n == 0)  // Base case
            return 1;
        else
            return n * factorial(n - 1);  // Recursive call
    }
    
    int main() {
        int result = factorial(5);  // Calls factorial(5)
        printf("Factorial of 5 is: %d\n", result);
        return 0;
    }
    

    Explanation:

    • factorial(5) calls factorial(4), which calls factorial(3), and so on until it reaches factorial(0).
    • The base case is when n == 0, at which point the recursion stops, and the values are multiplied together as the recursive calls return.

    Output:

    Factorial of 5 is: 120
    

    4. Recursion vs Iteration

    Both recursion and iteration are techniques used to repeat a set of operations. They are often interchangeable, but each has its pros and cons, and the choice between them depends on the situation.

    Recursion:

    • A function calls itself to solve a smaller instance of the problem.
    • Generally used for problems that naturally fit into a recursive structure, like tree traversals, factorials, and the Fibonacci sequence.
    • Requires additional memory for each recursive call, as each call adds a new stack frame to the call stack.

    Advantages:

    • Easier to write for problems that have a recursive structure.
    • Can lead to simpler and more readable code.

    Disadvantages:

    • Consumes more memory due to the creation of a new stack frame for each recursive call.
    • Can result in a stack overflow if the recursion depth is too high (i.e., too many recursive calls).

    Iteration:

    • Repeats a set of instructions using loops (for, while, do-while).
    • More memory efficient than recursion since it does not involve creating new stack frames.

    Advantages:

    • More memory-efficient, as it uses a constant amount of memory.
    • Typically faster than recursion because it avoids the overhead of function calls.

    Disadvantages:

    • Can be harder to write for problems that naturally have a recursive structure.
    • Can make code more complex when solving problems that require dividing the task into smaller, similar sub-tasks.

    Example: Factorial Using Iteration

    #include <stdio.h>
    
    int factorial(int n) {
        int result = 1;
        for (int i = 1; i <= n; i++) {
            result *= i;  // Multiply iteratively
        }
        return result;
    }
    
    int main() {
        int result = factorial(5);  // Calls factorial(5)
        printf("Factorial of 5 is: %d\n", result);
        return 0;
    }
    

    Comparison: Recursion vs Iteration for Factorial:

    • Recursion provides a natural, easy-to-understand implementation of the factorial problem.
    • Iteration is more efficient in terms of memory usage, as it doesn't need additional function calls and stack frames.

    Summary of Key Concepts

    1. Random Number Generation:

      • rand() generates pseudo-random numbers.
      • srand() is used to seed the random number generator, often with the current time (time(NULL)).
      • The modulus operator can be used to generate random numbers within a specified range.
    2. Scope Rules:

      • Local Scope: Variables declared inside functions or blocks.
      • Global Scope: Variables declared outside functions, accessible throughout the program.
      • Block Scope: Variables declared inside loops or conditionals.
      • Function Scope: Labels used with goto statements.
    3. Recursion:

      • A function calls itself to solve smaller instances of a problem.
      • Requires a base case to stop the recursion and avoid infinite loops.
      • Can lead to simpler solutions for problems that have a recursive structure.
    4. Recursion vs Iteration:

      • Recursion: Easier to implement for problems with a recursive structure but can lead to stack overflow and memory overhead.
      • Iteration: More memory-efficient and typically faster but can be more complex to implement for some problems.

    Understanding these concepts is vital for writing efficient and organized C programs, especially when dealing with complex problems or optimizing performance.

    ← Previous topic 16
    Stack rolling and unrolling, Headers, Passing Arguments by Value and by Reference
    Next topic 18 →
    Arrays: Defining Arrays, Character Arrays, Static and Automatic Local Arrays

    Past Papers

    Open this section to view and download past papers

    Click on Show Past Papers to load available exam papers.

    Reading Progress
    0%
    8mremaining
    1.4kwords
    Intermediatelevel
    On This Page

    No headings found

    Study Toolkit

    Subject Portal

    Programming Fundamentals