0% found this document useful (0 votes)
9 views33 pages

C Programming Notes 2

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views33 pages

C Programming Notes 2

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 33

C PROGRAMMING

A data type is an attribute that specifies the kind of data a variable


can hold, determining its possible values, the operations that can be
performed on it, and its memory requirements.
Data types, such as
 integers (whole numbers),
 strings (text), and
 booleans (true/false),
are fundamental in computer science and programming for correctly
interpreting, processing, and storing data, preventing errors, and
optimizing performance.
Data types in C classify the type of values a variable can hold
and determine the operations that can be performed on them.
They are broadly categorized into three main types:
 Primary (or Basic) Data Types:
These are the fundamental building blocks.
 int: Stores whole numbers (integers),
e.g., 5, -100. Can be modified with short, long, signed,
and unsigned.
 char: Stores single characters,
e.g., 'a', '7', '$'. Can be signed or unsigned.
 float: Stores single-precision floating-point numbers
(numbers with decimal points),
e.g., 3.14, -0.5.
 double: Stores double-precision floating-point numbers,
offering greater precision than float.
 void: A special type indicating the absence of a value,
often used as a function return type or for generic
pointers.
Derived Data Types:
These are built upon the primary data types.
 Arrays: Collections of elements of the same data type,
accessed by an index,
 An array is a collection of elements of the same data type
stored in contiguous memory locations.

e.g., int numbers[5].

 Pointers: A pointer is a variable that stores the memory


address of another variable.
 Functions: Blocks of code designed to perform a specific
task, which can also be considered a type in C.
 A function pointer is a pointer that stores the memory
address of a function. This allows functions to be passed
as arguments to other functions, stored in data structures,
or invoked dynamically.
1.Arrays and Pointers:
int numbers[] = {10, 20, 30};
int *ptr = numbers; // ptr points to the first element of
numbers
printf("First element using array index: %d\n",
numbers[0]);
printf("First element using pointer: %d\n", *ptr);
printf("Second element using pointer arithmetic: %d\n",
*(ptr + 1));
2. Arrays and Functions
void printArray(int *arr, int size) {
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}

int main() {
int myArr[] = {1, 2, 3, 4, 5};
printArray(myArr, 5); // Pass the array (as a pointer) and
its size
return 0;
}
3. Function Pointers:
int add(int a, int b) {
return a + b;
}

int subtract(int a, int b) {


return a - b;
}

int main() {
int (*operation)(int, int); // Declare a function pointer

operation = add; // Assign the address of the add


function
printf("Addition: %d\n", operation(10, 5));

operation = subtract; // Assign the address of the


subtract function
printf("Subtraction: %d\n", operation(10, 5));
return 0;
}

User-Defined Data Types:


 These are created by the programmer to define custom
data structures.
 Structures (struct): Allow grouping of different data types
under a single name, creating complex data structures.
 Unions (union): Similar to structures but allow different
members to share the same memory location.
 Enumerations (enum): Define a set of named integer
constants, improving code readability.
Understanding these data types is crucial for effective
programming in C, as they dictate how data is stored,
manipulated, and interpreted by the compiler.
struct Student {
char name[50];
int roll_number;
float marks;
};

******
#include <stdio.h>
int main() {
// Declare and initialize variables
int integerVar = 10;
char charVar = 'A';
float floatVar = 3.14f; // 'f' suffix indicates a float literal
double doubleVar = 1.23456789;

// Print the values


printf("Integer variable: %d\n", integerVar);
printf("Character variable: %c\n", charVar);
printf("Float variable: %f\n", floatVar);
printf("Double variable: %lf\n", doubleVar); // Use %lf for double

return 0;
}
*#include <stdio.h>
int main() {
printf("Size of int: %zu bytes\n", sizeof(int));
printf("Size of char: %zu byte\n", sizeof(char));
printf("Size of float: %zu bytes\n", sizeof(float));
printf("Size of double: %zu bytes\n", sizeof(double));

return 0;
}
*#include <stdio.h>
In main() {
int num;
char grade;
float price;
double amount;

printf("Enter an integer: ");


scanf("%d", &num);
printf("Enter a character: ");
scanf(" %c", &grade); // Space before %c to consume leftover
newline

printf("Enter a float price: ");


scanf("%f", &price);

printf("Enter a double amount: ");


scanf("%lf", &amount); // Use %lf for double input

printf("\nYou entered:\n");
printf("Integer: %d\n", num);
printf("Character: %c\n", grade);
printf("Price: %.2f\n", price); // .2f for 2 decimal places
printf("Amount: %.4lf\n", amount); // .4lf for 4 decimal places

return 0;
}
Type modifiers
These keywords can be used to alter the storage size and range of
basic integer and floating-point types.
Integer modifiers
 signed and unsigned: Control whether an integer can hold both
positive and negative values (signed) or only positive values and
zero (unsigned). By default, int is signed.
 short and long: Adjust the amount of memory allocated for an
integer.
o short int: Can store small integer values and often uses
less memory than int.
o long int: Can store larger integer values than int.
o long long int: Can store even larger integer values
than long int.
 Floating-point modifier
long double: Provides even greater precision than double.
operators in c
Operators in C are symbols that instruct the compiler to
perform specific operations on variables and data, known as
operands.
They are fundamental to manipulating data, performing
calculations, making decisions, and controlling program flow.

Here are the main categories of operators in C:


1.Arithmetic Operators:
Used for basic mathematical calculations. + (Addition), -
(Subtraction), * (Multiplication), / (Division), and % (Modulo -
remainder after division).
#include <stdio.h>
int main() {
int a = 20, b = 5, result;
result = a + b; // Addition
printf("a + b = %d\n", result);
result = a - b; // Subtraction
printf("a - b = %d\n", result);
result = a * b; //
}
Multiplication
printf("a * b = %d\n", result);
result = a / b; // Division
printf("a / b = %d\n", resul t);
result = a % b; // Modulo (remainder)
printf("a %% b = %d\n", result); // Use to print the % character
return 0;
2. Relational Operators:
Used to compare two operands and return a boolean result
(true or false).
 == (Equal to)
 != (Not equal to)
 > (Greater than)
 < (Less than)
 >= (Greater than or equal to)
 <= (Less than or equal to)
 #include <stdio.h>

 int main() {
 int a = 10, b = 20;

 printf("a > b: %d\n", a > b); //
Greater than
 printf("a < b: %d\n", a < b); // Less
than
 printf("a >= b: %d\n", a >= b); //
Greater than or equal to
 printf("a <= b: %d\n", a <= b); // Less
than or equal to
 printf("a == b: %d\n", a == b); //
Equal to
 printf("a != b: %d\n", a != b); // Not
equal to

 return 0;
 }
3. Logical Operators:
Used to combine or negate conditional expressions.
 && (Logical AND)
 || (Logical OR)
 ! (Logical NOT)
 #include <stdio.h>

 int main() {
 int a = 1, b = 0, c = 1;

 // Logical AND (&&): True if both
operands are true
 printf("(a && c): %d\n", a && c);

 // Logical OR (||): True if at least
one operand is true
 printf("(a || b): %d\n", a || b);

 // Logical NOT (!): Reverses the
logical state
 printf("!b: %d\n", !b);

 return 0;
 }
Bitwise operators
These operators perform operations on individual bits of an
integer.
c
#include <stdio.h>
int main() {
int a = 60; // 60 = 0011 1100 in binary
int b = 13; // 13 = 0000 1101 in binary
int result = 0;
result = a & b; // Bitwise AND -> 0000 1100
printf("a & b = %d\n", result
result = a | b; // Bitwise OR -> 0011 1101
printf("a | b = %d\n", result);
result = a ^ b; // Bitwise XOR -> 0011 0001
printf("a ^ b = %d\n", result);
result = ~a; // Bitwise NOT (complement)
printf("~a = %d\n", result);
result = a << 2; // Left shift
printf("a << 2 = %d\n", result);
result = a >> 2; // Right shift
printf("a >> 2 = %d\n", result);
return 0;
}

Assignment operators
Assignment operators are used to assign a value to a variable.
The compound assignment operators combine an arithmetic or
bitwise operation with an assignment.
c
#include <stdio.h>

int main() {
int a = 10, b = 5;
// Simple assignment
int c = a;
printf("c = a: %d\n", c);
// Add and assign (c = c + b)
c += b;
printf("c += b: %d\n", c);
// Subtract and assign (c = c - b)
c -= b;
printf("c -= b: %d\n", c);
// Multiply and assign (c = c * b)
c *= b;
printf("c *= b: %d\n", c);
// Divide and assign (c = c / b)
c /= b;
printf("c /= b: %d\n", c);
return 0;
}

Increment and decrement operators


These are unary operators that increase or decrease the value
of a variable by one.
c
#include <stdio.h>
int main() {
int a = 5;
int result_pre, result_post;
// Pre-increment: increments the value before using it
result_pre = ++a;
printf("Pre-increment: ++a -> result: %d, a: %d\n", result_pre,
a);
// Reset a
a = 5;
// Post-increment: uses the value, then increments it
result_post = a++;
printf("Post-increment: a++ -> result: %d, a: %d\n",
result_post, a);
// Reset a
a = 5;
// Pre-decrement: decrements the value before using it
result_pre = --a;
printf("Pre-decrement: --a -> result: %d, a: %d\n", result_pre,
a);
// Reset a
a = 5;
// Post-decrement: uses the value, then decrements it
result_post = a--;
printf("Post-decrement: a-- -> result: %d, a: %d\n",
result_post, a);
return 0;
}

Conditional (ternary) operator


This is a shorthand for an if-else statement and is the only
ternary operator in C.
c
#include <stdio.h>

int main() {
int age = 20;
char eligibility[20];

// condition ? expression_if_true : expression_if_false


age >= 18 ? strcpy(eligibility, "Eligible to vote") :
strcpy(eligibility, "Not eligible to vote");

printf("%s\n", eligibility);

return 0;
}
sizeof() operator
The sizeof() operator is a unary operator that returns the size of
a data type or variable in bytes.
c
#include <stdio.h>
int main() {
int my_int;
double my_double;
char my_char;
printf("Size of int: %zu bytes\n", sizeof(my_int));
printf("Size of double: %zu bytes\n", sizeof(my_double));
printf("Size of char: %zu bytes\n", sizeof(my_char))
return 0;
}

4. Assignment Operators:
Used to assign values to variables.
 = (Simple assignment)
 +=, -=, *=, /=, %= (Compound assignment operators)
5. Increment/Decrement Operators:
Used to increase or decrease the value of a variable by 1. ++
(Increment) and -- (Decrement).
6. Bitwise Operators:
Used to perform operations on individual bits of an integer.
& (Bitwise AND), | (Bitwise OR), ^ (Bitwise XOR), ~ (Bitwise
NOT), << (Left shift), and >> (Right shift).
7. Conditional (Ternary) Operator:
A shorthand for an if-else statement.
 condition ? expression1 : expression2;
8. Special Operators:
sizeof (Returns the size of a variable or data type)
 & (Address-of operator)
 * (Pointer dereference operator)
 , (Comma operator)
What are the 4 types of logical operators?

The logical Boolean operators perform logical operations


with bool operands. The operators include the
unary logical negation ( ! ), binary logical AND ( & ), OR
( | ), and exclusive OR ( ^ ), and the binary conditional
logical AND ( && ) and OR ( || ).

expressions in c

In C programming, an expression is a combination of operators,


operands, and sometimes function calls, that evaluates to a
single value. Essentially, it's a piece of code that computes a
result.
Key characteristics of C expressions:
 Operators: Symbols that perform operations
(e.g., +, -, *, /, %, ==, &&, ||, ++, --).
 Operands: The values or variables on which the operators act
(e.g., 5, x, (a + b)).
 Evaluation: Every expression in C evaluates to a value.
 This value can be assigned to a variable, used in another
expression, or passed as an argument to a function.
 No Semicolon: An expression by itself does not end with a
semicolon.
 When an expression is followed by a semicolon, it becomes an
expression statement.

Types of Expressions in C:

 Arithmetic Expressions: Perform mathematical calculations.


int sum = a + b;
float product = x * 3.14;
Relational Expressions: Compare two operands and evaluate
to a boolean value (true or false, represented as 1 or 0 in C).
int is_equal = (a == b);
int is_greater = (x > y);
 Logical Expressions: Combine relational expressions using
logical operators (&& - AND, || - OR, ! - NOT).
int condition = (age > 18 && has_license);
 Assignment Expressions: Assign a value to a variable
int x = 10;
y = x + 5;
 Conditional (Ternary) Expressions: A concise way to express
an if-else condition.
int max = (a > b) ? a : b; // If a > b, max = a, else max = b
 Increment/Decrement Expressions: Modify the value of a
variable by 1.
x++; // Post-increment
--y; // Pre-decrement
 Pointer Expressions: Involve operations on memory addresses
using pointers.
int *ptr = &my_var;
int value = *ptr;
Expression Evaluation:
Expressions are evaluated based on operator precedence (which
operators are evaluated first) and associativity (how operators of the
same precedence are grouped). Parentheses () can be used to
override default precedence.

control structure in c
Control structures in C programming manage the flow of program
execution, enabling decision-making, repetition, and conditional
execution of code blocks. They are categorized into three main types:
1. Decision-Making (Selection) Statements:
These statements allow the program to choose which block of code
to execute based on a condition.
 if statement: Executes a block of code only if a specified
condition is true.
if (condition) {
// code to be executed if condition is true
}
 if-else statement: Executes one block of code if the condition is
true, and another block if the condition is false.
if (condition) {
// code if condition is true
} else {
// code if condition is false
}
 switch statement: Allows for multi-way branching, executing
different blocks of code based on the value of an expression.
switch (expression) {
case value1:
// code for value1
break;
case value2:
// code for value2
break;
default:
// code if no match
}
**
#include <stdio.h>
int main() {
int num;
printf("Enter an integer: ");
scanf("%d", &num);
if (num > 0) {
printf("%d is positive.\n", num);
} else {
printf("%d is negative or zero.\n", num);
}
return 0;
}
**
switch statement.
This program prints the day of the week based on an integer input.
#include <stdio.h>

int main() {
int day;
printf("Enter a number (1-7) for the day of the week: ");
scanf("%d", &day);
switch (day) {
case 1:
printf("Monday\n");
break;
case 2:
printf("Tuesday\n");
break;
case 3:
printf("Wednesday\n");
break;
case 4:
printf("Thursday\n");
break;
case 5:
printf("Friday\n");
break;
case 6:
printf("Saturday\n");
break;
case 7:
printf("Sunday\n");
break;
default:
printf("Invalid day.\n");
}
return 0;
}
2. Iteration (Looping) Statements:
These statements allow a block of code to be executed repeatedly.
 for loop: Executes a block of code a specific number of times.
for (initialization; condition; increment/decrement) {
// code to be executed repeatedly
}
 while loop: Executes a block of code as long as a specified
condition remains true.
while (condition) {
// code to be executed repeatedly
}
 do-while loop: Executes a block of code at least once, and then
repeatedly as long as a specified condition remains true.
do {
// code to be executed at least once
} while (condition);
**

#include <stdio.h>
int main() {
int i;
for (i = 1; i <= 5; i++) {
printf("%d ", i);
}
printf("\n");
return 0;
}
while loop.
This program calculates the sum of numbers from 1 to 5 using
a while loop.
#include <stdio.h>

int main() {
int i = 1, sum = 0;
while (i <= 5) {
sum += i;
i++;
}
printf("Sum of numbers from 1 to 5: %d\n", sum);
return 0;
}
do-while loop.
This program prompts the user to enter a positive number, ensuring
at least one input using a do-while loop.
#include <stdio.h>
int main() {
int num;
do {
printf("Enter a positive number: ");
scanf("%d", &num);
} while (num <= 0);
printf("You entered: %d\n", num);
return 0;
}

3. Jump Statements:
These statements alter the normal sequential flow of execution
within a loop or function.
 break statement:
Terminates the current loop (or switch statement) and transfers
control to the statement immediately following the loop/switch.
 continue statement:
Skips the rest of the current iteration of a loop and proceeds to the
next iteration.
 goto statement:
Transfers control unconditionally to a labeled statement within the
same function. Its use is generally discouraged due to potential for
creating unstructured and hard-to-read code.
break Statement.
This program demonstrates break to exit a loop early when a specific
condition is met.
#include <stdio.h>

int main() {
int i;
for (i = 1; i <= 10; i++) {
if (i == 5) {
break; // Exit the loop when i is 5
}
printf("%d ", i);
}
printf("\n");
return 0;
}
continue statement.
This program demonstrates continue to skip the current iteration of a
loop.
#include <stdio.h>

int main() {
int i;
for (i = 1; i <= 5; i++) {
if (i == 3) {
continue; // Skip printing when i is 3
}
printf("%d ", i);
}
printf("\n");
return 0;
}
Skip some lines Jump statements in C are used to change the normal
flow of a program —
they make the program jump from one part to another.
Normally, statements run line by line, but jump statements can:
Exit from loops
Or return control from a function
Jump statements in C are control flow statements that alter the
normal sequential execution of a program by transferring control
to a different part of the code. The main jump statements in C are:
break statement:
Used to terminate the execution of the innermost switch statement
or loop (e.g., for, while, do-while) in which it is encountered.
Control is immediately transferred to the statement following the
terminated switch or loop block.
Example: Exiting a loop early when a specific condition is
met.continue statement:
continue statement:
Used within loops to skip the remaining statements in the current
iteration and proceed directly to the next iteration of the loop.
Example: Skipping the processing of certain values within a loop
based on a condition.
goto statement:
Provides an unconditional jump to a labeled statement within the
same function.
Syntax: goto label; and label: statement;

While it offers flexibility, its use is generally discouraged as it can lead


to complex and difficult-to-read "spaghetti code.
Example: Jumping to an error handling routine in older C code,
though modern C practices often use functions or structured control
flow for such scenarios.
return statement:
Used to terminate the execution of a function and return control to
the calling function.
Can optionally return a value to the caller.
Syntax: return; (for void functions) or return expression; (for
functions returning a value).
Example: Ending a function's execution and providing a result.

(or)(or)
Jump statements in C alter the normal flow of program execution by
transferring control to a different part of the code.
These statements are primarily used to exit or skip specific blocks of
code, such as loops and functions.
The four main jump statements in C are:
 break
 continue
 goto
 return

Explanation:
 continue When i == 3, the loop skipped printing 3.
 break When i == 5, loop ended immediately.
 goto Control jumped directly to the label jump:.
 return Sent the value 30 from the addNumbers() function to
main() and then exited the program.

⚙️Key Points

break and continue work only inside loops or switch.


goto can jump anywhere inside the same function.
return ends a function and optionally gives back a value.⚙️

Types of Jump Statements in C


| No. | Statement | Purpose |
| --- | ---------- | -------------------------------------------------- |
| 1️⃣ | `break` | Exit from loop or switch immediately |
| 2️⃣ | `continue` | Skip the rest of the current iteration of a loop |
| 3️⃣ | `goto` | Jump to a labeled part of the program |
| 4️⃣ | `return` | Exit from a function and optionally return a value |
1️-break Statement
Definition

Used to exit early from a loop or switch statement.

break;
} Example
#include <stdio.h>
int main() {
for(int i = 1; i <= 5; i++) {
if (i == 3)
break; // stop loop when i = 3
printf("%d ", i);
}
return 0;

🧠 Explanation:

When i == 3, the break statement ends the loop immediately.


🔹 2️⃣ continue Statement
Definition:

Used to skip the current iteration of a loop and go to the next


iteration.

continue;
Example
#include <stdio.h>
int main() {
for(int i = 1; i <= 5; i++) {
if (i == 3)
continue; // skip printing 3
printf("%d ", i);
}
return 0;
}

i == 3, continue skips the print statement and moves to the next


When loop iteration.
goto Statement

🧩 Definition:

Used to jump directly to a labeled part of the program.


⚠️Not recommended for modern programs (makes code confusing),
but important for learning

Syntax:

goto label;
// some code
label:
// code to jump to
#include <stdio.h>
int main() {
int n = 3;
if (n == 3)
goto jump;
printf("This will be skipped\n");
jump:
printf("You jumped here!\n"); return 0;}
Explanation:
When condition is true, control jumps directly to the label jump:.

🔹 4️⃣ return Statement

Definition:
Used to exit a function and optionally a value return to the calling
function.

📘 Syntax:

return value;
#include <stdio.h>
int add(int a, int b) {
return a + b; // return the sum to main()
}
int main() {
int result = add(5, 10);
printf("Sum = %d", result);
return 0; // end of main function
}

return sends the sum of two numbers back to the main function.

Common Use
Statement Meaning
break Exit from loop or switch Stop loop early
continue Skip current loop step Skip unwanted iteration
goto Jump to labeled code Rarely used
return Exit from function Send result or stop function

You might also like