Unit 1 CPS
Unit 1 CPS
In C programming, keywords are reserved words that have a special meaning and
purpose in the language. These keywords cannot be used as identifiers (like variable
names, function names, etc.). Here's a list of commonly used keywords in C:
1. auto - Declares automatic variables.
2. break - Exits from a loop or a switch statement.
3. case - Used in switch statements to define individual cases.
4. char - Declares a character variable.
5. const - Declares a constant value that cannot be changed.
6. continue - Skips the remaining code in the current iteration of a loop and jumps
to the next iteration.
7. default - Specifies the default case in a switch statement.
8. do - Used in do-while loops, which execute at least once.
9. double - Declares a double-precision floating-point variable.
10. else - Used with if to execute a block of code when the condition is false.
11. enum - Defines an enumeration, a set of named integer constants.
12. extern - Declares a variable or function as external.
13. float - Declares a floating-point variable.
14. for - Used for loop iteration.
15. goto - Jumps to a labeled statement within a function.
16. if - Used for conditional execution of code.
17. int - Declares an integer variable.
18. long - Declares a long integer variable.
19. register - Suggests that the variable be stored in a CPU register.
20. return - Exits from a function and optionally returns a value.
21. short - Declares a short integer variable.
22. signed - Specifies a signed modifier for integer types.
23. sizeof - Returns the size of a data type or variable.
24. static - Declares a static variable or function with internal linkage.
25. struct - Defines a structure, a user-defined data type.
26. switch - Allows a variable to be tested against a list of values.
27. typedef - Defines a new name (alias) for an existing data type.
28. union - Defines a union, a data structure that can hold different data types in the
same memory location.
29. unsigned - Specifies an unsigned modifier for integer types.
30. void - Specifies that a function returns no value or declares a pointer to an
unknown data type.
31. volatile - Indicates that a variable may be changed unexpectedly.
32. while - Used for loop iteration as long as a condition is true.
These keywords form the foundation of C programming and are integral to writing C
code.
Identifiers in C Language
In C programming, identifiers are names used to identify variables, functions, arrays,
and other user-defined items. Identifiers allow you to name and refer to these elements
in your code. Here are the key points regarding identifiers in C:
Rules for Naming Identifiers:
1. Character Set:
o Identifiers must begin with a letter (uppercase or lowercase) or an
underscore (_).
o The subsequent characters can be letters, digits, or underscores.
o Example: sum, _counter, var1.
2. Case Sensitivity:
o C is case-sensitive, meaning that variable, Variable, and VARIABLE are all
different identifiers.
3. Length:
o Identifiers can be of any length, but only the first 31 characters are
typically considered significant by most compilers.
4. No Reserved Words:
o Identifiers cannot be the same as C keywords (like int, return, while, etc.)
because keywords are reserved for specific purposes in the language.
5. No Special Characters:
o Identifiers cannot contain special characters like @, #, !, -, etc. The only
special character allowed is the underscore (_).
Examples of Valid Identifiers:
totalSum
_index
counter1
average_value
Examples of Invalid Identifiers:
2ndVariable (starts with a digit)
total-sum (contains a hyphen)
float (a reserved keyword)
Best Practices:
Meaningful Names: Choose identifiers that describe the purpose of the variable
or function (e.g., totalSum for a variable holding the sum).
Use of Underscores: When using multiple words, you can separate them with
underscores for readability (e.g., total_sum, max_value).
Avoid Starting with Underscore: Although allowed, starting identifiers with an
underscore is generally discouraged because identifiers that begin with an
underscore followed by a capital letter, or identifiers that start with two
underscores, are reserved for the implementation (e.g., in libraries or system
headers).
By following these rules and best practices, you can write clear and maintainable C
code.
Data Types in C Language
In C programming, data types define the type of data that can be stored in a variable,
as well as the operations that can be performed on that data. C has a rich set of data
types that can be categorized into several groups:
1. Basic Data Types
int:
o Used to store integers (whole numbers).
o Size: Typically 4 bytes.
o Example: int count = 10;
float:
o Used to store floating-point numbers (numbers with a decimal point).
o Size: Typically 4 bytes.
o Example: float temperature = 36.5;
double:
o Used to store double-precision floating-point numbers (more precision
than float).
o Size: Typically 8 bytes.
o Example: double area = 9.6789234;
char:
o Used to store a single character.
o Size: 1 byte.
o Example: char grade = 'A';
void:
o Represents the absence of type. Commonly used for functions that do not
return a value.
o Example: void function_name() { }
2. Derived Data Types
Arrays:
o A collection of elements of the same type.
o Example: int numbers[10]; (an array of 10 integers)
Pointers:
o Variables that store the address of another variable.
o Example: int *ptr; (pointer to an integer)
Functions:
In C, functions are blocks of code that perform a specific task, which can be
called from other parts of the program. Functions help organize code, improve
readability, and promote reusability.
o Functions help in breaking down complex problems into simpler pieces.
o They make the code more modular and easier to understand.
o Functions in C can be recursive, calling themselves to solve problems.
Strings:
In C, strings are arrays of characters terminated by a null character ('\0'). Since C
does not have a dedicated string data type, strings are handled as arrays of
char.
o Strings in C are null-terminated character arrays.
o Use functions from <string.h> for string manipulation.
o Handle strings carefully to avoid common pitfalls like buffer overflows.
3. User Defined Data Types
Structures (struct):
o A collection of variables of different data types under a single name.
o Example:
struct Person {
char name[50];
int age;
float height;
};
Unions (union):
o Similar to structures, but all members share the same memory location.
o Example:
union Data {
int i;
float f;
char str[20];
};
Enumerations (enum):
o A user-defined type that consists of named integer constants.
o Example:
enum Day {Sunday, Monday, Tuesday, Wednesday, Thursday, Friday,
Saturday};
Typedef (typedef):
The typedef keyword in C is used to create new type names (aliases) for existing
data types. This can make complex data types easier to work with, improve
code readability, and provide a more meaningful way to use certain types in a
program.
o ‘typedef’ does not create new data types; it only creates aliases.
o It can greatly improve code clarity and maintainability, especially when
working with complex or frequently used types.
o It's a common practice in C programming, especially when defining
structures, unions, and function pointers.
o Syntax: The general syntax for using typedef is:
typedef existing_type new_type_name;
Examples:
typedef unsigned long ulong
4. Modifiers
Modifiers are used with basic data types to alter the size or range of the data type.
short:
o Used to declare short integers.
o Example: short int x;
long:
o Used to declare long integers.
o Example: long int x;
signed:
o Default modifier for int, char, and other types (can store both positive and
negative values).
o Example: signed int x;
unsigned:
o Used to declare unsigned integers (can only store positive values).
o Example: unsigned int y;
Summary of Basic Data Types with Size (Typical):
char - 1 byte
int - 4 bytes
float - 4 bytes
double - 8 bytes
void - No storage
Choosing the Right Data Type:
Efficiency: Choose the smallest data type that can hold the value to save
memory.
Precision: Use double for high precision floating-point operations.
Boolean: Use _Bool or int (with 0 and 1) for true/false values.
Complexity: Use structures for complex data that involves multiple variables of
different types.
By understanding these data types and their modifiers, you can write more efficient
and effective C programs.
Constants
In C, a constant refers to a value that does not change during the execution of a
program. Constants are used to represent fixed values, such as numbers, characters, or
strings. There are several types of constants in C:
1. Integer Constants
These are whole numbers without any fractional or decimal part. They can be positive
or negative.
Decimal Constants: Base 10 (e.g., 123, -456)
Octal Constants: Base 8, prefixed by 0 (e.g., 012, 077)
Hexadecimal Constants: Base 16, prefixed by 0x or 0X (e.g., 0x1A, 0XFF)
2. Floating-point Constants
These represent real numbers with a fractional part. They can be expressed in either
standard decimal or scientific notation.
Decimal Notation: (e.g., 3.14, -0.001)
Exponential Notation: (e.g., 1.23e4 for 1.23 × 10^4)
3. Character Constants
A single character enclosed in single quotes (e.g., 'A', '9', '\n').
Character constants have a type of int in C, and their value is the ASCII value of
the character.
4. String Constants (String Literals)
A sequence of characters enclosed in double quotes (e.g., "Hello, World!", "C
programming").
Strings are stored as arrays of characters terminated by a null character '\0'.
5. Enumeration Constants
Defined using the enum keyword, they assign names to integral constants, making the
code more readable.
enum Color { RED, GREEN, BLUE };
6. Defined Constants
These are constants defined using the #define preprocessor directive. These are also
called macro constants.
#define PI 3.14159
#define MAX_SIZE 100
Using const Keyword
You can also declare a variable as constant using the const keyword, which prevents its
value from being modified after initialization.
const int max_attempts = 5;
const float gravity = 9.81;
I/O Statements
In C, Input/Output (I/O) statements are used to handle data input from the user
(keyboard) and output to the console (screen). The standard library <stdio.h> provides
functions for performing input and output operations.
Common I/O Functions in C
1. printf: Outputs formatted text to the console.
2. scanf: Reads formatted input from the keyboard.
3. gets/fgets: Reads a string from the input.
4. puts: Outputs a string to the console.
5. putchar/getchar: Reads or writes a single character.
Details of Common I/O Functions
1. printf Function
Usage: Outputs formatted data to the console.
Syntax:
printf("format_string", argument_list);
Example:
printf("Hello, %s! You are %d years old.\n", "Alice", 25);
Format Specifiers:
o %d or %i: Integer
o %f: Floating-point
o %c: Character
o %s: String
o %x/%X: Hexadecimal representation of an integer
o %o: Octal representation of an integer
2. scanf Function
Usage: Reads formatted input from the console.
Syntax:
scanf("format_string", &variable);
Example:
int age;
printf("Enter your age: ");
scanf("%d", &age);
Important: Use the & (address-of) operator before variables except when
reading a string.
3. gets and fgets Functions
Usage: Read an entire line of text input.
Syntax:
o gets:
gets(string_variable);
Note: gets is unsafe and has been deprecated due to potential buffer
overflow vulnerabilities. Use fgets instead.
o fgets:
fgets(string_variable, size, stdin);
Example:
char name[50];
printf("Enter your name: ");
fgets(name, sizeof(name), stdin);
4. puts Function
Usage: Outputs a string to the console, followed by a newline character.
Syntax:
puts(string_variable);
Example:
char message[] = "Hello, World!";
puts(message);
5. putchar and getchar Functions
putchar:
o Usage: Writes a single character to the console.
o Syntax:
putchar(character);
o Example:
putchar('A');
getchar:
o Usage: Reads a single character from the console.
o Syntax:
char ch = getchar();
o Example:
printf("Enter a character: ");
char c = getchar();
printf("You entered: %c\n", c);
Example Program Using I/O Functions
Here is a simple example demonstrating the usage of printf, scanf, puts, and fgets:
#include <stdio.h>
int main() {
char name[50];
int age;
return 0;
}
Operators
In C, operators are special symbols or keywords that perform operations on one or more
operands (variables, constants, or expressions). Operators in C can be categorized into
several types based on their functionality.
Types of Operators in C
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Bitwise Operators
5. Assignment Operators
6. Increment and Decrement Operators
7. Conditional (Ternary) Operator
8. Comma Operator
9. Sizeof Operator
10. Type Cast Operator
1. Arithmetic Operators
Arithmetic operators are used to perform basic mathematical operations.
Operator Description Example
+ Addition a+b
- Subtraction a-b
* Multiplication a*b
/ Division a/b
% Modulus (remainder) a % b
Example:
int a = 10, b = 3;
int sum = a + b; // 13
int remainder = a % b; // 1
2. Relational Operators
Relational operators are used to compare two values. They return either true (non-zero)
or false (zero).
Operator Description Example
== Equal to a == b
!= Not equal to a != b
> Greater than a>b
< Less than a<b
>= Greater than or equal to a >= b
<= Less than or equal to a <= b
Example:
int a = 5, b = 8;
if (a < b) {
printf("a is less than b");
}
3. Logical Operators
Logical operators are used to combine two or more conditions or expressions.
Operator Description Example
&& Logical AND a && b
` `
! Logical NOT !a
Example:
int a = 1, b = 0;
if (a && !b) {
printf("Condition is true");
}
4. Bitwise Operators
Bitwise operators perform operations on the binary representation of data.
Operator Description Example
& Bitwise AND a&b
` ` Bitwise OR
^ Bitwise XOR (exclusive OR) a^b
~ Bitwise NOT (one's complement) ~a
<< Left shift a << 2
>> Right shift a >> 2
Example:
int a = 5; // Binary: 0101
int b = 3; // Binary: 0011
int c = a & b; // Binary AND: 0001 (Decimal: 1)
int d = a << 1; // Left shift: 1010 (Decimal: 10)
5. Assignment Operators
Assignment operators assign values to variables.
Operator Description Example
= Simple assignment a=b
+= Add and assign a += b
-= Subtract and assign a -= b
*= Multiply and assign a *= b
/= Divide and assign a /= b
%= Modulus and assign a %= b
&= Bitwise AND and assign a &= b
` =` Bitwise OR and assign
^= Bitwise XOR and assign a ^= b
<<= Left shift and assign a <<= 2
>>= Right shift and assign a >>= 2
Example:
int a = 10;
a += 5; // Equivalent to a = a + 5