0% found this document useful (0 votes)
10 views24 pages

C Programming Basics: Key Concepts Explained

The document provides a comprehensive overview of C programming basics, covering the history, structure, data types, operators, control statements, loops, functions, and variable scope. It explains key concepts such as the use of printf and scanf for input/output, recursion, and storage classes, along with examples and syntax. The content is structured into units, detailing essential programming principles and practical applications in C.
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)
10 views24 pages

C Programming Basics: Key Concepts Explained

The document provides a comprehensive overview of C programming basics, covering the history, structure, data types, operators, control statements, loops, functions, and variable scope. It explains key concepts such as the use of printf and scanf for input/output, recursion, and storage classes, along with examples and syntax. The content is structured into units, detailing essential programming principles and practical applications in C.
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

UNIT 1 – C PROGRAMMING BASICS (THEORY ANSWERS)

1. Explain the history and evolution of the C programming language. Why is C


still widely used today? (5 Marks)

The C programming language was developed by Dennis Ritchie at AT&T Bell


Laboratories in 1972. It evolved from earlier languages such as BCPL and B. C
was primarily created to develop the UNIX operating system, which made it popular
due to its powerful features and efficiency.​
In 1989, the ANSI (American National Standards Institute) standardized C, known
as ANSI C, to ensure portability across systems. Later, ISO also certified it,
increasing its global acceptance.

Reasons why C is still widely used today:

●​ Efficiency and Speed: C produces fast and lightweight programs suitable for
system-level applications.​

●​ Portability: A C program written on one machine can run on others with


minimal changes.​

●​ Foundation Language: Many modern languages like C++, Java, and


Python are based on C syntax.​

●​ System Programming: It is still used to develop operating systems, device


drivers, and embedded systems.​

Conclusion:​
Due to its simplicity, flexibility, and powerful features, C continues to be one of the
most important and widely used programming languages in both academic and
professional domains.

2. Describe the basic structure of a C program with an example. Explain each


part. (5 Marks)

A C program follows a well-defined structure. Every program consists of different


sections such as headers, main function, declarations, statements, and return
statement.

Basic Structure of a C Program:

#include <stdio.h> // Header file


int main() // Main function
{
printf("Hello C"); // Statement
return 0; // End of program
}

Explanation of parts:

●​ Header Files (#include <stdio.h>): These contain standard library


functions such as printf() and scanf().​

●​ Main Function (main()): Every C program starts execution from the main()
function.​

●​ Braces { }: They define the starting and ending block of a function.​

●​ Statements: Instructions written inside the main function, such as printing or


calculations.​

●​ Return Statement (return 0;): Indicates successful completion of the


program.​

Conclusion:​
A proper structure ensures clarity, readability, and successful execution of the C
program.

3. Define variables, data types, and constants in C with examples. (5 Marks)

In C programming, data is stored and manipulated using variables, data types, and
constants.

●​ Variable:​
A variable is a named memory location used to store data. Its value can
change during execution.​
Example: int age = 18;​

●​ Data Type:​
Data types define the type of data a variable can hold, such as integer, float,
or character.​
Example: float salary = 5000.50;​

●​ Constant:​
A constant is a fixed value that cannot be changed during program execution.​
Example: const float PI = 3.14;​

Example Statement in C:​


const int MAX = 100;
Conclusion:​
Understanding variables, data types, and constants is essential to store and
manage data efficiently in C.

4. Explain the different types of data types in C (int, float, char, etc.) with
examples. (5 Marks)

Data types in C define the kind of data a variable can store. They help the compiler
understand how much memory to allocate and how to interpret the data.

Main Data Types in C:

1.​ int (Integer):​


Used to store whole numbers without decimal points.​
Example: int age = 25;​

2.​ float (Floating Point):​


Used to store numbers with decimal points (single precision).​
Example: float price = 99.50;​

3.​ double (Double Precision Float):​


Used to store larger decimal values with double precision.​
Example: double pi = 3.141592;​

4.​ char (Character):​


Used to store a single character enclosed in single quotes.​
Example: char grade = 'A';​

Conclusion:​
Different data types allow programmers to store and manipulate various kinds of
data efficiently. Choosing the correct data type is important for memory management
and program performance.

5. Describe the use of input and output functions (printf and scanf) in C with
syntax and examples. (5 Marks)

Input and output functions are used to interact with the user in C programming.

1. printf() – Output Function:​


Used to display information or results on the screen.​
Syntax:
printf("Format string", variable);

Example: printf("Sum = %d", sum);


2. scanf() – Input Function:​
Used to take input from the user.​
Syntax:
scanf("Format string", &variable);

Example: scanf("%d", &age);


Example Usage:
printf("Enter a number:");
scanf("%d", &num);

Conclusion:​
printf displays data to the user, while scanf receives input. These functions are
essential for interactive programs in C.

6. What are operators in C? Explain any four types of operators with examples.
(5 Marks)

Operators are special symbols used to perform operations on variables and values.

Types of Operators in C:

●​ Arithmetic Operators: Used for mathematical calculations.​


+, -, *, /, %​
Example: a + b​

●​ Relational Operators: Used for comparison of values.​


>, <, >=, <=, ==, !=​
Example: a > b​

●​ Logical Operators: Used for combining multiple conditions.​


&& (AND), || (OR), ! (NOT)​
Example: (a > b && a > c)​

●​ Assignment Operators: Used to assign values.​


=, +=, -=, *=, /=​
Example: a += 5;​

Conclusion:​
Operators help in performing operations and making decisions in a program.

7. Explain the concept of expressions in C. How are expressions evaluated? (5


Marks)

An expression is a combination of variables, constants, and operators that produces


a value.​
Example: a + b * c
Evaluation of Expressions:​
Expressions are evaluated based on operator precedence and associativity.

●​ Precedence determines which operator is evaluated first.​

●​ Associativity determines the direction (left to right).​

For example, in a + b * c, multiplication is done first, then addition.

Conclusion:​
Expressions form the basis of calculations and logical decisions in C programs.

8. Discuss the use of if and if-else statements with explanation and


examples. (5 Marks)
The if and if-else statements in C are used for decision-making. They allow a program
to execute different blocks of code based on conditions.
1. if Statement:​
The if statement checks a condition. If it is true, the statements inside if are executed.​
Syntax:
if (condition)
{
statement;
}

2. if-else Statement:​
When the condition in if is false, the else part is executed.​
Syntax:
if (condition)
{
statement1;
}
else
{
statement2;
}

Example (Conceptual):​
If marks ≥ 50 → Pass, else → Fail.
if (marks >= 50)
printf("Pass");
else
printf("Fail");

Conclusion:​
The if and if-else statements help control the flow of the program by executing
certain instructions based on logical conditions.
9. Explain the switch-case statement with syntax. Compare it with if-else-if. (5
Marks)

The switch-case statement in C is used when we need to choose one option from
multiple constant values.

Syntax of switch-case:

switch(expression)
{
case value1:
statements;
break;
case value2:
statements;
break;
default:
statements;
}

Comparison between switch and if-else-if:

Feature if-else-if switch-case

Condition Works with logical Works with constant values


s expressions only

Data Supports int, float, Supports int, char only


Types comparators

Readabilit Hard to read for many Easy to read with many


y options cases

Conclusion:​
switch-case is preferred when multiple choices depend on fixed values, while
if-else is better for complex conditions.

10. Write a C program to check whether a number is positive, negative, or zero


using if-else. Explain the logic. (5 Marks)
Conceptual Logic:
If number > 0 → the number is positive.​

If number < 0 → the number is negative.​


Else → the number is zero.​

Explanation:
The program takes a number as input from the user.​

It uses if-else conditional statements to compare the number with zero.​

Based on the comparison, it prints whether the number is positive, negative, or zero.​

C Program:
#include <stdio.h>

int main() {
int number;

// Input from user


printf("Enter a number: ");
scanf("%d", &number);

// Check if number is positive, negative, or zero


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

return 0;
}

Sample Output:
Enter a number: 7
The number is positive.

Enter a number: -3
The number is negative.

Enter a number: 0
The number is zero.

Conclusion:​
This program demonstrates how if-else statements can be used to classify a number as
positive, negative, or zero.

UNIT 2:
1. Explain for, while, and do-while loops with syntax and examples.
Compare their working. (5 Marks)

Loops in C are used to execute a block of code repeatedly until a specified


condition is met. The three main loops are for, while, and do-while.

a) for Loop​
Used when the number of iterations is known.​
Syntax:
for (initialization; condition; increment)
{
statements;
}

Example: Repeating a message 5 times.


b) while Loop​
Used when the condition is checked before execution.​
Syntax:
while (condition)
{
statements;
}

c) do-while Loop​
Executes the block at least once, even if the condition is false.​
Syntax:
do
{
statements;
}
while (condition);

Comparison:

Loop Condition Minimum


Type Check Execution

for Before loop 0 times

while Before loop 0 times


do-while After loop At least 1 time

Conclusion:​
All three loops are used for repetition, but do-while is unique as it ensures
the code runs at least once.

2. What are nested loops? Explain with a pattern example (star pattern).
(5 Marks)

A nested loop occurs when one loop is placed inside another loop. It is
commonly used for patterns and matrix operations.

Explanation:

●​ The outer loop controls the number of rows.​

●​ The inner loop controls the number of columns.​

Example – Star Pattern (Conceptual):

#include <stdio.h>

int main() {
int i, j, rows = 5;

// Outer loop for rows


for(i = 1; i <= rows; i++) {
// Inner loop for columns
for(j = 1; j <= i; j++) {
printf("* ");
}
printf("\n"); // Move to next row
}

return 0;
}
output:

* *
* * *

* * * *

The first row has 1 star, the second row has 2, and so on. Nested loops print
rows and columns repeatedly to create such patterns.

Uses of Nested Loops:

●​ Printing patterns​

●​ Working with 2D arrays​

●​ Matrix multiplication​

Conclusion:​
Nested loops are useful when repeated actions are required inside another
repetition.

3. Differentiate between break and continue statements with examples.


(5 Marks)

break and continue are jump statements used to control the flow of loops.

Feature break continue

Functio Terminates the loop Skips the current


n completely iteration

Executi Exits the loop immediately Goes to the next


on iteration

Usage Used in loops and Used only in loops


switch-case
Example Use:

●​ break: Stop when a condition is met​

●​ continue: Skip a specific value but continue loop​

Conclusion:​
break ends the loop, while continue skips a step but keeps the loop running,
helping manage loop execution.

4. Describe the concept of functions in C. Explain function declaration,


definition, and calling with examples. (5 Marks)

A function is a block of code that performs a specific task. Functions make


programs modular, reusable, and easier to debug.

Key Concepts:

1.​ Function Declaration (Prototype):​


It tells the compiler about the function’s name, return type, and
parameters.​
Syntax: return_type function_name(parameter_list);​
[Link] add(int, int); // Function declaration

Function Definition:​
The actual body of the function where statements are written.​
Syntax:​

return_type function_name(parameters)
{
statements;
}
Ex.
int add(int a, int b) { // Function definition
return a + b;
}

Function Call:​
The function is executed when it is called from main() or another function.​
Syntax: function_name(arguments);
Ex.
int result;
result = add(5, 10); // Function call with arguments

Advantages of Functions:
Breaks program into smaller tasks​

Avoids repetition​

Makes debugging and testing easier​


Conclusion:​
Functions are essential in C to organize code logically and improve
readability.

5. Explain the types of function arguments (call by value and call by


reference) with examples. (5 Marks)

1. Call by Value:

●​ Copies the actual value of the argument into the function’s parameters.​

●​ Changes inside the function do not affect the original variable.​

●​ Example: Passing a to a function as a + 5 will not change a.

#include <stdio.h>

void addTen(int num) {

num = num + 10; // Change affects only local copy

printf("Inside function: num = %d\n", num);

int main() {

int number = 5;

addTen(number);

printf("In main: number = %d\n", number); // Original variable


unchanged

return 0;

2. Call by Reference:

●​ Passes the address of the variable to the function.​


●​ Changes made inside the function affect the original variable.​

●​ Example: Using pointers or reference variables.​

Conclusion:​
Call by value is safer for protecting original data, while call by reference
allows functions to modify data directly.

6. What is recursion? Explain with an example such as factorial or


Fibonacci series. (5 Marks)

Recursion is a technique where a function calls itself to solve a problem. It is


used when a problem can be broken into smaller sub-problems.

Example –#include <stdio.h>

// Recursive function to calculate factorial


int factorial(int n) {
if (n == 0) // Base case
return 1;
else
return n * factorial(n - 1); // Recursive call
}

int main() {
int num;

printf("Enter a number: ");


scanf("%d", &num);

printf("Factorial of %d is: %d\n", num, factorial(num));

return 0;
}

Advantages:

●​ Simplifies complex problems​

●​ Reduces code length​

Conclusion:​
Recursion is a powerful tool in programming but must have a base case to
prevent infinite calls.
7. Discuss the concept of variable scope (local and global) with
examples. (5 Marks)

Variable Scope determines where a variable can be accessed in a program.

1.​ Local Variable:​

●​ Declared inside a function or block​

●​ Accessible only within that function​

●​ Memory is released after function ends​

2.​ Global Variable:​

●​ Declared outside all functions​

●​ Accessible by all functions in the program​

●​ Memory exists throughout program execution​

Conclusion:​
Scope defines visibility and lifetime of variables, helping prevent errors and
control memory usage.

8. Explain storage classes in C: auto, static, extern, and register with


examples and uses. (5 Marks)

Storage Classes define the scope, lifetime, and visibility of variables.

1.​ auto: Default for local variables. Exists only within function.​

2.​ static: Local variables retain value between function calls.​

3.​ extern: Accesses variables defined outside the function or file.​

4.​ register: Stores variable in CPU register for faster access (used for
small, frequently accessed variables).​

Conclusion:​
Storage classes control memory allocation, variable lifespan, and program
efficiency.
9. Write a function in C to find the sum of two numbers. Explain how it is
called in the main() function. (5 Marks)

Answer:

Theory Explanation:

●​ A function can take two numbers as parameters, calculate their sum,


and return the result.​

●​ In the main() function, the function is called with arguments, and the
returned value can be displayed.​

●​ Functions improve modularity by separating tasks (like addition) from


the main program logic.​

C Program Example:

#include <stdio.h>

// Function to calculate sum of two numbers


int sum(int a, int b) {
return a + b;
}

int main() {
int num1, num2, result;

// Input from user


printf("Enter first number: ");
scanf("%d", &num1);
printf("Enter second number: ");
scanf("%d", &num2);

// Function call
result = sum(num1, num2);

// Display result
printf("Sum of %d and %d is: %d\n", num1, num2, result);

return 0;
}

Explanation:
1.​ The function sum() takes two integers a and b as parameters.​

2.​ It calculates their sum and returns it to the calling function.​

3.​ In main(), the function is called as sum(num1, num2), and the result is
stored in the variable result.​

4.​ The sum is then printed using printf().​

Sample Output:

Enter first number: 10

Enter second number: 20

Sum of 10 and 20 is: 30

Conclusion:

●​ Functions make programs modular, reusable, and easier to read.​

●​ The addition operation is separated from the main logic, improving


clarity and maintainability.

10. Discuss the advantages of using functions in programming. How do


they improve modularity and reusability? (5 Marks)

Advantages of Functions:

1.​ Modularity: Breaks program into smaller, manageable tasks.​

2.​ Reusability: Same function can be called multiple times.​

3.​ Readability: Makes code easier to read and understand.​

4.​ Debugging: Errors can be identified easily in small functions.​

5.​ Efficient Maintenance: Changes in one function do not affect others.​


Conclusion:​
Functions are crucial in structured programming for creating efficient,
maintainable, and reusable code.

UNIT 3 – ARRAYS AND STRINGS

1. Explain the concept of a one-dimensional array. Write a program to input


and display elements of an array. (5 Marks)

A one-dimensional array (1D array) is a collection of elements of the same data


type stored in consecutive memory locations. It allows storing multiple values under
a single name, making data management easier.

Program – Input and Display Array:

#include <stdio.h>
int main() {
int marks[5], i;
printf("Enter 5 marks: ");
for(i = 0; i < 5; i++) {
scanf("%d", &marks[i]);
}
printf("Marks are: ");
for(i = 0; i < 5; i++) {
printf("%d ", marks[i]);
}
return 0;
}

Conclusion:​
1D arrays help efficiently store and manipulate a series of data using loops.

2. Describe two-dimensional arrays with syntax and example. Write a program


to store and print a 3×3 matrix. (5 Marks)

A two-dimensional array (2D array) is like a table with rows and columns. Each
element is identified by row and column indices.

Program – 3×3 Matrix Input and Display:

#include <stdio.h>
int main() {
int matrix[3][3], i, j;
printf("Enter elements of 3x3 matrix:\n");
for(i = 0; i < 3; i++) {
for(j = 0; j < 3; j++) {
scanf("%d", &matrix[i][j]);
}
}
printf("Matrix is:\n");
for(i = 0; i < 3; i++) {
for(j = 0; j < 3; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}
return 0;
}

Conclusion:​
2D arrays are essential for mathematical operations, graphics, and storing
structured data.
3. Explain the difference between array declaration and initialization with
suitable examples. (5 Marks)
Array Declaration: Allocates memory for the array without giving values.​

int numbers[5]; // Declared array

●​

Array Initialization: Assigns values at the time of declaration or later.​



int numbers[5] = {1, 2, 3, 4, 5}; // Initialized array

●​

Conclusion:​
Declaration reserves space; initialization assigns specific values to array elements.

4. Discuss various applications of arrays in real-world programming with


examples. (5 Marks)

Applications:

●​ Storing Data: Example: int marks[30]; for storing student marks​

●​ Games: 2D array for Tic-Tac-Toe board​

●​ Mathematical Calculations: Matrix operations using int matrix[3][3];​

●​ Sorting and Searching: Array can be used in linear or binary search​

●​ Database Records: Store multiple values of the same type​

Conclusion:​
Arrays provide organized storage and efficient manipulation of data in programming.

5. What is a string in C? Explain string declaration and initialization with


examples. (5 Marks)
String Declaration:​

char name[20];

String Initialization:​

char name[20] = "Pooja";
Conclusion:​
Strings are sequences of characters used widely for text storage and processing in C.

6. Explain input and output functions used for strings (gets, puts, scanf,
printf) with examples. (5 Marks)

Examples:

#include <stdio.h>
int main() {
char name[20];

// Input using scanf


printf("Enter your name: ");
scanf("%s", name);
printf("Hello %s\n", name);

// Input using gets


printf("Enter full name: ");
gets(name);
puts(name); // Output using puts

return 0;
}

Conclusion:​
These functions allow reading and displaying strings effectively in C.

7. Describe the use of string handling functions: strlen(), strcpy(),


strcat(), and strcmp() with examples. (5 Marks)

Examples:

#include <stdio.h>
#include <string.h>
int main() {
char str1[20] = "Hello";
char str2[20] = "World";

printf("Length: %lu\n", strlen(str1)); // strlen


strcpy(str2, str1); // strcpy
strcat(str1, str2); // strcat
printf("Comparison: %d\n", strcmp(str1, str2)); // strcmp
return 0;
}

Conclusion:​
strlen() → finds the length of a string.​

strcpy() → copies one string into another.​

strcat() → joins two strings.​

strcmp() → compares two strings.​

These functions make string manipulation easy in C.

8. W.A.P for searching elements in an array (5 Marks)

Simple Program – Linear Search:

#include <stdio.h>
int main() {
int arr[5] = {10, 20, 30, 40, 50}, i, key;
printf("Enter element to search: ");
scanf("%d", &key);
for(i = 0; i < 5; i++) {
if(arr[i] == key) {
printf("Element found at index %d", i);
break;
}
}
if(i == 5)
printf("Element not found");
return 0;
}

Conclusion:​
Searching in arrays helps find specific values efficiently.

9. Write a program to accept array and array elements from user and display
the array (5 Marks)

Program:

#include <stdio.h>
int main() {
int n, i;
printf("Enter size of array: ");
scanf("%d", &n);
int arr[n];

printf("Enter array elements: ");


for(i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}

printf("Array elements are: ");


for(i = 0; i < n; i++) {
printf("%d ", arr[i]);
}

return 0;
}

Conclusion:​
This program demonstrates input and output of array elements dynamically.

10. Describe common string operations such as concatenation, comparison,


and copying with examples. (5 Marks)

Example Program:

#include <stdio.h>
#include <string.h>
int main() {
char str1[20] = "Hello";
char str2[20] = "World";

// Concatenation
strcat(str1, str2);
printf("Concatenated: %s\n", str1);

// Copying
strcpy(str2, str1);
printf("Copied string: %s\n", str2);

// Comparison
if(strcmp(str1, str2) == 0)
printf("Strings are equal\n");
else
printf("Strings are not equal\n");

return 0;
}

Conclusion:​
String operations are essential for text manipulation in C programs.

11. What is a string? Explain the types of string operations in detail. (5 Marks)

Definition of String:​
In C, a string is a sequence of characters stored in contiguous memory locations
and terminated by a null character \0. Strings are essentially one-dimensional
character arrays. They are widely used to store text such as names, messages,
and sentences.

Declaration and Initialization of Strings:

char name[20]; // Declaration


char name[20] = "Pooja"; // Initialization

Types of String Operations in C:

1.​ Input/Output Operations:​

○​ Input: Using scanf() (single word) or gets() (whole line including


spaces)​

○​ Output: Using printf() or puts()​

char str[20];
scanf("%s", str);
gets(str);
printf("%s", str);
puts(str);

String Length (strlen)​

Returns the number of characters in a string, excluding the null character.​

printf("Length: %lu", strlen(str));

String Copy (strcpy)​

Copies the contents of one string into another.​

char str2[20];
strcpy(str2, str);

String Concatenation (strcat)​

Joins two strings by appending the second string to the first.​

strcat(str, str2);

String Comparison (strcmp)​

Compares two strings lexicographically.​

Returns 0 if equal, <0 if first string is smaller, >0 if first string is greater.​

if(strcmp(str, str2) == 0)
printf("Strings are equal");

Other Operations:​

strrev (reverse string, compiler dependent)​

strlwr / strupr (convert to lowercase/uppercase)​

Substring extraction using loops​

Conclusion:​
Strings are essential for text processing in C. Operations such as input/output,
length calculation, copying, concatenation, and comparison allow programmers to
efficiently manipulate and analyze textual data.

You might also like