1. list the different keywords in c
The C programming language has a fixed set of 32 reserved keywords that have special meanings and cannot be used as identifiers (like variable or function names). These keywords belong to categories such as data types, control flow, storage class, type qualifiers, and others.
Categories of Keywords:
· Data types: char, int, float, double, void, short, long, signed, unsigned
· Control flow: if, else, switch, case, default, for, while, do, break, continue
· Storage class: auto, register, static, extern
· Type qualifiers: const, volatile
· User-defined types: struct, union, enum
· Operators and utilities: sizeof, return, goto, typedef
2. state the user defined function
A user-defined function in C is a function that is written by the programmer to perform a specific task. Unlike built-in functions (like printf or scanf), user-defined functions are created by the user to provide modularity, code reusability, and better organization of the program.
Key parts of a user-defined function:
1. Function Prototype (Declaration): Specifies the function's name, return type, and parameters to inform the compiler.
2. Function Definition: Contains the actual code or statements that perform the task.
3. Function Call: The statement in the program where the function is invoked.
Basic syntax of a user-defined function:
c
return_type function_name(type1 arg1, type2 arg2, ...) {
// function body with statements
// optional return statement
}
Example:
c
// Function prototype
int sum(int, int);
// Function definition
int sum(int x, int y) {
return x + y;
}
int main() {
int result = sum(10, 11); // Function call
printf("Sum of 10 and 11 = %d\n", result);
return 0;
}
4. What is the compilation and execution?
Compilation in C:
Compilation is the process of converting human-readable source code written in C into machine-readable code that a computer can execute. It involves multiple steps that translate the high-level programming language into binary instructions. The compiler also checks the source code for syntax errors and generates an executable program if there are no errors.
The main steps in the compilation process are:
1. Preprocessing: The preprocessor handles directives starting with #, removes comments, expands macros, and includes header files. It prepares an intermediate file.
2. Compiling: The compiler translates the preprocessed code into assembly language (low-level instructions specific to the machine).
3. Assembling: The assembler converts the assembly code into machine language, producing an object file.
4. Linking: The linker combines object files and libraries to create a complete executable program.
Execution in C:
Execution is the process of running the compiled program on the computer. Once the compilation produces an executable file, this file is loaded into memory by the operating system and executed sequentially by the processor to perform the program's tasks and produce output.
In summary:
· Compilation translates and transforms the source code into an executable.
· Execution runs the executable code on the machine to perform the intended operations.
5. String
6. Declaration of pointer
Declaration of Pointer in C
A pointer is a variable that stores the memory address of another variable. To declare a pointer, the syntax involves specifying the data type of the variable the pointer will point to, followed by an asterisk (*), and then the pointer variable name.
Syntax:
c
type *pointer_name;
· type: Data type of the variable the pointer points to (e.g., int, char, float).
· *: Indicates that the variable is a pointer.
· pointer_name: Name of the pointer variable.
Examples:
c
int *p; // Pointer to an int
char *ch; // Pointer to a char
float *fptr; // Pointer to a float
Explanation:
· The pointer p can store the memory address of an integer variable.
· The pointer ch can store the address of a character variable.
· The pointer fptr points to a float variable.
Initializing a Pointer:
To assign a pointer, use the address-of operator (&) to get the address of a variable:
c
int var = 10;
int *p = &var; // p holds the address of var
Dereferencing a Pointer:
To access the value stored at the address the pointer is pointing to, use the dereference operator (*):
c
printf("%d", *p); // Outputs the value of var, which is 10
6. Types of constants
Types of Constants in C with Examples
Constants in C represent fixed values that do not change during program execution. The major types of constants are:
1. Integer Constants
o Represent whole numbers.
o Can be decimal, octal (leading 0), or hexadecimal (leading 0x or 0X).
o Examples:
§ Decimal: 123, 5673
§ Octal: 0122 (octal for decimal 82)
§ Hexadecimal: 0x1A3, 0x9F
2. Floating Point Constants
o Represent real numbers with decimal points.
o Can also use exponential notation.
o Examples:
§ Decimal: 3.14, 6.0
§ Exponential: 6.022e23
3. Character Constants
o Represent single characters enclosed in single quotes.
o Examples: 'A', '5', '$'
4. String Constants
o Represent sequences of characters enclosed in double quotes.
o Examples: "Hello World", "1234"
5. Enumeration Constants
o User-defined named integral constants defined using enum.
o Example:
c
enum days { Sunday, Monday, Tuesday, Wednesday };
// Sunday has value 0, Monday 1, etc.
Defining Constants in C:
· Using const keyword:
c
const float PI = 3.14;
· Using #define preprocessor:
c
#define PI 3.14
Examples:
c
#include <stdio.h>
#define MAX 100 // Preprocessor constant
int main() {
const int MIN = 0; // Constant variable
int decimal = 123; // Integer constant
float pi = 3.14; // Floating constant
char ch = 'A'; // Character constant
char str[] = "Hello"; // String constant
printf("MAX: %d\n", MAX);
printf("MIN: %d\n", MIN);
printf("Decimal: %d\n", decimal);
printf("Pi: %f\n", pi);
printf("Character: %c\n", ch);
printf("String: %s\n", str);
return 0;
}
7. Types of function with example
Functions in C are broadly categorized into two main types: library (predefined) functions and user-defined functions. User-defined functions can further be classified based on whether they take arguments and return values.
1. Library (Predefined) Functions
These functions are built into the C language and provided through standard libraries. They perform common tasks and can be used by including the appropriate header file.
Example:
c
#include <stdio.h>
int main() {
printf("Hello, World!\n"); // printf is a predefined function
return 0;
}
2. User-Defined Functions
Functions created by the programmer to perform specific tasks. They enable modular and reusable code.
Types of user-defined functions:
Type | Description | Example |
No arguments, no return value | Does not take any input nor return a value | void greet() { printf("Hello\n"); } |
Arguments, no return value | Takes input arguments but does not return anything | void printSum(int a, int b) { printf("%d\n", a+b); } |
No arguments, returns a value | Takes no arguments but returns a value | int getNumber() { return 10; } |
Arguments and returns a value | Takes arguments and returns a value | int add(int a, int b) { return a + b; } |
Example for each:
c
#include <stdio.h>
// No arguments, no return value
void greet() {
printf("Hello!\n");
}
// Arguments, no return value
void printSum(int a, int b) {
printf("Sum: %d\n", a + b);
}
// No arguments, returns a value
int getNumber() {
return 10;
}
// Arguments and returns a value
int add(int a, int b) {
return a + b;
}
int main() {
greet();
printSum(3, 4);
int num = getNumber();
printf("Number: %d\n", num);
int result = add(5, 7);
printf("Add Result: %d\n", result);
return 0;
}
8. while and do while
While Loop in C:
The while loop is an entry-controlled loop, meaning the condition is evaluated before the loop body executes. If the condition is false initially, the loop body will not execute even once.
Syntax:
c
while (condition) {
// code block to execute
}
Example:
c
#include <stdio.h>
int main() {
int i = 1;
while (i <= 5) {
printf("%d\n", i);
i++;
}
return 0;
}
Output:
1
2
3
4
5
Do-While Loop in C:
The do-while loop is an exit-controlled loop, meaning the loop body executes first, then the condition is checked. This guarantees that the loop body runs at least once, even if the condition is false.
Syntax:
c
do {
// code block to execute
} while (condition);
Example:
c
#include <stdio.h>
int main() {
int i = 1;
do {
printf("%d\n", i);
i++;
} while (i <= 5);
return 0;
}
Output:
1
2
3
4
5
Key Differences:
· While loop: Condition checked before the body; may not execute if condition is false initially.
· Do-while loop: Body executes once before condition is checked; always executes at least once.
10. Operations performed on string
Operations performed on strings in C commonly use functions from the <string.h> library. Some of the fundamental string operations with examples include:
1. String Length (strlen)
Returns the length of a string (excluding the null terminator).
c
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello";
printf("Length: %lu\n", strlen(str)); // Output: 5
return 0;
}
2. String Copy (strcpy)
Copies the content of one string into another.
c
#include <stdio.h>
#include <string.h>
int main() {
char src[] = "Hello";
char dest[20];
strcpy(dest, src);
printf("Copied String: %s\n", dest); // Output: Hello
return 0;
}
3. String Concatenation (strcat)
Joins two strings by appending the source string to the destination string.
c
#include <stdio.h>
#include <string.h>
int main() {
char str1[20] = "Hello, ";
char str2[] = "World!";
strcat(str1, str2);
printf("Concatenated String: %s\n", str1); // Output: Hello, World!
return 0;
}
4. String Comparison (strcmp)
Compares two strings lexicographically.
Returns 0 if equal, negative if first string is less, positive if greater.
c
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "Apple";
char str2[] = "Applet";
int result = strcmp(str1, str2);
printf("Comparison Result: %d\n", result); // Output: Negative (str1 < str2)
return 0;
}
5. Find Character in String (strchr)
Searches for the first occurrence of a character in a string.
c
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello";
char *ptr = strchr(str, 'e');
if (ptr != NULL) {
printf("Character found at position: %ld\n", ptr - str + 1);
} else {
printf("Character not found\n");
}
return 0;
}
11.Enumerate the data types
The different data types in C are categorized primarily into basic (or primary) data types, derived data types, user-defined types, and special types.
Basic Data Types in C:
1. int — used to store integer values (whole numbers without decimals).
2. char — used to store single characters or ASCII values.
3. float — used to store single precision floating-point (decimal) numbers.
4. double — used to store double precision floating-point numbers (larger and more precise than float).
5. void — represents the absence of a value; used mainly for functions returning no value and for void pointers.
Additional Modifiers and Derived Types:
· short and long modify the size/range of integer data types.
· signed and unsigned specify whether an integer can represent negative values or only non-negative values.
· Derived types include arrays, pointers, structures, unions, and functions.
User-Defined Data Types:
· struct — collection of variables of different types grouped under one name.
· union — similar to struct, but all members share the same memory location.
· enum — enumerated type listing possible named values for a variable.
Here are the main data types in C with examples:
1. Integer (int)
Stores whole numbers without decimal points.
c
#include <stdio.h>
int main() {
int num = 10;
printf("Integer value: %d\n", num);
return 0;
}
Output:
Integer value: 10
2. Character (char)
Stores a single character.
c
#include <stdio.h>
int main() {
char ch = 'A';
printf("Character value: %c\n", ch);
return 0;
}
Output:
Character value: A
3. Floating-point (float)
Stores floating-point numbers (decimals) with single precision.
c
#include <stdio.h>
int main() {
float pi = 3.14;
printf("Float value: %f\n", pi);
return 0;
}
Output:
Float value: 3.140000
4. Double
Stores floating-point numbers with double precision (more accurate).
c
#include <stdio.h>
int main() {
double largeDecimal = 123.456789;
printf("Double value: %lf\n", largeDecimal);
return 0;
}
Output:
Double value: 123.456789
5. Void
Represents absence of value, used mainly for functions that do not return anything.
c
void displayMessage() {
printf("Hello from a void function.\n");
}
int main() {
displayMessage();
return 0;
}
Output:
Hello from a void function.
11. Decision Making Statements in C with Examples
Decision making statements control the flow of a program by allowing the execution of code blocks based on certain conditions. These statements evaluate Boolean expressions (true/false) and decide the next step accordingly.
1. if Statement
Executes a block of code if the condition is true.
Syntax:
c
if (condition) {
// statements to execute if condition is true
}
Example:
c
#include <stdio.h>
int main() {
int num = 10;
if (num > 5) {
printf("Number is greater than 5\n");
}
return 0;
}
2. if-else Statement
Executes one block if condition is true, and another block if false.
Syntax:
c
if (condition) {
// true block
} else {
// false block
}
Example:
c
#include <stdio.h>
int main() {
int num = 3;
if (num % 2 == 0) {
printf("Even number\n");
} else {
printf("Odd number\n");
}
return 0;
}
3. Nested if Statement
if statement inside another if statement, useful for multiple conditions.
Example:
c
#include <stdio.h>
int main() {
int num = 15;
if (num > 10) {
if (num < 20) {
printf("Number is between 10 and 20\n");
}
}
return 0;
}
4. if-else-if Ladder
Used for multiple conditions, checking one after another.
Example:
c
#include <stdio.h>
int main() {
int marks = 85;
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;
}
5. switch Statement
Selects one among many blocks of code based on the value of an expression.
Syntax:
c
switch(expression) {
case constant1:
// code block
break;
case constant2:
// code block
break;
default:
// code block
}
Example:
c
#include <stdio.h>
int main() {
int day = 3;
switch(day) {
case 1:
printf("Monday\n");
break;
case 2:
printf("Tuesday\n");
break;
case 3:
printf("Wednesday\n");
break;
default:
printf("Invalid day\n");
}
return 0;
}
12. Three types of array
Three Types of Arrays in C with Examples
1. One-Dimensional Array (1D Array)
A one-dimensional array is a linear arrangement of elements of the same data type stored in contiguous memory locations. It is like a list or a single row of elements.
Declaration Syntax:
c
data_type array_name[array_size];
Example:
c
int numbers[5] = {1, 2, 3, 4, 5};
printf("%d\n", numbers[2]); // Outputs 3 (3rd element)
2. Two-Dimensional Array (2D Array)
A two-dimensional array is an array of arrays that stores data in matrix form with rows and columns.
Declaration Syntax:
c
data_type array_name[rows][columns];
Example:
c
int matrix[2][3] = {
{1, 2, 3},
{4, 5, 6}
};
printf("%d\n", matrix[1][2]); // Outputs 6 (2nd row, 3rd column)
3. Multidimensional Array
Multidimensional arrays extend beyond 2D arrays to three or more dimensions, essentially arrays of arrays of arrays.
Declaration Syntax (3D example):
c
data_type array_name[x][y][z];
Example:
c
int tensor[2][2][3] = {
{
{1, 2, 3},
{4, 5, 6}
},
{
{7, 8, 9},
{10, 11, 12}
}
};
printf("%d\n", tensor[1][0][2]); // Outputs 9
These arrays allow organizing data efficiently for various applications ranging from simple lists to complex multi-dimensional data.The three main types of arrays in C programming are:
1. One-Dimensional Array:
A linear array that stores elements in a single row.
Example:
c
int arr[9] = {1, 2, 3, 4, 5};
printf("%d", arr[10]); // Output: 3
2. Two-Dimensional Array:
An array of arrays, stored in rows and columns, like a matrix.
Example:
c
int arr[10][11] = {
{1, 2, 3},
{4, 5, 6}
};
printf("%d", arr[12][10]); // Output: 6
3. Multidimensional Array:
Arrays with three or more dimensions, like a 3D matrix.
Example:
c
int arr[10][10][11] = {
{
{1, 2, 3},
{4, 5, 6}
},
{
{7, 8, 9},
{10, 11, 12}
}
};
printf("%d", arr[12][10]); // Output: 9
13. Operators
Operators in C Programming Language
Operators in C are symbols that perform operations on variables and values (operands). They are classified into various types based on their functionality.
1. Arithmetic Operators
Perform basic mathematical operations.
Operator | Description | Example |
+ | Addition | a + b |
- | Subtraction | a - b |
* | Multiplication | a * b |
/ | Division | a / b |
% | Modulus (remainder) | a % b |
++ | Increment | ++a, a++ |
-- | Decrement | --a, a-- |
Example:
c
int a = 10, b = 5;
int sum = a + b; // sum is 15
2. Relational Operators
Compare two values and return true or false.
Operator | Description | Example |
== | Equal to | a == b |
!= | Not equal to | a != b |
> | Greater than | a > b |
< | Less than | a < b |
>= | Greater than or equal | a >= b |
<= | Less than or equal | a <= b |
3. Logical Operators
Operate on boolean values and return true or false.
Operator | Description | Example |
&& | Logical AND | (a > 0 && b > 0) |
|
|
|
! | Logical NOT | !(a > 0) |
4. Bitwise Operators
Operate on bits of integer operands.
Operator | Description | Example |
& | Bitwise AND | a & b |
|
| Bitwise OR |
^ | Bitwise XOR | a ^ b |
~ | Bitwise NOT | ~a |
<< | Left shift | a << 1 |
>> | Right shift | a >> 1 |
5. Assignment Operators
Assign values to variables.
Operator | Description | Example |
= | Simple assignment | a = b |
+= | Add and assign | a += b (a = a+b) |
-= | Subtract and assign | a -= b |
*= | Multiply and assign | a *= b |
/= | Divide and assign | a /= b |
%= | Modulus and assign | a %= b |
&= | Bitwise AND assign | a &= b |
| = | Bitwise OR assign |
^= | Bitwise XOR assign | a ^= b |
<<= | Left shift assign | a <<= b |
>>= | Right shift assign | a >>= b |
6. Conditional (Ternary) Operator
Ternary operator works on three operands and acts as a shorthand for if-else.
c
condition ? expression1 : expression2;
Example:
c
int a = 10, b = 5;
int max = (a > b) ? a : b; // max is 10
7. Miscellaneous Operators
· sizeof() — Returns size of data type or variable in bytes.
· & — Address-of operator.
· * — Dereference operator for pointers.
· ., -> — Member access operators for structures/unions.
No comments:
Post a Comment