0% found this document useful (0 votes)
20 views8 pages

C Programming Concepts and Examples

regarding cp engineering sem 2

Uploaded by

vyaspoorva1
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views8 pages

C Programming Concepts and Examples

regarding cp engineering sem 2

Uploaded by

vyaspoorva1
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

2 Marks Questions:

1. Mention the different types of Tokens in “C” , and explain one of them.
Types of Tokens in C:
1. Keywords – Reserved words with special meaning (e.g., int, return, if)
2. Identifiers – Names used for variables, functions, arrays (e.g., main, sum)
3. Constants – Fixed values that do not change (e.g., 10, 'A', 3.14)
4. Strings – Sequence of characters enclosed in double quotes (e.g., "Hello")
5. Operators – Symbols that perform operations (e.g., +, -, *, /)
6. Special Symbols – Symbols used for syntax (e.g., {}, (), ;, #)

2. What is flowchart? Explain use of different Symbols of flowchart.


A flowchart is a graphical representation of an algorithm or process. It uses symbols to
depict the sequence of steps, decisions, inputs, and outputs in a program or workflow.
Symbol Name Purpose

Terminator Indicates the start or end of the


Oval flowchart.
(Start/End)
Represents a decision or conditional
Decision branch (e.g., if).
Diamond
Represents a process or operation (e.g.,
Process assignment).
Rectangle

3. What is token? Explain different tokens in C.


In C programming, a token is the smallest individual unit in a program that the compiler
recognizes. While writing a C program, everything is broken into tokens during the
compilation process.

4. Write a C program to determine whether a given number is negative, positive or zero, using
if-else statements.

#include <stdio.h>

int main() {
int num;
clrscr();
printf("Enter a number: ");
scanf("%d", &num);

if (num >= 0) {
if (num == 0)
printf("The number is zero.\n");
else
printf("The number is positive.\n");
} else {
printf("The number is negative.\n");
}

getch();
}

5. Explain nested if else statement with example.


A nested if-else is an if-else statement inside another if-else statement. It is used to test
multiple conditions in a structured way, especially when a decision depends on another
decision.
Example- above

6. Write algorithm to find sum of five integer numbers.


Step-by-step Algorithm:
1. Start
2. Initialize a variable sum = 0
3. Repeat steps 4 to 6 for i = 1 to 5
4. Input a number and store it in variable num
5. Add num to sum
6. sum = sum + num
7. Display the value of sum
8. Stop

7. Define function with example.


A function in C is a block of code that performs a specific task. Functions are used to break a
large program into smaller, manageable parts and promote code reusability.
Types of Functions:
1. Library functions – Built-in (e.g., printf(), scanf())
2. User-defined functions – Created by the programmer

8. Describe library function 1)strcat() 2)strlwr()


1) strcat() – String Concatenation
• Purpose: Appends one string at the end of another.
• Header File: #include <string.h>
Syntax: char *strcat(char *dest, const char *src);

2) strlwr() – Convert String to Lowercase


• Purpose: Converts all characters in a string to lowercase.
• Header File: #include <string.h> (Note: May not be part of ANSI C; it's available in some
compilers like Turbo C)
• Syntax: char *strlwr(char *str);
9. Describe library function 1)strlen() 2)strcpy()
1) strlen() – String Length
• Purpose: Returns the length of a string (number of characters before the null character \0)
• Header File: #include <string.h>
• Syntax: size_t strlen(const char *str);

2) strcpy() – String Copy


• Purpose: Copies the contents of one string into another.
• Header File: #include <string.h>
• Syntax: char *strcpy(char *dest, const char *src);

10. Explain break and continue statement with example.


1) break Statement
• Purpose: Terminates the loop or switch statement immediately.
• Use Case: When a certain condition is met and you want to exit the loop early.

2) continue Statement
• Purpose: Skips the current iteration and jumps to the next loop iteration.
• Use Case: When you want to skip some code inside the loop based on a condition.

11. What is the difference between declaration and definition of function.

Aspect Function Declaration Function Definition

Tells the compiler about the Provides the actual body


Purpose function's name, return type, (logic) of the function
and parameters
Includes Yes
No
Body?
Also Called Function Prototype Function Implementation

Ends With Semicolon (;) Code Block ({ ... })

Anywhere in the program,


Location Typically before main() usually after main()

int add(int a, int b) {


Example int add(int, int); return a + b; }

Compilation Helps compiler validate function Generates actual code


Role calls before definition during compilation
12. Why do we prefer iteration over recursion in any C program?
We prefer iteration over recursion in C because:
• Iteration uses less memory, while recursion uses the call stack for each function call.
• Iteration is faster due to no overhead from repeated function calls.
• It avoids stack overflow, which can happen in deep recursion.
• Iterative code is generally more efficient and easier to optimize by the compiler.

13. Give an example of nested structure.

#include <stdio.h>

struct Address {
int houseNo;
int pinCode;
};
Clrscr();
struct Person {
char name[20];
struct Address addr; // Nested structure
};

int main() {
struct Person p1 = {"John", {101, 400001}};

printf("Name: %s\n", [Link]);


printf("House No: %d\n", [Link]);
printf("Pin Code: %d\n", [Link]);

getch();
}

14. What is structure? Write one example of structure.


A structure is a user-defined data type in C that allows you to group different types of
variables under a single name. It is used to represent a record.

#include <stdio.h>
struct Student {
int id;
char name[20];
float marks;
};
Clrscr();
int main() {
struct Student s1 = {101, "Alice", 88.5};

printf("ID: %d\n", [Link]);


printf("Name: %s\n", [Link]);
printf("Marks: %.2f\n", [Link]);

getch();
}

15. What are the advantages and Disadvantages of Array?

Advantages of Arrays:
1. Efficient Access: Elements can be accessed directly using an index.
2. Code Simplicity: Reduces the need for multiple variables.
3. Memory Management: All elements are stored in contiguous memory locations.
4. Easy Iteration: Loops can be used to efficiently traverse or manipulate data.

Disadvantages of Arrays:
1. Fixed Size: The size of an array must be known at compile time and cannot be changed
during runtime.
2. Same Data Type: Only elements of the same type can be stored.
3. Memory Waste: If the declared size is not fully used, memory is wasted.
4. Insertion/Deletion Complexity: Inserting or deleting elements is less efficient and may
require shifting elements.

16. Differentiate between Structure and Union.

Aspect Structure (struct) Union (union)

Memory Allocates separate memory for Allocates one shared


Allocation each member memory for all members

Memory Requires less memory


Requires more memory
Usage
All members can be accessed at Only one member can be
Access accessed at a time
the same time

Sum of sizes of all members (plus Size of the largest


Size member
padding)

Used when all values need to be Used when only one


Use Case value is needed at a time
stored simultaneously

struct student { int id; float union data { int i; float f;


Example };
marks; };

17. What is file? Explain different file operations.


In C programming, files are used to store input/output data permanently, unlike variables
that store data temporarily in memory.

Operation Function Used Purpose

Opening a file fopen() Opens a file in specified mode

Closing a file fclose() Closes an opened file

Reading from fscanf(), fgets(), Reads data from a file


file fread()
fprintf(), fputs(), Writes data to a file
Writing to file
fwrite()
Moves or finds current file pointer
File position fseek(), ftell() location

Checks if end of file has been


End of file feof() reached

18. Explain different operators in c.


Type Description Examples

Perform basic arithmetic +, -, *, /, %


1. Arithmetic Operators
operations
==, !=, >, <, >=,
2. Relational Operators Compare two values <=

Combine conditions (returns &&, `


3. Logical Operators
true or false)
4. Assignment =, +=, -=, *=, /=,
Assign values to variables %=
Operators
Increase or decrease a value by ++, --
[Link]/Decrement
1
6. Bitwise Operators Perform operations on bits &, `

19. Write syntax of for loop and nested for loop.


1. Syntax of for Loop:
for (initialization; condition; increment/decrement) {
// code to be executed
}
2. Syntax of Nested for Loop:
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
}}
20. Identify the types of pointers from the below two programs:
1. #include
int main(){
int *ptr = NULL;
printf("%d", *ptr);
return 0;}

2. #include
<stdio.h>
int main(){
int *p;
*p=10;
printf("%d", *p);
return 0;}

Program 1:
Type of Pointer: NULL Pointer
• ptr is explicitly initialized to NULL.
• A NULL pointer means it does not point to any valid memory location

Program 2:
Type of Pointer: Uninitialized (Dangling/Wild) Pointer
• p is declared but not initialized to point to valid memory.
• Dereferencing *p without assigning it a valid address leads to undefined behavior.
• May cause a crash or garbage value.

21. What are the C file operations, provide six different possible file operation function?
File operations in C are used to create, read, write, and manage files on disk using standard
library functions provided in <stdio.h>.

Six Common File Operation Functions in C:


Function Purpose Example Usage

fopen() Opens a file in a specified mode FILE *fp = fopen("[Link]", "r");

fclose() Closes an opened file fclose(fp);

fprintf() Writes formatted data to a file fprintf(fp, "Hello File");

fscanf() Reads formatted data from a file fscanf(fp, "%d", &num);

fread() Reads binary data from a file fread(&x, sizeof(int), 1, fp);

fwrite() Writes binary data to a file fwrite(&x, sizeof(int), 1, fp);

22. Derive the output of the below code snippet . Give proper explanation to your answer.
#include <stdio.h>
int main(){
int c = 5, no = 10;
do {
no /= c;
} while(c--);
printf (\"%d\\n\", no);
return 0;}

• Expected Output: No valid output


• Actual Result: Runtime error: division by zero
To fix the code, you must prevent dividing by zero. For example, changing the loop condition
to while(c > 1) would avoid the error.

23. What is pointer? Write syntax to declare pointer.


A pointer is a variable that stores the memory address of another variable. Instead of
holding a value directly, it points to a memory location.
Syntax to Declare a Pointer:
data_type *pointer_name;

24. Explain difference between while and do while loop.


Aspect while Loop do-while Loop

Condition At the end of the loop


At the beginning of the loop
Check
Minimum Executes at least once
May not execute even once
Execution
do { //code } while
Syntax while (condition) { //code } (condition);

When loop depends on a When loop must run at


Use Case least once
condition being true

Common questions

Powered by AI

The distinction between a function declaration and definition in C is fundamental. A function declaration informs the compiler about a function's name, return type, and parameters without providing its actual implementation, serving as a 'prototype.' This ensures correct function calls. A function definition includes the complete implementation with executable code, and it comprises both the function name and body. Declaration helps the compiler check for correct function signatures during compilation, while the definition is essential for generating executable code .

A 'nested if-else' statement in C allows for multiple levels of decision-making by placing an if-else block inside another. This structure tests for various conditions and executes corresponding blocks of code based on the outcome. By allowing conditions within conditions, it enables complex decision logic to be implemented in a structured way. For example, determining a number's positivity uses nested blocks: one to check if the number is non-negative, then another to differentiate zero from positive .

In C, 'fopen()' is used to open a file in a specified mode (e.g., read, write), creating a file pointer to be used in subsequent operations like reading or writing. 'fclose()' closes an open file, releasing resources and ensuring any buffered data is properly written. Managing file operations with these functions is crucial because improper opening or closing can lead to resource leaks, data corruption, or undefined behaviors. Proper management ensures data integrity, efficient resource use, and program reliability .

In C programming, a structure allocates separate memory locations for each member, allowing simultaneous access to all members. This is useful when you need to store and work with multiple attributes together. Conversely, a union shares a single memory location among all members, saving memory but allowing only one value to be actively stored at any one time. A union is preferable when memory usage is a concern and only one field is needed at a time, while structures are better suited for modeling complex data that requires multiple fields to be accessed concurrently .

Arrays in C provide efficient access to elements via an index, which allows for direct and quick data handling. They reduce code complexity by decreasing the need for multiple variables and store data in contiguous memory, which is beneficial for memory management and iteration. However, arrays have limitations such as a fixed size determined at compile time, inability to store different data types, potential memory waste if not fully utilized, and the inefficiency of inserting or deleting elements, which may require shifting .

Iteration is typically preferred over recursion in C programs because it uses less memory, avoiding the stack space consumption caused by recursive function calls. Recursive calls store return addresses and local variables on the call stack, which can lead to stack overflow in deep recursive chains. Iteration also reduces the overhead associated with repeated function calls, improving performance and execution speed. Additionally, iterative loops are usually more straightforward for compilers to optimize than recursive calls, making them more efficient in general .

In a flowchart, different symbols represent various programming elements, aiding in the visualization of algorithms. For example, ovals denote the start and end, representing termination points. Diamonds illustrate decision nodes, indicating branches such as conditional statements. Rectangles are used for processes or operations, like arithmetic tasks or variable assignments. These symbols help in structuring and simplifying complex algorithms into a sequential, visual format that is easy to analyze and communicate, enabling efficient program design and debugging before implementation .

Pointers can lead to segmentation faults or division by zero errors when uninitialized pointers are dereferenced, as they might point to random memory locations. In the provided code snippet, using the loop 'do { no /= c; } while(c--);', the decrement of 'c' without guarding against zero causes a division by zero error. To avoid this, modifying the loop condition to 'while(c > 1)' prevents decrementing 'c' to zero before the division operation, thus averting the runtime error .

In C programming, a token is the smallest individual unit that the compiler recognizes. Tokens are crucial as they represent the building blocks of a C program, parsed during compilation. There are several types of tokens: 1. Keywords - Reserved words with special meaning (e.g., int, return) are instructions to the compiler and cannot be used as identifiers. 2. Identifiers - Names for variables, functions, and arrays (e.g., main, sum) are how programmers reference data stored or operations performed. 3. Constants - Fixed values like numbers or characters that don't change (e.g., 10, 'A') provide immutable data within the program. 4. Strings - Sequences of characters (e.g., "Hello") are used for handling text. 5. Operators - Symbols that perform operations like addition or subtraction (e.g., +, -) enable computational tasks. 6. Special Symbols - Syntax elements like braces or semicolons denote structure or end statements (e.g., {}, ();) These components are combined according to the syntax rules of C to create a meaningful and executable program .

In C, 'break' and 'continue' are used to alter normal control flow. The 'break' statement exits a loop or switch statement entirely, useful when an exit condition is met, like terminating a search as soon as a match is found. On the other hand, 'continue' skips the rest of the code in the current loop iteration and proceeds with the next iteration, useful for skipping over unwanted outputs in a loop under certain conditions .

You might also like