0% found this document useful (0 votes)
26 views19 pages

C Programming

The document provides an overview of C programming concepts, including algorithms, loops, variables, operators, and the structure of a C program. It explains key elements such as header files, control statements, data types, and the importance of not using keywords as identifiers. Additionally, it covers practical examples and pseudocode for common programming tasks.

Uploaded by

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

C Programming

The document provides an overview of C programming concepts, including algorithms, loops, variables, operators, and the structure of a C program. It explains key elements such as header files, control statements, data types, and the importance of not using keywords as identifiers. Additionally, it covers practical examples and pseudocode for common programming tasks.

Uploaded by

sandhya.check
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 19

C PROGRAMMING

PART-A

1. Define an Algorithm.

An algorithm is a step-by-step procedure to solve a specific problem or perform a task. It


consists of a sequence of well-defined instructions that can be executed systematically.
Algorithms are finite, precise, and ensure the desired outcome when followed correctly.

2. Write a for loop to print the numbers from 10 to 1 in descending order.

for(int i = 10; i >= 1; i--)


{
printf("%d\n", i);
}

This loop starts with i as 10 and reduces it by 1 in each iteration. It continues until i becomes less
than 1, printing numbers from 10 to 1 in descending order.

3. Distinguish between an algorithm and a flowchart.


4. What is a header file in C? Provide the names of any two commonly used header files.

A header file in C contains definitions and declarations of functions, macros, and variables,
which can be included in programs using the #include directive. For example, stdio.h is used for
input/output operations, and math.h provides mathematical functions. These header files make
code reusable and reduce redundancy.

5. Write a pseudocode to check whether a number is even or odd.

plaintext
CopyEdit
Start
Input number
If number % 2 == 0
Print "Even"
Else
Print "Odd"
End

This pseudocode checks if the remainder when the number is divided by 2 is zero. If true, the
number is even; otherwise, it is odd.

6. Write the output for the below program:

#include<stdio.h>
int main()
{
int number;
for(number=1;number<=10;number++)
{
printf("%d\n",number);
}
return 0;
}

The output of the program is:


1
2
3
4
5
6
7
8
9
10
This loop prints numbers from 1 to 10 in ascending order, one number per line.

7. What is a variable in C programming? Illustrate with an example.

A variable in C is a named memory location used to store a value that can change during
program execution. For example, int age = 25; declares a variable age of type integer, which
stores the value 25. Variables allow the program to store, retrieve, and manipulate data
dynamically.

8. Give the purpose of the break and continue statements in C.

The break statement is used to exit a loop or switch statement prematurely when a specific
condition is met. The continue statement skips the remaining code in the current iteration of the
loop and proceeds to the next iteration. Both statements control the flow of loops, enhancing
flexibility in programming.

9. Why should keywords not be used as identifiers in C?

Keywords are reserved words in C that have predefined meanings and specific purposes, such as
int, while, and return. Using them as identifiers would cause conflicts, as the compiler interprets
them for their predefined functionalities. This would result in syntax errors and make the
program invalid.

10. State the syntax of an if-else statement.

if (condition) {
// Statements if condition is true
} else {
// Statements if condition is false
}
The if part executes when the condition evaluates to true, while the else part executes if the
condition is false. This allows the program to make decisions based on conditions.

11. Write down the rules for declaring variables.

Variable names must begin with a letter or an underscore but not a digit. They can include
letters, digits, and underscores but must not match C keywords. Variable names are case-
sensitive, meaning Age and age are treated as different variables.

12. List the different format specifiers used in C for input and output operations.

Format specifiers define the type of data to be read or printed in C programs. Common ones
include %d for integers, %f for floating-point numbers, %c for characters, %s for strings, and
%lf for double-precision floating-point numbers. These specifiers are used with functions like
scanf and printf.

13. Summarize the various types of C operators.

C operators are categorized into arithmetic, relational, logical, bitwise, and assignment operators.
Arithmetic operators like + and - perform basic calculations, while relational operators like < and
> compare values. Logical operators such as && and || enable complex condition evaluations,
and assignment operators like = assign values to variables.

14. Show the differences between while and do-while statements.

In the while loop, the condition is evaluated before executing the loop body, so it may not
execute if the condition is initially false. In the do-while loop, the body executes at least once
because the condition is evaluated after the loop. Thus, do-while guarantees at least one iteration.

15. Write a C program to perform logical operations on two numbers provided by the user.

#include <stdio.h>
int main() {
int a, b;
printf("Enter two numbers: ");
scanf("%d %d", &a, &b);
printf("Logical AND (a && b): %d\n", a && b);
printf("Logical OR (a || b): %d\n", a || b);
printf("Logical NOT (!a): %d\n", !a);

return 0;
}

This program performs logical operations like AND, OR, and NOT on two input numbers. It
demonstrates how logical operators work on integer inputs in C.

PART-B

1. Explain the general structure of a C program with an example. Discuss each part of the
structure in detail.

The general structure of a C program is standardized and consists of multiple sections to


organize the code effectively. This structure makes the program readable and ensures proper
execution.
1. Documentation Section:
The documentation section contains comments that explain the purpose of the program,
the author’s name, and any additional information about the code. Comments do not
affect the execution of the program. They are of two types:
o Single-line comments: Start with //.
o Multi-line comments: Enclosed within /* */.

Example:

// This is a single-line comment


/* This is a multi-line comment */
2. Preprocessor Directives:
Preprocessor directives are commands that instruct the compiler to perform specific tasks
before compilation. They start with the # symbol. For example, #include <stdio.h> is
used to include the Standard Input and Output library in the program. Without this,
functions like printf and scanf cannot be used.
3. Global Declarations:
Variables or constants declared outside all functions are called global variables. These
variables are accessible throughout the entire program. For instance:
int globalVar = 100; // Accessible in all functions
4. Main Function:
The main function is the entry point of any C program. Execution always begins with
main(). Its structure is as follows:
int main() {
// Code goes here
return 0; // Indicates successful execution
}
5. Local Declarations:
Variables declared inside a function are called local variables. These are specific to the
function in which they are declared. For example:
int main() {
int localVar = 10; // Accessible only in main()
return 0;
}
6. Statements:
Statements include instructions to perform actions such as printing output, taking input,
or performing calculations. For example:
printf("Hello, World!");
7. User-defined Functions:
User-defined functions allow programmers to divide complex programs into smaller
modules. These functions are created to perform specific tasks and can be called multiple
times.
Example of a C Program:

#include <stdio.h> // Preprocessor directive

// Global variable declaration


int globalVar = 10;

// User-defined function
void greet() {
printf("Hello from the function!\n");
}

int main() {
// Local variable declaration
int localVar = 5;

// Statements
printf("Global Variable: %d\n", globalVar);
greet();

return 0; // Indicates successful execution


}
Explanation of the Example:

● The #include <stdio.h> directive allows the use of input-output functions like printf.
● The global variable globalVar can be accessed by any function in the program.
● The greet() function is a user-defined function, which is called from the main() function
to display a message.
● Inside the main() function, a local variable localVar is declared and used only within the
scope of the function.

This structure ensures clarity and modularity, making the program easy to understand and
maintain.

2. Draw a flowchart to find the maximum of three numbers and explain it.

A flowchart is a visual representation of a program’s logic, making it easier to understand the


flow of execution.
Steps to Find the Maximum of Three Numbers:

1. Start the process.


2. Input three numbers, A, B, and C.
3. Compare the first number A with the other two numbers B and C.
o If A is greater than both B and C, it is the maximum.
4. If the above condition is false, compare B with C.
o If B is greater, it is the maximum.
5. If both conditions are false, C is the maximum.
6. Print the maximum number and end the process.
Explanation:

● The decision-making process involves comparing numbers using logical conditions.


● The flowchart clearly depicts the step-by-step process, ensuring that every condition is
checked before determining the result.

3. Write a pseudocode to calculate the factorial of a given number.

Factorial of a number n is the product of all positive integers from 1 to n. It is denoted as n!. For
example, 5! = 5 × 4 × 3 × 2 × 1 = 120.
Pseudocode:
START
INPUT number n
SET factorial = 1
FOR i = 1 to n
factorial = factorial * i
END FOR
PRINT factorial
STOP
Explanation of Pseudocode:

1. Start by initializing the factorial variable to 1.


2. Use a loop to multiply factorial by every number from 1 to n.
3. After the loop ends, the factorial variable holds the result.
4. Print the result and terminate the program.

For example, if n = 4, the calculation proceeds as:

4. Discuss the different categories of operators in the C programming language with relevant
examples.
Operators in C programming are symbols used to perform specific operations on variables and
values. These operations include arithmetic, comparison, logical evaluation, and more. Operators
are broadly categorized into several types:

1. Arithmetic Operators:
These operators are used for basic mathematical calculations like addition, subtraction,
multiplication, division, and modulus.
Operator Meaning Example Output
+ Addition 5+3 8
- Subtraction 5-3 2
* Multiplication 5*3 15
/ Division 15 / 3 5
% Modulus (Remainder) 15 % 4 3
Example Code:
int a = 10, b = 3;
printf("Addition: %d\n", a + b);
printf("Modulus: %d\n", a % b);

2. Relational Operators:
Relational operators are used to compare two values. The result is either true (1) or false (0).
Operator Meaning Example Output
== Equal to 5 == 3 0
Operator Meaning Example Output
!= Not equal to 5 != 3 1
> Greater than 5>3 1
< Less than 5<3 0
>= Greater than or equal to 5 >= 3 1
<= Less than or equal to 5 <= 3 0
Example Code:
int x = 10, y = 20;
if (x < y)
{
printf("x is smaller than y\n");
}

3. Logical Operators:
Logical operators combine two or more conditions.
Operator Meaning Example Output
&& Logical AND (5 > 3) && (4 > 2) 1
` Logical OR ‘5
! Logical NOT !(5 > 3) 0
Example Code:
int a = 10, b = 5;
if (a > b && b > 0) {
printf("Both conditions are true\n");
}

4. Bitwise Operators:
Bitwise operators perform operations at the bit level.
Operator Meaning Example Output
& Bitwise AND 5&3 1
` ` Bitwise OR `5
^ Bitwise XOR 5^3 6
~ Bitwise NOT ~5 -6
5. Assignment Operators:
Assignment operators are used to assign values to variables.
Operator Meaning Example Output
= Assign value a = 10 10
+= Add and assign a += 5 15
-= Subtract and assign a -= 2 8
*= Multiply and assign a *= 3 30
/= Divide and assign a /= 2 5
%= Modulus and assign a %= 3 1
Example Code:
int a = 10;
a += 5; // Equivalent to a = a + 5
printf("Updated value of a: %d\n", a);

6. Increment and Decrement Operators:


These operators increase or decrease the value of a variable by 1.
Operator Meaning Example Output
++ Increment by 1 ++a 11
-- Decrement by 1 --a 9
Example Code:
int x = 10;
x++; // Increments x by 1
printf("Value after increment: %d\n", x);

7. Conditional (Ternary) Operator:


The ternary operator is a shorthand for if-else.
Syntax Example Output

(condition) ? expr1 : expr2 (a > b) ? a : b a or b

Example Code:
int a = 5, b = 10;
int max = (a > b) ? a : b;
printf("Maximum value: %d\n", max);

8. Special Operators:
C includes some special operators for specific tasks:

● sizeof: Returns the size of a data type or variable in bytes.


● &: Address-of operator gives the memory address of a variable.
● *: Dereference operator accesses the value at the address.

Example Code:
int a = 5;
printf("Size of int: %zu\n", sizeof(a)); // Size in bytes
printf("Address of a: %p\n", &a); // Prints the address of a

Conclusion:
C programming offers a wide range of operators for performing operations efficiently.
Understanding these operators is essential for building robust and logical programs. Each type of
operator serves a unique purpose, enabling developers to write optimized and readable code.

5. Discuss the character set used in C and explain the different data types available in C
with examples.

Character Set in C:
The character set in C includes letters, digits, special symbols, and white spaces that can be used
to construct programs.
1. Letters:
o Uppercase letters: A-Z
o Lowercase letters: a-z
2. Digits:
o Numbers: 0-9
3. Special Symbols:
o ~, !, @, #, $, %, ^, &, *, (, ), {}, [], ;, : etc.
4. White Space Characters:
o Space, tab (\t), newline (\n), carriage return (\r).

The character set ensures that programs can be written using human-readable symbols.
Data Types in C:
C provides a variety of data types to handle different kinds of data. These are broadly classified
into four categories:

1. Basic Data Types:


These represent fundamental data such as integers, floating-point numbers, and characters.
Data Type Description Memory (bytes) Example
int Integer (whole numbers) 4 int x = 5;
float Floating-point numbers 4 float y = 3.14;
char Single character 1 char c = 'A';
double Double-precision float 8 double z = 2.718;

2. Derived Data Types:


These are constructed using basic data types and include arrays, pointers, and structures.

● Array: Collection of elements of the same type.


Example:

int arr[5] = {1, 2, 3, 4, 5};

● Pointer: Stores the address of another variable.


Example:

int a = 10;
int *p = &a; // Pointer to a

3. Enumeration Data Types (enum):


These allow defining variables that can take predefined values.

enum Days {Mon, Tue, Wed, Thu, Fri};


enum Days today = Mon; // Assigning Monday

4. Void Data Type:


Represents no data. Commonly used with functions that do not return a value.
Example:
void greet() {
printf("Hello, World!");
}
Example Program Using Different Data Types:
#include <stdio.h>
int main() {
int a = 10; // Integer
float b = 5.5; // Float
char c = 'A'; // Character
double d = 3.14159; // Double-precision float

printf("Integer: %d\n", a);


printf("Float: %.2f\n", b);
printf("Character: %c\n", c);
printf("Double: %.5lf\n", d);

return 0;
}
Output:
Integer: 10
Float: 5.50
Character: A
Double: 3.14159

6. Write a program to calculate the grade of a student based on marks in five subjects.

Grading Criteria:

● Marks >= 90: Grade A


● Marks >= 75: Grade B
● Marks >= 50: Grade C
● Marks < 50: Fail

Program:
#include <stdio.h>
int main() {
int marks[5], i;
float total = 0, percentage;
char grade;

// Input marks for 5 subjects


for (i = 0; i < 5; i++) {
printf("Enter marks for subject %d: ", i + 1);
scanf("%d", &marks[i]);
total += marks[i];
}
// Calculate percentage
percentage = (total / 500) * 100;

// Assign grade based on percentage


if (percentage >= 90) {
grade = 'A';
} else if (percentage >= 75) {
grade = 'B';
} else if (percentage >= 50) {
grade = 'C';
} else {
grade = 'F'; // Fail
}

// Print results
printf("Total Marks: %.2f\n", total);
printf("Percentage: %.2f%%\n", percentage);
printf("Grade: %c\n", grade);

return 0;
}
Sample Input and Output:
Enter marks for subject 1: 85
Enter marks for subject 2: 78
Enter marks for subject 3: 92
Enter marks for subject 4: 74
Enter marks for subject 5: 88

Total Marks: 417.00


Percentage: 83.40%
Grade: B

7. Write a C program to find all roots of a quadratic equation.

A quadratic equation is in the form:

Program to Find Roots of a Quadratic Equation:


#include <stdio.h>
#include <math.h> // For sqrt() function

int main() {
float a, b, c, discriminant, root1, root2, realPart, imagPart;

// Input coefficients
printf("Enter coefficients a, b, and c: ");
scanf("%f %f %f", &a, &b, &c);

// Calculate discriminant
discriminant = (b * b) - (4 * a * c);

// Check conditions for roots


if (discriminant > 0) {
// Two distinct real roots
root1 = (-b + sqrt(discriminant)) / (2 * a);
root2 = (-b - sqrt(discriminant)) / (2 * a);
printf("Roots are real and distinct: %.2f and %.2f\n", root1, root2);
} else if (discriminant == 0) {
// One real root
root1 = root2 = -b / (2 * a);
printf("Roots are real and equal: %.2f and %.2f\n", root1, root2);
} else {
// Complex roots
realPart = -b / (2 * a);
imagPart = sqrt(-discriminant) / (2 * a);
printf("Roots are complex: %.2f + %.2fi and %.2f - %.2fi\n", realPart, imagPart, realPart,
imagPart);
}

return 0;
}

Explanation of Code:

1. Input Coefficients: The user inputs the values of a, b, and c.


2. Discriminant Calculation: The discriminant formula determines the nature of the roots:
o D>0D > 0D>0: Two distinct real roots.
o D=0D = 0D=0: Two equal real roots.
o D<0D < 0D<0: Two complex roots.
3. Math Library: The sqrt() function calculates the square root. For complex roots, the
imaginary part is derived from the negative discriminant.
4. Output: Displays the roots based on the discriminant's value.

Sample Input and Output 1 (Distinct Real Roots):


Enter coefficients a, b, and c: 1 -3 2
Roots are real and distinct: 2.00 and 1.00
Sample Input and Output 2 (Complex Roots):
Enter coefficients a, b, and c: 1 2 5
Roots are complex: -1.00 + 2.00i and -1.00 - 2.00i

8. Write an algorithm to find the first N natural numbers.

Algorithm:

1. Step 1: Start.
2. Step 2: Input N, the number of natural numbers to be printed.
3. Step 3: Initialize a counter variable, i = 1.
4. Step 4: Repeat the following steps while i <= N:
o Print the value of i.
o Increment i by 1.
5. Step 5: Stop.

9. Enumerate the difference between ‘else-if ladder’ and ‘switch-case’ statements with
appropriate C programs.

Difference Between Else-If Ladder and Switch-Case:


Aspect Else-If Ladder Switch-Case
Used for selecting one option from
Usage Used for checking multiple conditions. multiple fixed values of a single
variable.
Can evaluate expressions involving Works only with integral or
Data Types
ranges and conditions. character values.
Requires repeated condition checks,
Syntax Cleaner and simpler syntax for
which can become verbose for many
Simplicity handling multiple fixed values.
conditions.
All conditions are checked sequentially Directly jumps to the matching case,
Execution
until one is satisfied. improving efficiency.

Program Using Else-If Ladder:


#include <stdio.h>
int main() {
int marks;
printf("Enter marks: ");
scanf("%d", &marks);

if (marks >= 90) {


printf("Grade A\n");
} else if (marks >= 75) {
printf("Grade B\n");
} else if (marks >= 50) {
printf("Grade C\n");
} else {
printf("Fail\n");
}
return 0;
}
Sample Output:
Enter marks: 85
Grade B

Program Using Switch-Case:


#include <stdio.h>
int main() {
int choice;
printf("Enter a number (1-3): ");
scanf("%d", &choice);

switch (choice) {
case 1:
printf("You chose 1\n");
break;
case 2:
printf("You chose 2\n");
break;
case 3:
printf("You chose 3\n");
break;
default:
printf("Invalid choice\n");
}
return 0;
}
Sample Output:
css
CopyEdit
Enter a number (1-3): 2
You chose 2

You might also like