PPS SEMII

1. Short note on String

A String is a one-dimensional array of characters terminated by a null(‘\0’). Each character in the array occupies one byte of memory, and the last character
must always be null(‘\0’). The termination character (‘\0’) is important in a string to identify where the string
ends. 

Syntax:

charstring_name[size];

char name[10]; [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] 

 name[10           D A    R    S   H   A   N \0 

Declaration and Initialisation


You can declare and initialize a string in multiple ways:

Method 1:

char name[10] = {'D','A','R','S','H','A','N','\0'}; (Manual null termination Method 2:
char name[10] = "DARSHAN"; (The \0 is automatically inserted at the end)

Reading Strings from User 1scanf()


Used for simple strings. It terminates input at the first whitespace (space, tab, or newline). Example:

scanf("%s", name);

Gets() / fgets()

Used to read a complete string, including spaces. gets() reads until a newline is encountered.
    ex :
– char name[10] = “Dhruv”;    
             printf(“Name: %s”, name);

2. Explain different methods to read and print a string.        ——  Methods to Read Strings 1. Using scanf()


This is the most basic method for reading input.

Behavior:

It reads characters until it encounters the first whitespace (space, tab, or newline).

Key Detail:

You do not need the address-of (&) operator because the string name itself represents the base address.

Example:

scanf("%s", name);

2. Using gets() This function is specifically designed to read character strings

Behavior:

Unlike scanf(), it does not stop at whitespaces. It continues reading until a newline (\n) or End of File (EOF) is reached.

Advantage:

Useful for reading full names or sentences that include spaces.

Example:

gets(name);

3. Using fgets()


This is a more secure alternative to gets() as it allows you to specify the maximum number of characters to read.

Syntax:


fgets(str, size, stdin);

Behavior:

It reads a string including spaces and is preferred for preventing buffer overflows.


  • Explain following :strlen, strcpy, strncpy, strcat, strncat, strcmp, strncmp, strstr, strchr,strrchr

Methods to Print Strings

1. Using printf() The standard formatted output function

Format Specifier:

Uses %s to print the character array.

Example:

printf("Name = %s", name);

2. Using puts()

A simpler function dedicated to outputting strings.

Behavior:

It prints the string and automatically adds a newline character at the end.

Example:

puts(name);

For the examples below, assume: char s1[20] = "Their"; and char s2[20] = "There";

1. Length and Copying


-strlen(s1)

Returns the length of the string as an integer (excluding the null character). Example: strlen("Hello") returns 5.


-strcpy(s1, s2)

Copies the entire second string (s2) into the first string (s1). The original content of s1 is overwritten. Example: After strcpy(s1, s2), s1 becomes "There".          – 

Strncpy(s1, s2, n)

Copies only the first n characters of s2 into s1. Example: strncpy(s1, "Apple", 2) makes s1 start with "Ap".

2. Concatenation (Joining)


-strcat(s1, s2)

Appends (joins) string s2 to the end of string s1. Example:strcat("Their", "There") results in "TheirThere".

-strncat(s1, s2, n)

Appends only the first n characters of s2 to the end of s1. Example:strncat("Their", "There", 2) results in "TheirTh".

3. Comparison strcmp(s1, s2) Compares two strings character by character

Returns 0 if strings are identical.
Returns a negative value if s1 < s2. Returns a positive value if s1 > s2.


-strncmp(s1, s2, n)

Compares only the first n characters of both strings.Example: strncmp("Their", "There", 3) returns 0 because “The” matches “The”.

4. Searching

Strstr(s1, s2)


Searches for the first occurrence 


Of the entire string s2 inside s1


It returns a pointer to the start of the match. Example: strstr("Hello World", "World") returns a pointer to "World". 

Strchr(s1, c)


Finds the first occurrence of a single character c in string s1. Example: strchr("Their", 'i') returns a pointer starting at "ir".

Strrchr(s1, c)


Finds the last occurrence (reverse search) of character c in string s1. Example: strrchr("There", 'e') returns a pointer to the very last 'e'

5 What is the function? Why it is important


A function is a group of statements that perform a specific task. It divides a large program into smaller parts. A function is something like hiring a person to do a specific job for you.  Every C program can be thought of as a collection of these functions. Program execution in C language starts from the main function.

Why function ?

Avoids rewriting the same code over and over. Using functions it becomes easier to write programs and keep track of what they
doing.

7 . What is Function? Explain type of User Defined Functions. Explain any two in detail


Types of User-Defined Functions

While built-in functions (like print() or sqrt()) come pre-installed, User-Defined Functions (UDFs)
are created by you to meet specific needs. They are generally categorized based on how they handle inputs (arguments)
And outputs (return values)
:

  1. No Argument and No Return Value:


    The function does its job and prints the result itself.

  2. With Arguments and No Return Value:

    You give the function data, but it doesn’t “hand” anything back to the main program.

  3. No Argument and With Return Value:

    The function calculates something internally and sends the result back.


4. With Arguments and With Return Value:


The most common type; you provide data, and the function processes it and returns a result.

Detailed Look at Two Types

1. Function with Arguments and No Return Value :- In this model, the “calling” function sends data (arguments) to the “called” function. The called function uses that data to act but doesn’t send a result back to the logic that triggered it.

  • How it works:


    Useful for tasks like printing a specific message or updating a global variable.

  • Example:

    A function that takes a name as an input and prints a personalized greeting.

2. Function with Arguments and a Return Value :- This is the most “complete” form of a function. It acts like a calculator: you put numbers in, it does the math, and it hands you the final answer to use elsewhere in your code.

  • How it works:


    The return keyword is used to send a value back to the caller. This value can then be stored in a variable or used in further calculations.

  • Example:

    A function that takes two numbers ($x$ and $y$), adds them, and returns the sum $s$ where:
    s = x + y

9 Explain nesting of functions


1. Function Call Within a Function

While C does not support defining a function inside another function (unlike some other languages), it heavily relies on nesting calls.
This means main() can call Function A, and Function A can then call Function B.


2. Algorithm & Logic

Start:


The program begins execution in main().

Outer Call:


main() reaches a point where it needs a specific task done and calls the “Outer Function.”

Inner Call:


Inside the “Outer Function,” the code reaches a line that calls the “Inner Function.”

Return Path:


The “Inner Function” finishes and returns control to the “Outer Function.”     The “Outer Function” finishes and returns control back to main().


3. Code Example

#include <stdio.H>
#include <string.H>
// Inner-most logic (Standard Library Function): 
strlen() // Outer Function: Calculates double
the length Int getDoubleLength(char str[]) { Int length = strlen(str); Return length * 2; } Void main() { Char myStr[20] = "Darshan"; Int result; Result = getDoubleLength(myStr); Printf("The double length of %s is: %d", myStr, result); }

4. Key Rules to Remember   -No Nested Definitions:


You cannot write void functionA() { void functionB() { ... } }. This will result in a compilation error.

Scope:


A function called inside another must be either defined above it or declared (prototyped) at the top of the file.

Stack Memory:


Each time a function is called (nested), a new “frame” is added to the stack. If you nest too many calls (like in infinite recursion), you may hit a Stack Overflow.


Difference Between Local Variable and Global Variable

FeatureLocal VariableGlobal Variable
Definition
Variable declared inside a function or blockVariable declared outside all functions
Scope
Accessible only within the function/block where it is declaredAccessible throughout the program (all functions)

Lifetime

Exists only during function executionExists throughout the entire program execution
Initialization
Not initialised automatically (contains a garbage value)Automatically initialized to 0 (default)

Memory Location

Stored in stackStored in data segment
Access
Cannot be accessed outside the functionCan be accessed by all functions
Modification
Changes affect only that functionChanges affect all functions using it

Example ;-


#include <stdio.H>
int x = 10; // Global variable
void func() {
int y = 5; // Local variable
printf(“Global x = %d\n”, x);
printf(“Local y = %d\n”, y);
}
int main() {
func();
printf(“Global x in main = %d”, x);
// printf(“%d”, y); 
return 0;
}


Demonstrate GoTo statement with an example. 

Syntax of goto

The syntax consists of two parts: the goto keyword and a unique label ending with a colon (:).

  • Forward Jump:


    goto label;
    ...
    Label:
    
  • Backward Jump (Looping):


    label:
    ...
    Goto label;
    

Code Example: Multiplication Table

#include <stdio.H>

Int main() {
    Int num, i = 1;
Printf("Enter the number whose table you want to
print? "); Scanf("%d", &num); // Defining the label Table: Printf("%d x %d = %d\n", num, i, num * i); I++; // Conditional jump back to the label If(i <= 10) Goto table; Return 0; }


What is an array? Briefly explain the array.

Definition

An array is a fixed-size, sequential collection of elements of the same data type grouped under a single variable name. Instead of declaring 100 separate variables for 100 students’ roll numbers, you can declare one array to hold them all.

Key Characteristics

  • Fixed Size:
    Once declared, the size of the array (the number of elements it can hold) remains constant.
  • Same Data Type:
    All elements in the array must be of the same type (e.G., all integers, all floats, or all characters).
  • Sequential Memory:
    Elements are stored in contiguous memory locations and are accessed using an index.
  • Zero-Indexed:
    In languages like C, the array index always starts at 0. If an array has a size of 5, the indices range from 0 to 4.

Basic Syntax (C Programming)

To declare an array, you specify the data type, the name, and the size in square brackets: data-type variable-name[size];

Example: int mark[5]; // Declares an integer array that can hold 5 values

Common Operations

  1. Initialization:
    Assigning values at the time of declaration, e.G., int mark[5] = {85, 75, 65, 55, 45};.
  2. Accessing:
    Retrieving a value using its index, such as mark[0] to get the first element.
  3. Traversing:
    Using a for loop to read or print every element in the array sequentially.