C Programming Prepratory
C Programming Prepratory
C Programming Prepratory
1. Conditional Statements
i) if:
Example:
ii) if-else:
c
if (condition) {
// code to be executed if the condition is true
} else {
// code to be executed if the condition is false
}
Example:
c
if (condition1) {
// code to be executed if condition1 is true
} else if (condition2) {
// code to be executed if condition2 is true
} else {
// code to be executed if none of the conditions are true
}
Example:
c
int x = 0;
if (x > 0) {
printf("x is positive");
} else if (x < 0) {
printf("x is negative");
} else {
printf("x is zero");
}
Example:
c
int x = 5, y = 10;
if (x == y) {
printf("x and y are equal");
} else {
if (x > y) {
printf("x is greater than y");
} else {
printf("y is greater than x");
}
}
v) switch:
c
switch (expression) {
case value1:
// code to be executed if expression equals value1
break;
case value2:
// code to be executed if expression equals value2
break;
// add more cases as needed
default:
// code to be executed if none of the cases are true
}
Example:
c
char grade = 'B';
switch (grade) {
case 'A':
printf("Excellent");
break;
case 'B':
printf("Good");
break;
case 'C':
printf("Average");
break;
default:
printf("Not a valid grade");
}
2. Simple Calculator Program in C using Switch Statement
c
#include <stdio.h>
int main() {
char operator;
double num1, num2, result;
switch (operator) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
if (num2 != 0) {
result = num1 / num2;
} else {
printf("Error: Division by zero");
return 1; // Exit with an error code
}
break;
default:
printf("Error: Invalid operator");
return 1; // Exit with an error code
}
Anonymous
Write a C program to compute the roots of a quadratic equation by accepting the coefficients.
ChatGPT
Certainly! Below is a simple C program that computes the roots of a quadratic
equation given the coefficients
a
,
c
#include <stdio.h>
#include <math.h>
int main() {
double a, b, c;
double discriminant, root1, root2;
// Input coefficients
printf("Enter coefficients (a, b, c): ");
scanf("%lf %lf %lf", &a, &b, &c);
// Calculate discriminant
discriminant = b * b - 4 * a * c;
a
,
c
as input and calculates the roots using the quadratic formula. It considers cases
where the roots are real and distinct, real and equal, or complex.
Anonymous
Explain the following operators with an example program: i) Relational ii) increment/decrement
iii) sizeof iv) Arithmetic v) logical iv) bitwise
ChatGPT
Certainly! Let's go through each type of operator with a brief explanation and an
example program:
i) Relational Operators:
Relational operators are used to compare values. They return a Boolean result
(either true or false).
Example Program:
c
#include <stdio.h>
int main() {
int a = 5, b = 10;
// Relational operators
printf("%d > %d is %s\n", a, b, a > b ? "true" : "false");
printf("%d < %d is %s\n", a, b, a < b ? "true" : "false");
printf("%d == %d is %s\n", a, b, a == b ? "true" : "false");
printf("%d != %d is %s\n", a, b, a != b ? "true" : "false");
Example Program:
c
#include <stdio.h>
int main() {
int x = 5;
Example Program:
c
#include <stdio.h>
int main() {
int x;
double y;
// sizeof operator
printf("Size of int: %lu bytes\n", sizeof(x));
printf("Size of double: %lu bytes\n", sizeof(y));
c
#include <stdio.h>
int main() {
int a = 5, b = 2;
// Arithmetic operators
printf("Sum: %d\n", a + b);
printf("Difference: %d\n", a - b);
printf("Product: %d\n", a * b);
printf("Quotient: %d\n", a / b);
printf("Remainder: %d\n", a % b);
v) Logical Operators:
Example Program:
c
#include <stdio.h>
int main() {
int x = 5, y = 10;
// Logical operators
printf("(x > 0) && (y > 0) is %s\n", (x > 0) && (y > 0) ?
"true" : "false");
printf("(x > 0) || (y < 0) is %s\n", (x > 0) || (y < 0) ?
"true" : "false");
printf("!(x == y) is %s\n", !(x == y) ? "true" : "false");
Example Program:
c
#include <stdio.h>
int main() {
unsigned int a = 5, b = 3;
// Bitwise operators
printf("a & b is %u\n", a & b);
printf("a | b is %u\n", a | b);
printf("a ^ b is %u\n", a ^ b);
printf("~a is %u\n", ~a);
printf("a << 1 is %u\n", a << 1);
printf("a >> 1 is %u\n", a >> 1);
These examples illustrate the basic usage of each type of operator. Feel free to ask
for clarification on any specific part!
Anonymous
Explain the working of break, continue statement with a suitable example.
ChatGPT
Break Statement:
Example Program:
c
#include <stdio.h>
int main() {
int i;
In this example, the loop runs from 1 to 10, but when i becomes 5, the break
statement is encountered, and the loop is exited prematurely. The output will be 1
2 3 4 Encountered 5. Exiting loop. .
Continue Statement:
The continue statement is used to skip the rest of the code inside a loop for the
current iteration and proceed to the next iteration.
Example Program:
c
#include <stdio.h>
int main() {
int i;
These statements provide control flow within loops, allowing you to exit a loop
prematurely or skip specific iterations based on certain conditions.
Anonymous
Compute sin(x) using Taylor series approximation. Compare your result with the built-in library
function. Print both the results with appropriate inferences.
ChatGPT
Certainly! Below is a C program that computes sin(x) using the Taylor series
approximation and compares the result with the built-in library function ( sin() ). It
uses a few terms of the Taylor series for the approximation.
c
#include <stdio.h>
#include <math.h>
return result;
}
int main() {
double x, resultTaylor, resultLibrary;
// Compare results
printf("\nComparison:\n");
printf("Absolute difference between Taylor series and library
function: %lf\n", fabs(resultTaylor - resultLibrary));
In this program, the computeSin function approximates sin(x) using the Taylor
series with a specified number of terms. The results are then compared with the
built-in sin() function, and the absolute difference is printed. You can adjust the
terms variable to see how the approximation improves with more terms in the
series.
Anonymous
Explain the following looping statements with syntax and example program. i) while ii) do-while
iii) for.
ChatGPT
i) while Loop:
The while loop repeatedly executes a block of statements as long as the given
condition is true.
Syntax:
Example Program:
c
#include <stdio.h>
int main() {
int i = 1;
The do-while loop is similar to the while loop, but it guarantees that the block
of statements is executed at least once, as the condition is checked after the
execution.
Syntax:
Example Program:
c
#include <stdio.h>
int main() {
int i = 1;
The for loop is used when you know the number of iterations in advance. It
combines initialization, condition checking, and increment/decrement in a single
line.
Syntax:
Example Program:
c
#include <stdio.h>
int main() {
// for loop example
for (int i = 1; i <= 5; i++) {
printf("%d ", i);
}
Each type of loop has its use cases, and you can choose the one that fits your
specific scenario based on the control flow requirements.
Anonymous
Explain how to declare and initialize a string with examples.
ChatGPT
c
#include <stdio.h>
int main() {
// Declaration and initialization using character array
char str1[] = "Hello, World!";
In this example, str1 is a character array automatically sized to fit the provided
string literal.
int main() {
// Declaration and initialization using a pointer to a string
literal
const char *str2 = "Programming in C";
c
#include <stdio.h>
int main() {
// Declaration and manual initialization character by
character
char str3[20]; // Declare a character array of size 20
// Manual initialization
str3[0] = 'C';
str3[1] = 'o';
str3[2] = 'd';
str3[3] = 'e';
str3[4] = '\0'; // Null-terminate the string
Keep in mind that strings in C are null-terminated, meaning they end with the null
character '\0' . This character signifies the end of the string when using standard
string functions.
Choose the method based on your specific needs and the nature of your data. The
first two examples are common and concise, while the third example provides more
control over individual characters.
Anonymous
Explain all the string handling functions with syntax and example program for each.
ChatGPT
Certainly! Here are explanations and example programs for some common string
handling functions in C:
Syntax:
Example Program:
c
#include <stdio.h>
#include <string.h>
int main() {
const char *str = "Hello, World!";
return 0;
}
2. strcpy - String Copy:
Syntax:
Example Program:
c
#include <stdio.h>
#include <string.h>
int main() {
const char *src = "Copy me!";
char dest[20];
return 0;
}
Syntax:
Example Program:
c
#include <stdio.h>
#include <string.h>
int main() {
char dest[20] = "Hello, ";
const char *src = "World!";
return 0;
}
Syntax:
Example Program:
c
#include <stdio.h>
#include <string.h>
int main() {
const char *str1 = "apple";
const char *str2 = "banana";
if (result < 0) {
printf("%s comes before %s\n", str1, str2);
} else if (result > 0) {
printf("%s comes after %s\n", str1, str2);
} else {
printf("%s is equal to %s\n", str1, str2);
}
return 0;
}
Syntax:
Example Program:
c
#include <stdio.h>
#include <string.h>
int main() {
const char *src = "Copy me!";
char dest[20];
return 0;
}
These are just a few examples, and there are more string handling functions in C.
Each function serves a specific purpose, and you can choose the appropriate one
based on your requirements.
Anonymous
Write a C program to check if the input string is palindrome or not. with built-in function without
built-in function
ChatGPT
Checking Palindrome with Built-in Function:
c
#include <stdio.h>
#include <string.h>
return 1; // Palindrome
}
int main() {
char input[100];
return 0;
}
Checking Palindrome without Built-in Function:
c
#include <stdio.h>
return 1; // Palindrome
}
int main() {
char input[100];
return 0;
}
These programs take a string as input, and using either built-in functions ( strlen )
or manual length calculation, they check whether the given string is a palindrome or
not. If it is a palindrome, a corresponding message is printed.
Anonymous
Explain how to declare and initialize array of strings with examples.
ChatGPT
Syntax:
c
#include <stdio.h>
int main() {
// Declaration and initialization of an array of strings
char strings[][20] = {"Apple", "Banana", "Cherry", "Date"};
return 0;
}
If you want to dynamically allocate memory for an array of strings, you can use
pointers:
Syntax:
c
#include <stdio.h>
#include <stdlib.h>
int main() {
// Dynamic allocation of an array of strings
char **strings;
strings = (char **)malloc(4 * sizeof(char *));
strings[0] = "Apple";
strings[1] = "Banana";
strings[2] = "Cherry";
strings[3] = "Date";
return 0;
}
In this example, strings is a pointer to a pointer ( char ** ), and memory is
dynamically allocated to store pointers to strings. Each string is then assigned to
the corresponding memory location.
Remember to free the dynamically allocated memory using free to avoid memory
leaks.
Choose the method based on your specific requirements. The first example with a
fixed-size array is suitable when the number of strings is known at compile time,
while the second example with dynamic memory allocation is useful when the
number of strings is determined at runtime.
Anonymous
Write functions to implement string operations such as compare, concatenate, and find string
length. Use the parameter passing techniques.
ChatGPT
Certainly! Here's an example C program that defines functions to implement string
operations—compare, concatenate, and find string length—using parameter passing
techniques:
c
#include <stdio.h>
#include <stdlib.h>
int length2 = 0;
while (str2[length2] != '\0') {
length2++;
}
if (result == NULL) {
fprintf(stderr, "Memory allocation failed.\n");
exit(1); // Exit with an error code
}
return result;
}
return length;
}
int main() {
const char *string1 = "Hello";
const char *string2 = "World";
// Compare strings
if (compareStrings(string1, string2)) {
printf("Strings are equal.\n");
} else {
printf("Strings are not equal.\n");
}
// Concatenate strings
char *concatenatedString = concatenateStrings(string1,
string2);
printf("Concatenated string: %s\n", concatenatedString);
return 0;
}
Anonymous
Define pointer variable. State its uses. Explain with example the declaration and initialization of
pointer variable.
ChatGPT
Pointer Variable:
Declaration Syntax:
Initialization Example:
c
#include <stdio.h>
int main() {
int x = 10;
return 0;
}
In this example, int *ptr; declares a pointer variable named ptr that can store
the memory address of an integer. The &x operator is used to get the memory
address of the variable x , and this address is then assigned to the pointer variable
ptr . The *ptr expression is used to access the value stored at the memory
location pointed to by ptr , which, in this case, is the value of x . The output would
be Value of x: 10 .
Anonymous
Write a C program using pointers to compute sum, mean and standard deviation of all elements
stored in an array of n real numbers.
ChatGPT
Certainly! Below is a C program that uses pointers to compute the sum, mean, and
standard deviation of elements stored in an array of n real numbers:
c
#include <stdio.h>
#include <math.h>
// Calculate sum
for (int i = 0; i < n; i++) {
*sum += arr[i];
}
// Calculate mean
*mean = *sum / n;
int main() {
int n;
double numbers[n];
return 0;
}
This program takes the number of elements and the array of real numbers as input,
calculates the sum, mean, and standard deviation using pointers, and then outputs
the results. The calculateStats function is responsible for performing the
computations.
Anonymous
Explain all the steps used to open a file in C language.
ChatGPT
To open a file in C, you typically use the fopen function. Below are the steps
involved in opening a file in C:
Include the necessary header file for file operations, which is <stdio.h> .
Check if the file was opened successfully by verifying if the file pointer is not NULL .
c
if (filePointer == NULL) {
// Handle error (e.g., print an error message and exit the
program)
perror("Error opening file");
return 1; // Exit with an error code
}
Example Program:
c
#include <stdio.h>
int main() {
FILE *filePointer;
return 0;
}
In this example, the file "example.txt" is opened in read mode ("r"). If the file is
successfully opened, you can perform additional file operations (reading, writing,
etc.), and finally, close the file using fclose . Always remember to close the file
when you're done to release system resources.
Anonymous
Explain all the functions used to read from a file in C language.
ChatGPT
In C, there are several functions used to read from a file. The primary ones are
fgetc , fgets , and fread . Here's an explanation of each:
c
char *fgets(char *str, int n, FILE *stream);
Description: Reads up to n-1 characters from the specified file (stream ) and
stores them in the string str . It stops reading when a newline character is
encountered, or n-1 characters are read, or the end of file is reached.
Example:
c
FILE *file = fopen("example.txt", "r");
char buffer[100];
fclose(file);
3. fread - Read Block of Data from File:
c
size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);
Description: Reads up to nmemb blocks of data, each size bytes long, from the
specified file (stream ) and stores them in the memory block pointed to by ptr .
Return Value: Returns the total number of elements successfully read (which
may be less than nmemb if the end of file is reached or an error occurs).
Example:
c
FILE *file = fopen("example.bin", "rb");
int buffer[100];
fclose(file);
These functions provide different levels of granularity for reading from a file,
allowing you to choose the one that fits your specific requirements. Always
remember to check for errors and handle them appropriately.
Anonymous
Explain all the functions used to write to a file in C language.
ChatGPT
In C, there are several functions used to write to a file. The primary ones are fputc ,
fputs , and fwrite . Here's an explanation of each:
c
3. fwrite - Write Block of Data to File:
c
size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE
*stream);
Description: Writes up to nmemb blocks of data, each size bytes long, from the
memory block pointed to by ptr to the specified file (stream ).
Return Value: Returns the total number of elements successfully written (which
may be less than nmemb if an error occurs).
Example:
c
FILE *file = fopen("output.bin", "wb");
int buffer[100];
fclose(file);
These functions provide different levels of granularity for writing to a file, allowing
you to choose the one that fits your specific requirements. Always remember to
check for errors and handle them appropriately. Additionally, close the file using
fclose when you're done writing to it to ensure that the changes are saved and
resources are released.
Anonymous
Write a C program to copy a text file to another, read both the input file name and target file
name.
ChatGPT
Certainly! Here's a simple C program that copies the contents of one text file to
another. It prompts the user to enter both the input file name and the target file
name:
c
#include <stdio.h>
#include <stdlib.h>
int main() {
char inputFileName[MAX_FILENAME_LENGTH];
char targetFileName[MAX_FILENAME_LENGTH];
FILE *inputFile, *targetFile;
char buffer[BUFFER_SIZE];
size_t bytesRead;
return 0;
}
This program prompts the user to enter the names of the input file and target file. It
then opens the input file for reading and the target file for writing. It reads the
content from the input file in chunks and writes it to the target file. Finally, it closes
both files.
Anonymous
Explain Structure definition, declaration, accessing and initialization of structures with suitable
example.
ChatGPT
Structure Definition in C:
Syntax:
Structure Initialization:
Example:
c
#include <stdio.h>
// Structure definition
struct Point {
int x;
int y;
};
int main() {
// Structure declaration and initialization
struct Point p1 = {10, 20};
return 0;
}
In this example, a structure named Point is defined with two members ( x and
y ). Two variables p1 and p2 of type Point are declared and initialized with
values. The coordinates are accessed using the dot ( . ) operator.
Anonymous
Implement structures to read, write and compute average- marks of the students, list the
students scoring above and below the average marks for a class of N students.
ChatGPT
Certainly! Here's an example program in C that uses structures to read, write, and
compute the average marks of students. It also lists students scoring above and
below the average marks:
c
#include <stdio.h>
#include <stdlib.h>
return totalMarks / n;
}
int main() {
int n;
return 0;
}
This program prompts the user to enter the number of students, then reads details
for each student (name and marks). It computes the average marks and lists
students scoring above and below the average. Dynamic memory allocation is used
to handle an array of students.
Anonymous
Differentiate structures and unions.
Summary:
Structures allow grouping of variables where each member has its own memory
location, suitable for scenarios where multiple pieces of information are needed
simultaneously.
Unions allow grouping of variables where all members share the same memory
location, suitable for scenarios where only one piece of information is needed at
a time. The size of a union is determined by its largest member.
Anonymous
Explain enumerated datatype in C language.
ChatGPT
Enumerated Datatype in C:
int main() {
// Declare a variable of type 'Color'
enum Color myColor;
return 0;
}
In this example, the enum Color defines three constants: Red , Green , and
Blue , each having an associated integer value (starting from 0 by default). The
myColor variable is then declared, assigned the value Blue , and used in a switch
statement to determine the color.
Enums provide a way to create more meaningful and self-explanatory code,
especially when dealing with a set of related constants.
|
|
|