0% found this document useful (0 votes)
14 views

C programming

about c programming

Uploaded by

panditanu4317
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

C programming

about c programming

Uploaded by

panditanu4317
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 11

Bitwise operators are operators in C that perform bit-level operations on integer data types,

manipulating individual bits of the operands. Examples include AND (&), OR (|), XOR (^), left
shift (<<), and right shift (>>).

Constants in C: Constants are fixed values that do not change during the execution of the
program. They are used to store values that remain constant. Constants can be of different
types, such as integer constants, floating-point constants, character constants, etc.

fprintf() statement: fprintf() is a function in C used to write formatted output to a file. It


works similarly to printf(), but instead of printing to the console, it writes the output to a
specified file.

Types of Arrays: Arrays in C can be categorized as:


One-dimensional arrays: A linear collection of elements (e.g., int arr[5];).
Two-dimensional arrays: A matrix-like structure (e.g., int arr[3][4];).
Multidimensional arrays: Arrays with more than two dimensions (e.g., int arr[3][3][3];).
Dynamic arrays: Arrays whose size is determined at runtime using memory allocation
functions like malloc().

getchar() and putchar(): getchar(): A function that reads a single character from the
standard input (keyboard). Syntax: char ch = getchar(); It returns the next character input by
the user.
putchar(): A function that writes a single character to the standard output (screen). Syntax:
putchar(ch); It outputs the character ch to the console.

fscanf() is a function in C used to read formatted input from a file. It works like scanf() but
reads data from a file instead of standard input.
Syntax: int fscanf(FILE *stream, const char *format, ...);
Example: #include <stdio.h> int main() { FILE *file = fopen("data.txt", "r");
int num; fscanf(file, "%d", &num); // Reads a number from the file
printf("Number: %d\n", num); fclose(file); return 0; }

A storage class in C defines the scope, lifetime, and visibility of variables or functions. The
four types are:
auto: Default for local variables. register: Suggests storing the variable in a CPU register for
faster access. static: Preserves the value of a variable between function calls. extern: Allows
sharing a variable across multiple files.

A union in C is a user-defined data type that allows storing different types of data in the
same memory location. It shares memory for all its members, meaning only one member
can hold a value at a time.
Syntax: union UnionName { dataType1 member1;
dataType2 member2; // ... };

A token in C is the smallest individual unit in a program, like a word in a language.


Types of Tokens:
1. Keywords (e.g., int, return) Identifiers (e.g., variable or function names) Constants
(e.g., 10, 'A')
2. Operators (e.g., +, ==) Special Symbols (e.g., {, ;) Strings (e.g., "Hello")

getch() is a function in C used to read a single character from the keyboard without echoing
it on the screen. Syntax: char getch(void);
Example: #include <stdio.h> int main() { char ch; printf("Enter a character: ");
ch = getch(); // Reads a single character without echoing it
printf("\nYou entered: %c\n", ch); return 0; }

A preprocessor in C is a tool that processes the code before the actual compilation starts. It
handles directives that are used to modify the code, such as including files, defining
constants, and conditional compilation.
Common Preprocessor Directives:
#define: Defines constants or macros. #include: Includes header files. #if, #else, #endif:
Conditional compilation. #undef: Undefines a macro. #ifdef, #ifndef: Checks if a macro is
defined or not.

Q. Explain different types of loops in c with examples. give thorough answer


Entry-controlled loops & Exit-controlled loops
1. Entry-controlled Loops- These loops check the condition before the first iteration. If the
condition is false initially, the loop will not execute at all.
Subtypes of Entry-controlled Loops:
for loop & while loop
1.1 for loop- This loop is used when the number of iterations is known beforehand. It
contains initialization, condition, and increment/decrement expressions in one line.
Example: for (int i = 1; i <= 5; i++) { printf("Iteration: %d\n", i); }
1.2 while loop- This loop repeats as long as the given condition is true. The condition is
checked before each iteration, so if the condition is false initially, the loop will not execute.
Example: int i = 1; while (i <= 5) { printf("Iteration: %d\n", i); i++; }
2. Exit-controlled Loops- These loops check the condition after the loop body has
executed, ensuring that the loop is always executed at least once.
Subtype of Exit-controlled Loop: do-while loop
2.1 do-while loop- The loop executes at least once, even if the condition is false, because
the condition is checked after the loop body.
Example: int i = 1; do { printf("Iteration: %d\n", i); i++; } while (i <= 5);
 Entry-controlled loops: Condition is checked before execution.
o for loop - while loop
 Exit-controlled loops: Condition is checked after execution.
o do-while loop
These loops are categorized based on when the condition is evaluated during the loop's
execution.

1. break and continue statements in loops: break: Exits the loop immediately. continue:
Skips the current iteration and moves to the next one. Example: #include <stdio.h> int
main() {
for (int i = 1; i <= 10; i++) { if (i == 6) break; // Exit loop when i is 6
printf("%d ", i); } printf("\n"); for (int i = 1; i <= 10; i++) {
if (i == 6) continue; // Skip 6 printf("%d ", i); } return 0; }

Dynamic memory management in C allows programs to allocate memory during runtime, as


opposed to static memory allocation, where memory is fixed at compile time. This provides
flexibility and efficient use of memory. malloc(): Allocates a block of memory of a
specified size but does not initialize it. Returns a pointer to the allocated memory. calloc():
Allocates memory for an array of specified elements and initializes it to zero. It is similar to
malloc(), but it also sets the allocated memory to zero. realloc(): Changes the size of an
already allocated memory block. It can be used to resize memory that was initially allocated
using malloc() or calloc(). free(): Deallocates memory that was previously allocated using
malloc(), calloc(), or realloc(). It is essential to free memory to prevent memory leaks in the
program.

Ternary Operator in C: The ternary operator is a shorthand for the if-else statement and
allows for concise conditional expressions. Syntax: condition ? expression_if_true :
expression_if_false; How it works: If the condition is true, the expression_if_true is
executed. If the condition is false, the expression_if_false is executed. It is
typically used for simple conditions where an if-else statement would be unnecessarily
lengthy. The ternary operator helps reduce the amount of code, making it more readable
and compact.

Q. Explain Malloc() and Free() functions with example.


In C, malloc() and free() are functions used for dynamic memory allocation and deallocation,
respectively.
1. malloc() Function
The malloc() function is used to allocate a block of memory of a specified size during
runtime. It returns a pointer to the first byte of the allocated memory. If the memory
allocation fails, it returns NULL.
Syntax: void *malloc(size_t size);
2. free() Function
The free() function is used to deallocate or release a block of memory that was previously
allocated using malloc(), calloc(), or realloc(). This is important to prevent memory leaks in a
program.
Syntax: void free(void *ptr);
Example: #include <stdio.h> #include <stdlib.h>
int main() { int *ptr = (int *)malloc(sizeof(int));
if (ptr == NULL) { printf("Memory allocation failed!\n");
return 1; } *ptr = 42; printf("Value: %d\n", *ptr);
free(ptr); // Deallocate memory return 0; }

Q. Explain Nested if giving suitable example.


A nested if statement in C is an if statement inside another if statement. It allows for
checking multiple conditions, with each condition evaluated only if the outer condition is
true.
Syntax: if (condition1) { // Code to execute if condition1 is true
if (condition2) { // Code to execute if both condition1 and condition2 are true } }
Example: #include <stdio.h>int main() { int num1 = 10, num2 = 5;
if (num1 > 0) { // Outer if condition if (num2 > 0) { // Inner if condition
printf("Both numbers are positive.\n"); } else {
printf("num2 is not positive.\n"); } } else {
printf("num1 is not positive.\n"); } return 0; }

Q. Write a C program to delete element from an array at a specific position.


#include <stdio.h> int main() { int n, pos;
printf("Enter number of elements: "); scanf("%d", &n);
int arr[n]; printf("Enter elements: ");
for (int i = 0; i < n; i++) { scanf("%d", &arr[i]); }
printf("Enter position to delete: "); scanf("%d", &pos);
if (pos < 1 || pos > n) { printf("Invalid position!\n");
} else { for (int i = pos - 1; i < n - 1; i++) {
arr[i] = arr[i + 1]; } n--; // Reduce the array size
printf("Updated array: "); for (int i = 0; i < n; i++) {
printf("%d ", arr[i]); } printf("\n"); }
return 0; }

Q. Write a C program to find factorial of a number using recursion.


#include <stdio.h> int factorial(int n) {
if (n == 0 || n == 1) // 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; }

Q. Write a C program to store information of 10 students and display it using structure.


#include <stdio.h> struct Student { int rollNo;
char name[50]; float marks; };
int main() { struct Student students[10]; // Array of 10 students
for (int i = 0; i < 10; i++) { printf("Enter details for student %d:\n", i + 1);
printf("Roll No: "); scanf("%d", &students[i].rollNo);
printf("Name: "); scanf(" %[^\n]%*c", students[i].name); // To read string with
spaces
printf("Marks: "); scanf("%f", &students[i].marks);
printf("\n"); } // Display the information
printf("\nStudent Information:\n"); for (int i = 0; i < 10; i++) {
printf("Student %d:\n", i + 1); printf("Roll No: %d\n", students[i].rollNo);
printf("Name: %s\n", students[i].name); printf("Marks: %.2f\n\n",
students[i].marks);
} return 0; }

Q. Write a C program to print number triangle. 1 1 2 1 1 2 3 2 1 1 2 3 4 3 2 1 1 2 3 4 5 4 3 2


1

#include <stdio.h> int main() { int i, j, num = 5;


for (i = 1; i <= num; i++) { for (j = i; j < num; j++) { printf(" "); }
for (j = 1; j <= i; j++) { printf("%d ", j); }
for (j = i - 1; j >= 1; j--) { printf("%d ", j); }
printf("\n"); } return 0; }

Q. Write a C program to count a number of words and characters in a file.


#include <stdio.h> #include <ctype.h>
int main() { FILE *file; char ch; int wordCount = 0, charCount = 0;
int inWord = 0; file = fopen("input.txt", "r"); if (file == NULL) {
printf("File not found!\n"); return 1; }
while ((ch = fgetc(file)) != EOF) { charCount++;
if (isspace(ch)) { if (inWord) { wordCount++;
inWord = 0; } } else { inWord = 1;
} } if (inWord) { wordCount++; }
fclose(file); printf("Number of characters: %d\n", charCount);
printf("Number of words: %d\n", wordCount); return 0; }

Q. Write a C program to swap two numbers using pointers


#include <stdio.h> void swap(int *a, int *b) {
int temp = *a; *a = *b; *b = temp; }
int main() { int num1, num2; printf("Enter two numbers: ");
scanf("%d %d", &num1, &num2);
printf("Before swapping: num1 = %d, num2 = %d\n", num1, num2);
swap(&num1, &num2); printf("After swapping: num1 = %d, num2 = %d\n", num1,
num2);
return 0; }
Q. Write a C program to accept marks of 10 students of a class in an array. Calculate and
print average marks.
#include <stdio.h> int main() { int marks[10]; int sum = 0;
float average; printf("Enter marks of 10 students:\n");
for (int i = 0; i < 10; i++) { printf("Student %d: ", i + 1);
scanf("%d", &marks[i]); sum += marks[i]; }
average = sum / 10.0; printf("Average marks: %.2f\n", average); return 0; }

Q. Write a C program to print Fibonacci series for 'n' terms using recursion.
#include <stdio.h> int fibonacci(int n) { if (n <= 1) {
return n; } else { return fibonacci(n - 1) + fibonacci(n - 2); } }
int main() { int n; printf("Enter the number of terms: ");
scanf("%d", &n); printf("Fibonacci series: "); for (int i = 0; i < n; i++) {
printf("%d ", fibonacci(i)); } printf("\n"); return 0; }

Q. Write a C program to accept 60 students record in an array of structure with fields Roll
No., Name, Marks. Print student name who is having highest marks.
#include <stdio.h> #include <string.h> struct Student {
int rollNo; char name[50]; float marks; };
int main() { struct Student students[60]; int i; int highestIndex = 0;
printf("Enter details of 60 students:\n"); for (i = 0; i < 60; i++) {
printf("Student %d:\n", i + 1); printf("Roll No: ");
scanf("%d", &students[i].rollNo); printf("Name: ");
scanf(" %[^\n]%*c", students[i].name); printf("Marks: ");
scanf("%f", &students[i].marks); printf("\n"); }
for (i = 1; i < 60; i++) { if (students[i].marks > students[highestIndex].marks) {
highestIndex = i; } } printf("Student with highest marks:\n");
printf("Name: %s\n", students[highestIndex].name); printf("Roll No: %d\n",
students[highestIndex].rollNo); printf("Marks: %.2f\n", students[highestIndex].marks);
return 0; }

Q. Write a C program to print following patterns:


A. #include <stdio.h> int main() { int i, j, num = 4, count = 1;
for (i = 1; i <= num; i++) { for (j = 1; j <= i; j++) { printf("%d ", count);
count++; } printf("\n"); } return 0; }

B. #include <stdio.h> int main() { int i, j, num = 5;


for (i = num; i >= 1; i--) { for (j = i; j < num; j++) { printf(" "); }
for (j = 1; j <= i; j++) { printf("%d ", i); } printf("\n"); }
return 0; }

#include <stdio.h> int main() { int i, j, num = 4, count = 1;


for (i = 1; i <= num; i++) { for (j = i; j < num; j++) { printf(" "); }
for (j = 1; j <= i; j++) { printf("%d ", count); count++; }
printf("\n"); } return 0; }

#include <stdio.h> int main() { int i, j, num = 5;


for (i = num; i >= 1; i--) { for (j = i; j < num; j++) { printf(" "); }
for (j = 1; j <= i; j++) { printf("%d ", i); } printf("\n"); } return 0; }

Q. Write a C program to count and display total number of alphabets, numeric characters,
special characters, number of words and number of lines in a file.
#include <stdio.h> #include <ctype.h> int main() { FILE *file; char ch;
int alphabets = 0, digits = 0, specialChars = 0, words = 0, lines = 0; int inWord = 0;
file = fopen("file.txt", "r"); if (file == NULL) { printf("Could not open file.\n"); return
1; }
while ((ch = fgetc(file)) != EOF) { if (isalpha(ch)) { alphabets++; }
else if (isdigit(ch)) { digits++; } else if (!isspace(ch)) { specialChars++; }
if (isspace(ch) || ch == '\n' || ch == '\t') { if (inWord) { words++; inWord = 0; }
} else { inWord = 1; } if (ch == '\n') { lines++; } } if (inWord) { words++; }
fclose(file); printf("Total alphabets: %d\n", alphabets);
printf("Total numeric characters: %d\n", digits); printf("Total special characters: %d\n",
specialChars);
printf("Total words: %d\n", words); printf("Total lines: %d\n", lines); return 0; }

Q. Write a C program to store n elements in an array and print the elements using pointer.
#include <stdio.h> int main() { int n, i; printf("Enter the number of elements: ");
scanf("%d", &n); int arr[n]; printf("Enter %d elements:\n", n); for (i = 0; i < n; i++) {
scanf("%d", &arr[i]); } printf("Elements in the array are:\n"); int *ptr = arr;
for (i = 0; i < n; i++) { printf("%d ", *(ptr + i)); } return 0; }

Q. Write a C program to declare two dimension array 4x3, accept element for the same.
give explanation too.
#include <stdio.h> int main() { int arr[4][3]; int i, j;
printf("Enter elements for the 4x3 array:\n"); for (i = 0; i < 4; i++) {
for (j = 0; j < 3; j++) { printf("Enter element for arr[%d][%d]: ", i, j);
scanf("%d", &arr[i][j]); } }
printf("\nElements of the 4x3 array are:\n"); for (i = 0; i < 4; i++) {
for (j = 0; j < 3; j++) { printf("%d ", arr[i][j]); } printf("\n"); } return 0; }
Explanation: Array Declaration: The statement int arr[4][3]; declares a two-dimensional
array arr with 4 rows and 3 columns. This means the array can store 12 elements in total.

Q. Write a C program to find the square of any number using the function.
#include <stdio.h> int square(int num) { return num * num; }
int main() { int number, result; printf("Enter a number: ");
scanf("%d", &number); result = square(number);
printf("The square of %d is %d\n", number, result); return 0; }

Q. Write a C program to enter the string, display and count the length of string.
#include <stdio.h> #include <string.h> int main() {
char str[100]; int length; printf("Enter a string: "); fgets(str, sizeof(str), stdin);
printf("You entered: %s", str); length = strlen(str) - 1;
printf("Length of the string is: %d\n", length); return 0; }

Q. Write a C program to enter elements of 4x4 matrix, display matrix and count the sum of
all elements.
#include <stdio.h> int main() { int matrix[4][4];
int i, j, sum = 0; printf("Enter the elements of the 4x4 matrix:\n");
for (i = 0; i < 4; i++) { for (j = 0; j < 4; j++) {
printf("Enter element at matrix[%d][%d]: ", i, j); scanf("%d", &matrix[i][j]); } }
printf("\nThe entered 4x4 matrix is:\n"); for (i = 0; i < 4; i++) {
for (j = 0; j < 4; j++) { printf("%d ", matrix[i][j]); } printf("\n"); }
for (i = 0; i < 4; i++) { for (j = 0; j < 4; j++) { sum += matrix[i][j]; } }
printf("\nSum of all elements in the matrix is: %d\n", sum); return 0; }

Q. Write a C program to accept string from the console and count number of characters,
words, special characters, and spaces in the entered string.
#include <stdio.h> #include <ctype.h> int main() { char str[100];
int i, characters = 0, words = 0, spaces = 0, special_characters = 0;
int in_word = 0; printf("Enter a string: "); fgets(str, sizeof(str), stdin);
for (i = 0; str[i] != '\0'; i++) { if (isalpha(str[i])) { characters++; in_word = 1;
} else if (isdigit(str[i])) { characters++; in_word = 1; } else if (isspace(str[i])) {
spaces++; if (in_word) { words++; in_word = 0; } } else { special_characters++;
} } if (in_word) { words++; } printf("\nTotal characters: %d\n", characters);
printf("Total words: %d\n", words); printf("Total spaces: %d\n", spaces);
printf("Total special characters: %d\n", special_characters); return 0; }

Q. Write a C program to make a simple calculator by using switch statement minimum five
basic arithmetic operations.
#include <stdio.h> int main() { float num1, num2, result; int choice;
printf("Simple Calculator\n"); printf("Select an operation:\n");
printf("1. Addition\n"); printf("2. Subtraction\n"); printf("3. Multiplication\n");
printf("4. Division\n"); printf("5. Modulo (Remainder)\n"); printf("Enter your choice (1-
5): ");
scanf("%d", &choice); printf("Enter two numbers: "); scanf("%f %f", &num1, &num2);
switch(choice) { case 1: result = num1 + num2; printf("Result: %.2f\n", result); break;
case 2: result = num1 - num2; printf("Result: %.2f\n", result); break;
case 3: result = num1 * num2; printf("Result: %.2f\n", result); break;
case 4: if(num2 != 0) { result = num1 / num2; printf("Result: %.2f\n", result);
} else { printf("Error: Division by zero is not allowed.\n"); } break;
case 5: if((int)num2 != 0) { result = (int)num1 % (int)num2;
printf("Result: %.0f\n", result); } else { printf("Error: Modulo by zero is not allowed.\
n"); }
break; default: printf("Invalid choice. Please select a valid option between 1 and 5.\
n");
} return 0; }

You might also like