C LANGUAGE UNIT-1
C LANGUAGE
UNIT=1
Q.1 Define Programming Language. Differentiate between Compiler and Interpreter.
Ans. Define Programming Language
A Programming Language is a formal language used to write instructions (programs) that a computer can understand and execute.
It allows programmers to communicate with the computer to perform specific tasks like calculations, data processing, file handling, and controlling hardware.
Programming languages use syntax (rules) and semantics (meaning).
Programs written in high-level languages (like C, C++, Java) must be translated into machine language.
C language is a high-level, structured, and procedure-oriented programming language developed by Dennis Ritchie.
》Uses of Programming Language
To develop software and applications
To solve real-world problems logically
To control hardware and system resources
To create efficient and reusable programs
》Compiler
A Compiler is a language translator that converts the entire source code written in a high-level language (like C) into machine code at once.
It checks all errors together after compilation.
It generates an object code / executable file.
Example: C compiler (GCC, Turbo C)
Working of Compiler
Source Code → Compiler → Object Code → Execution
》Interpreter
An Interpreter is a language translator that converts one statement at a time from high-level language into machine code and executes it immediately.
It checks errors line by line.
No separate object code is generated.
Example: Python interpreter
Working of Interpreter
Source Code → Interpreter → Execution (line by line)
》Difference Between Compiler and Interpreter (Without Table)
1.Compiler translates the entire program at once, whereas interpreter translates the program line by line.
2.Compiler shows all errors after compiling the whole program, whereas interpreter shows errors immediately.
3.Compiler generates object code, but interpreter does not generate object code.
4.Programs compiled using compiler execute faster, while interpreted programs execute slower.
5.Compiler-based languages like C require compilation only once, while interpreted languages need interpreter every time.
》Conclusion
Compiler is faster and more efficient for large programs like C programs.
Interpreter is easier for debugging and learning.
C language uses a compiler, which makes it suitable for system programming and performance-critical applications.
Q.2. Explain Structure of a C Program with Diagram
A C program follows a fixed and well-defined structure.
Each part of a C program has a specific purpose and is written in a proper sequence.
Understanding the structure of a C program helps in writing clear, correct, and error-free programs.
》Structure of a C Program:
A C program is generally divided into the following parts:
●Documentation Section
●Link Section
●Definition Section
●Global Declaration Section
●main() Function
●User Defined Functions
》Diagram: Structure of a C Program
+----------------------------+
| Documentation Section |
| (Comments) |
+----------------------------+
| Link Section |
| (#include statements) |
+----------------------------+
| Definition Section |
| (#define statements) |
+----------------------------+
| Global Declaration Section |
| (Global variables, |
| function prototypes) |
+----------------------------+
| main() Function |
| { |
| Declaration statements |
| Executable statements |
| } |
+----------------------------+
| User Defined Functions |
| (Function definitions) |
+----------------------------+
》Explanation of Each Section
1. Documentation Section
>This section contains comments.
>It is used to describe the program such as program name, author name, date, and purpose.
>Comments improve program readability.
>Comments are ignored by the compiler.
>Example:
/* Program to find sum of two numbers */
2. Link Section
>This section includes header files using #include.
>Header files provide predefined functions.
>Example: stdio.h is used for input/output functions like printf() and scanf().
>Example:
#include <stdio.h>
3. Definition Section
>This section defines constants using #define.
>Constants defined here cannot be changed during program execution.
>It helps to make programs more readable and maintainable.
>Example:
#define PI 3.14
4. Global Declaration Section
>This section declares global variables and function prototypes.
>Global variables can be accessed by all functions in the program.
>Function prototypes tell the compiler about functions used later.
>Example:
int a, b;
int add(int, int);
5. main() Function
>Execution of a C program always starts from the main() function.
>It is the most important part of a C program.
>It contains:
Declaration of local variables
Executable statements
>Example:
int main()
{
int sum;
sum = a + b;
printf("%d", sum);
return 0;
}
6. User Defined Functions
>These functions are written by the programmer.
>They are used to divide a large program into smaller parts.
>This improves modularity, reusability, and readability of code.
>They are defined outside the main() function.
>Example:
int add(int x, int y)
{
return x + y;
}
3. Explain C Tokens with examples.
Introduction
>C Tokens are the smallest individual units of a C program.
>The C compiler breaks a program into tokens to understand and compile it.
>Every keyword, variable name, constant, operator, and special symbol in a C program is considered a token.
》Main types of C tokens are: Keywords, Identifiers, Constants, Strings, Operators, and Special Symbols.
2.Identifier – Short Explanation
An Identifier is a name given to a variable, function, array, or any other user-defined item in a C program.
Identifiers are used to identify program elements uniquely.
Examples:
sum, total_marks, main, add
Rules for Identifiers:
Must begin with a letter (a–z or A–Z) or underscore (_)
Cannot start with a digit
No spaces or special symbols allowed
Keywords cannot be used as identifiers
Example in C:
int sum;
➡️ Here, sum is an identifier.
Q.4. Write algorithm and flowchart to find maximum of three numbers.
》An Algorithm is a finite set of step-by-step instructions used to solve a particular problem.
It defines the logic of the program in a simple and systematic manner.
●Algorithm to Find Maximum of Three Numbers
Step 1: Start
Step 2: Read three numbers a, b, and c
Step 3: Check if a > b
>If Yes, go to Step 4
>If No, go to Step 6
Step 4: Check if a > c
>If Yes, print “a is maximum”
>If No, print “c is maximum”
Step 5: Go to Step 8
Step 6: Check if b > c
>If Yes, print “b is maximum”
>If No, print “c is maximum”
Step 7: Go to Step 8
Step 8: Stop
》A Flowchart is a graphical representation of an algorithm.
It uses standard symbols to represent different steps like input, processing, decision, and output.
(DRAW Shapes (LOOK IN ABOVE SS) in below explaination)
1. Terminator Symbol
Shape: Oval
Purpose: Represents Start and End of a flowchart
Example:
Start, End
2. Input / Output Symbol
Shape: Parallelogram
Purpose: Used to take input or display output
Example:
Read a, b, c
Print maximum
3. Process Symbol
Shape: Rectangle
Purpose: Used for calculations and processing
Example:
sum = a + b
max = a
4. Decision Symbol
Shape: Diamond
Purpose: Used for conditions and comparisons
It has Yes/No or True/False branches
Example:
a > b ?
5. Flow Line
Shape: Arrow
Purpose: Shows the direction of flow of the program
Flowchart diagram:
●Conclusion
》Algorithm explains the logic in words, while flowchart explains the same logic using diagrams.
》Both are important tools for problem solving and are widely used in C programming.
Q.5. Explain Type Conversion and Typecasting
(Intro)
Type conversion can be done automatically by the compiler or manually by the programmer. Based on this,it is classified into Type Conversion and Typecasting.
1.Type Conversion (Implicit Type Conversion)
➡️ Here, integer value 10 is automatically converted into 10.0 (float).
2.Typecasting (Explicit Type Conversion).
Syntax: (data_type) expression
➡️ Here, a is explicitly converted into float to get correct decimal result 2.5.
●Difference Between Type Conversion and Typecasting (Theory)
>Type conversion is automatic, whereas typecasting is manual.
>Type conversion is performed by the compiler, while typecasting is performed by the programmer.
>Type conversion is safer, while typecasting may lead to data loss.
>Type conversion does not require any special syntax, but typecasting requires casting operator.
____Unit:2____
1. Explain if, if-else, else-if ladder and switch-case.
2. Differentiate between Entry vs Exit controlled loop and break vs continue.
Entry Control Loop vs Exit Control Loop
》Entry control loop checks the condition before executing the loop body, while exit control loop checks the condition after executing the loop body.
》Entry control loop may execute zero times, whereas exit control loop executes at least one time.
》In entry control loop, if condition is false initially, loop body is skipped, but in exit control loop, loop body runs once even if condition is false.
》Entry control loop is used when the number of iterations is known in advance, while exit control loop is used when at least one execution is required.
》Logic of entry control loop is simple and straightforward, while exit control loop logic is slightly complex.
》Entry control loop is also called pre-test loop, while exit control loop is called post-test loop.
》for and while loops are entry control loops in C.
do-while loop is an exit control loop in C.
》Entry control loop is mostly used in counting and repetition tasks.
Exit control loop is mostly used in menu-driven and user-interactive programs.
●Break vs Continue
》The break statement terminates the loop completely, whereas the continue statement skips only the current iteration.
》After break, control comes outside the loop, but after continue, control goes to the next iteration.
》break stops further execution of the loop, while continue allows the loop to run again.
》break is used when no more looping is required, but continue is used when some values need to be ignored.
》break can be used in loops and switch statements, whereas continue is used only in loops.
》break skips all remaining statements of the loop permanently, while continue skips remaining statements only for that iteration.
》break immediately exits the loop, but continue only skips the rest of the current loop cycle.
》break immediately exits the loop, but continue only skips the rest of the current loop cycle.
Q.3. Write a program to check prime number.
#include <stdio.h>
#include <conio.h>
void main() {
int n, i, flag = 0;
clrscr();
printf("Enter a number: ");
scanf("%d", &n);
if (n <= 1) {
flag = 1;
} else {
for (i = 2; i <= n / 2; i++) {
if (n % i == 0) {
flag = 1;
break;
}
}
}
if (flag == 0)
printf("%d is a Prime number", n);
else
printf("%d is NOT a Prime number", n);
getch();
}
Output
Enter a number: 7
7 is a Prime number
Enter a number: 10
10 is NOT a Prime number
Explanation (Easy & Short)
1. User enters a number n.
2. If n is 1 or less, it is not prime.
3. Loop checks divisibility from 2 to n/2.
4. If divisible → Not Prime, otherwise → Prime.
Q.4 Write pattern program:
1
2 1
3 2 1
4 3 2 1
#include <stdio.h>
#include <conio.h>
void main() {
int i, j;
clrscr(); // Clear the screen (specific to conio.h)
for(i = 1; i <= 4; i++) { // Outer loop for rows
for(j = i; j >= 1; j--) { // Inner loop for printing numbers
printf("%d ", j);
}
printf("\n"); // Move to next row
}
getch(); // Wait for a key press before closing
}
●Explanation:
>Outer loop for(i=1;i<=4;i++) controls the rows.
>Inner loop for(j=i;j>=1;j--) prints numbers from current row number down to 1.
>printf("\n") moves to the next row after printing each line.
>The program prints the pattern exactly as required.
Q.5. Explain nested loops with example.
Q.1. Explain 1-D and 2-D Arrays with Example
●Introduction
An array is a collection of elements of the same data type stored at contiguous memory locations.
Arrays are used to store multiple values in a single variable name.
They make it easy to process large sets of data using loops.
Arrays in C can be 1-D (one-dimensional) or 2-D (two-dimensional).
●1-D Array (One-Dimensional Array)
A 1-D array stores elements in a single row.
It is also called a linear array.
Syntax:
data_type array_name[size];
Example:
int marks[5]; // 1-D array of 5 integers
Example Program: 1-D Array
#include <stdio.h>
#include<conio.h>
void main() {
int marks[5] = {80, 75, 90, 85, 70};
int i;
clrscr();
for(i = 0; i < 5; i++) {
printf("marks[%d] = %d\n", i, marks[i]);
}
getch();
}
Output:
marks[0] = 80
marks[1] = 75
marks[2] = 90
marks[3] = 85
marks[4] = 70
●2-D Array (Two-Dimensional Array)
A 2-D array stores elements in rows and columns, forming a matrix/table.
Syntax:
data_type array_name[rows][columns];
Example:
int matrix[2][3]; // 2 rows and 3 columns
Example Program: 2-D Array
#include <stdio.h>
#include <conio.h>
void main() {
int matrix[2][3] = {{1, 2, 3}, {4, 5, 6}};
int i, j;
clrscr();
for(i = 0; i < 2; i++) {
for(j = 0; j < 3; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}
getch();
}
Output:
1 2 3
4 5 6
●Key Differences
1-D array → single row of elements; 2-D array → multiple rows and columns.
1-D array is like a list; 2-D array is like a table or matrix.
1-D array needs one subscript [i]; 2-D array needs two [i][j].
Both store elements of the same data type.
Arrays help in efficient data processing with loops.
Q.2. Program to find maximum element from array.
#include <stdio.h>
#include <conio.h>
void main() {
int arr[10], i, n, max;
clrscr(); // Clear screen
printf("Enter number of elements (max 10): ");
scanf("%d", &n);
printf("Enter %d elements:\n", n);
for(i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
max = arr[0]; // Assume first element as maximum
for(i = 1; i < n; i++) {
if(arr[i] > max) {
max = arr[i]; // Update max if current element is larger
}
}
printf("Maximum element in the array = %d", max);
getch(); // Wait for key press
}
》Sample Input
Enter number of elements (max 10): 5
Enter 5 elements:
12 45 7 22 34
》Output
Maximum element in the array = 45
●Explanation :
>arr[10] is the array to store elements.
>max stores the maximum value.
>The first element is assumed as maximum.
>Loop compares each element with max.
If a larger element is found, max is updated.
>After loop ends, max contains the largest element in the array.
Q.3. Explain String Functions in C
Introduction
A string in C is a sequence of characters terminated by a null character \0.
Strings are stored as arrays of characters.
C provides a set of library functions in string.h to manipulate strings easily.
●Commonly Used String Functions
》strlen(str)
Returns the length of the string (number of characters before \0).
Example:
char str[] = "Hello";
printf("%d", strlen(str)); // Output: 5
》strcpy(dest, src)
Copies the source string into the destination string.
Example:
char src[] = "Hello";
char dest[10];
strcpy(dest, src);
printf("%s", dest); // Output: Hello
》strcat(dest, src)
Concatenates (joins) source string at the end of destination string.
Example:
char str1[20] = "Hello ";
char str2[] = "World";
strcat(str1, str2);
printf("%s", str1); // Output: Hello World
》strcmp(str1, str2)
Compares two strings.
If both strings are equal, it returns 0; otherwise, it returns a negative or positive value.
Example:
strcmp("abc", "abd"); // Returns negative value
》strrev(str)
Reverses the string.
Example:
char str[] = "Hello";
strrev(str);
printf("%s", str); // Output: olleH
》strupr(str) / strlwr(str)
Converts string to uppercase / lowercase.
Example:
char str[] = "Hello";
strupr(str);
printf("%s", str); // Output: HELLO
●Conclusion
String functions in C help to handle, manipulate, and compare strings easily.
●Program code:
#include <stdio.h>
#include <conio.h>
#include <string.h>
void main() {
char str1[20], str2[20], str3[20];
int len;
clrscr(); // Clear screen
// Input two strings (single word only)
printf("Enter first string: ");
scanf("%s", str1);
printf("Enter second string: ");
scanf("%s", str2);
// 1. strlen() - Length of first string
len = strlen(str1);
printf("\nLength of first string: %d", len);
// 2. strcpy() - Copy string
strcpy(str3, str1);
printf("\nString copied to str3: %s", str3);
// 3. strcat() - Concatenate strings
strcat(str1, str2);
printf("\nAfter concatenation (str1 + str2): %s", str1);
// 4. strcmp() - Compare strings (numeric result)
printf("\nResult of strcmp(str2, str3): %d", strcmp(str2, str3));
// 5. strrev() - Reverse string
strrev(str3);
printf("\nReverse of str3: %s", str3);
// 6. strupr() - Uppercase string
strupr(str3);
printf("\nUppercase of str3: %s", str3);
// 7. strlwr() - Lowercase string
strlwr(str3);
printf("\nLowercase of str3: %s", str3);
getch(); // Wait for key press
}
●Sample Input
Enter first string: hello
Enter second string: world
●Sample Output
Length of first string: 5
String copied to str3: hello
After concatenation (str1 + str2): helloworld
Result of strcmp(str2, str3): 15
Reverse of str3: olleh
Uppercase of str3: OLLEH
Lowercase of str3: olleh
Q.4. Explain User Defined Functions
●Introduction
A function is a block of code that performs a specific task.
Functions help in reducing code repetition, making programs modular, and easier to debug.
》There are two types of functions in C:
1>Built-in functions – Provided by C library (like printf(), scanf())
2>User-defined functions – Created by the programmer
●Definition
A user-defined function is a function written by the programmer to perform a specific task repeatedly whenever needed.
● Advantages of User Defined Functions
Code Reusability – Write once, use multiple times.
Modularity – Program can be divided into smaller, manageable parts.
Ease of Debugging – Errors can be easily traced in smaller functions.
Reduces Complexity – Makes large programs easier to understand.
Better Readability – Function names describe their task.
●Structure of a User Defined Function
A function has 4 main parts:
>Function Declaration (Prototype) – Tells the compiler about the function.
int sum(int a, int b);
>Function Definition – Contains the actual code of the function.
int sum(int a, int b) {
return a + b;
}
>Function Call – Used to execute the function in main().
result = sum(5, 3);
>Return Type – Data type of value returned by function (int, float, void).
●Example Program
#include <stdio.h>
#include <conio.h>
// Function Definition
int sum(int a, int b) {
return a + b;
}
void main() {
int x = 5, y = 3, result;
clrscr(); // Clear screen
// Function Call
result = sum(x, y);
printf("Sum of %d and %d is %d", x, y, result);
getch(); // Wait for key press
}
●Output
Sum of 5 and 3 is 8
Q.5. Recursive Factorial Program
●Introduction
A recursive function is a function that calls itself to solve a problem.
Factorial of a number n is n! = n × (n-1) × (n-2) × … × 1.
Recursive factorial uses the formula:
factorial(n)=n×factorial(n-1)
Base case: factorial(0) = 1 or factorial(1) = 1
●Program:
#include <stdio.h>
#include <conio.h>
// Function to calculate factorial
int factorial(int n) {
if(n <= 1)
return 1; // Base case
else
return n * factorial(n - 1); // Recursive call
}
void main() {
int num, fact;
clrscr(); // Clear screen
printf("Enter a number: ");
scanf("%d", &num);
fact = factorial(num); // Call the recursive function
printf("Factorial of %d is %d", num, fact);
getch(); // Wait for key press
}
●Sample Input / Output
>Input:
Enter a number: 4
>Output:
Factorial of 4 is 24
●Explanation
factorial() calls itself until n becomes 1.
Each call multiplies n with factorial(n-1).
Base case (n <= 1) stops the recursion.
The final result is returned and printed in main().


Comments
Post a Comment