0% found this document useful (0 votes)
10 views17 pages

C-Programming Short Notes Removed

The document provides an overview of C programming concepts, including format specifiers, data types, signed vs unsigned integers, and cyclic properties related to overflow. It also covers operators, control structures like if-else and loops, and the usage of printf and scanf functions. Key points include the behavior of bitwise operators, logical operators, and the importance of syntax in C programming.

Uploaded by

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

C-Programming Short Notes Removed

The document provides an overview of C programming concepts, including format specifiers, data types, signed vs unsigned integers, and cyclic properties related to overflow. It also covers operators, control structures like if-else and loops, and the usage of printf and scanf functions. Key points include the behavior of bitwise operators, logical operators, and the importance of syntax in C programming.

Uploaded by

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

C-PROGRAMMING

GATE फर्रे

Flow chart of the C program Format Specifier


Format Data Type Used For
Specifier

%d or %i int Signed integer

%u unsigned int Unsigned integer

%f float/double Decimal floating-point number

%c char Single character

%s char [] (string) Null-terminated string

Data Types %p void* Pointer address

%x int Unsigned hexadecimal (lowercase)

%o int Unsigned octal number

\n: use to give the break in the line.


\t: move the cursor to the next available frame in the line.

Signed vs Unsigned Cyclic Property


• Signed (default): Can store both positive and This property is observed when we try to store a value
negative numbers. −�𝟐𝟐𝒏𝒏−𝟏𝟏 �𝒕𝒕𝒕𝒕 𝟐𝟐𝒏𝒏−𝟏𝟏 − 𝟏𝟏 larger than the range of a given data type.
For example, a char (in signed form) has a range from
• Unsigned: Can store only positive numbers, but with
–128 to 127. If we try to assign a value like 129 to a
double the max range. 𝟎𝟎 𝒕𝒕𝒕𝒕 𝟐𝟐𝒏𝒏 − 𝟏𝟏
char, the compiler does not show an error. Instead, it
uses the cyclic (wrap-around) behaviour and stores a
corresponding value within the valid range.
This happens due to integer overflow, and the excess
value wraps around using modulo arithmetic based on
the size of the data type.

Page No:- 01
C-PROGRAMMING
GATE फर्रे

⚠ Note: This cyclic property does not apply to float


-
- 0 1 2 and double types.
3
These are floating-point numbers, and they are
stored in memory using the IEEE 754 format.
Because of this, overflow in floating-point types
behaves differently and does not wrap around.
Hence, avoid relying on cyclic behaviour for float or
- - 1 double.
1 1

When we try to store 129 in a char variable, it


causes an overflow because the value exceeds the Negative number will be stored in the 2’s
maximum limit of 127 (for signed char). complement from in the memory.
Since it goes beyond the range, it wraps around If the msb is 1 it means the number is -ve and it is
using the cyclic property. stored in the 2’s complement form.
Let’s understand it step-by-step: Range( 𝟐𝟐𝒏𝒏−𝟏𝟏 𝒕𝒕𝒕𝒕 𝟐𝟐𝒏𝒏−𝟏𝟏 − 𝟏𝟏 )
• If c = 128, it overflows by 1 step and wraps to -
128 = - (129 -1)
• If c = 129, it overflows by 2, so the stored value Operators
becomes -127 = -(129-2) Assignment operator (=)
• And so on...
This is not something you need to memorize —
left value = right value
just practice these kinds of questions more to
must be variable expression / constant
understand the behaviour intuitively. variable
• When value is +ve overflow then clockwise in the
circle The assignment operator = first assigns the value, then
• When the value is -ve overflow then move returns the assigned value.
anticlockwise in the circle. So if (a = 1) means:
• First, 1 is assigned to a
• Then, the expression returns 1, which is true, so
the if block runs
Char c Modulus (%)
(8bit)−𝟐𝟐𝟖𝟖−𝟏𝟏 𝒕𝒕𝒕𝒕 𝟐𝟐𝟖𝟖−𝟏𝟏 − 𝟏𝟏
Example:
Char c = 129;
Range =–128 to127 both operands must be int value types
Printf (“%d”, c);
a%b = remainder of a when divided by b.
This is 129, it is positive overflow. So, we need to Sign of the Result Follows Dividend (Left Operand)
move in the clockwise direction by 2 unit which is -
127.

5%3=2
-5 % 3 = -2
5 % -3 = 2
-5 % -3 = -2

Page No:- 02
C-PROGRAMMING
GATE फर्रे

Bitwise Operators Bitwise And, OR

Bitwise And (|)

Result bit is 1 only


if both bits are 1.
(5) 0101
(3) & 0011

= 0001

Logical AND (&&)


Bitwise OR (|)
Result bit is 1 if
(Expression 1 && expression 2) either of bits are 1.
Returns: (5) 0101
• true (1) if both conditions are true (3) & 0011
= 0111
• false (0) if either condition is false

It has the short circuiting, means if the first operand


Left Shift Operator (<<)
output is 0 or false then second expression will not be
evaluated. Syntax: x << n = x * (2𝑛𝑛 )
How It Works
Logical OR ( | | ) • Each bit shift to the left multiplies the
number by 2.

(Expression 1 || expression 2) • Zeros are added on the right side.


Returns:
• Leftmost bits are discarded if overflow
• false (0) if both conditions are false
occurs.
• true (1) if either condition is true

It has the short circuiting, means if the first operand


output is 1 or true then second expression will not be Use Cases
evaluated. Now we have the example: 1 << 3
• 1 = 0000 0001

• 1 << 3 → 0000 1000 = 8

Another method: 1*23 = 8.

Page No:- 03
C-PROGRAMMING
GATE फर्रे

Right Shift Operator (>>) Comma Operator (,)

Syntax: x >> n = x / (2𝑛𝑛 ) it evaluates from left to right and discard, final
Example: 8 >> 3 Another value is right most
• 8 in binary: 0000 1000 method:
• 8 >> 3 → 0000 0001 = 1 8 / 23 = 8 / 8 ex. int a= 9,8,7;
=1
is interpreted as:
int a = 9;
8;
Bitwise NOT Operator (~) 7;
// so the final value of a=5;
~5
Operates bit-by-bit. • 5 = 0000 0101
Converts each 1 to 0 and
• ~5 = 1111 ex. int a= (9,8,7);
each 0 to 1.
1010 = -6 (in we apply the associativity of comma
~x = -(x+1)
two's operator.
complement)
// so, the final value of a=9;

Logical Not (!) Increment (++) and Decrement (-)


Pre-Increment / Pre-Increment
The Logical NOT operator is denoted by(!)
Syntax: ++x, --x
• It is a unary operator (works on a single operand).
We do the increment or decrement first then will use
• It reverses the logical state of its operand. the value in the expression.
Ex. int x = 5;
int y = ++x; // x becomes 6, then y = 6

!0 = true
! true = false
Syntax: x++, x--, First use the value and then perform
the increment or decrement.
int x = 5;
int y = x++; // y = 5, then x becomes 6

Page No:- 04
C-PROGRAMMING
GATE फर्रे

Ternary Operator
Only else block can’t exist. if block is necessary
Syntax: ++x, --x for else.
We do the increment or decrement first then You cannot write else without if.
will use the value in the expression. else {
Ex. int x = 5; // statement;
int y = ++x; // x becomes 6, then y = 6 } // invalid, compiler give the error of wrong
syntax

sizeof
If( )
is a compile-time operator used to determine Statement; // expression is mandatory in the if block
the memory size (in bytes) of a data type or If(1) –> this is perfect statements
Note: In C, if you do not use curly braces {} after an if
variable.
statement, only the very next single statement is
Returns size_t type (an unsigned integer). considered part of the if block.
Evaluated at compile time (except in Variable
Length Arrays).
No function call — it's an operator, not a There should be no statement between
the if and else block.
function.
You must not insert any statements
between if and else.
if (exp) {
If and else statements // statement1;
}
// statement2;
Syntax: if(expression) else {
{statements} // statement3;
}
else {statements}
Result: Compilation error — "else
without if"
There is no compulsion of the else block after if.
This means you can use if without using
else.
if (exp) {
statement;
} // valid syntax, there is no requirement of
the else block

Page No:- 05
C-PROGRAMMING
GATE फर्रे

Pattern Valid? Explanation Loops


if (exp) yes Only if block, no else needed, For loops
{statement;} but expression is mandatory in if
block

If () statement; no Expression is missing


else no Must follow an if block
{statement;}

if (exp) no Statement between if and else


{statement;} breaks the pair
statement;
else
{statement;}

if (exp) yes Proper structure


{statement;}
else
{statement;}

Valid syntax: for (;


In a chain of if - else if - else if - else, only the first
for (exp1; exp2; exp3) { ;)
block whose condition is true will execute, even if
Statements; this is valid
other conditions are also true. }
int x = 15; for loop, will
if (x > 10)
printf ("Condition 1: x > 10\n"); Flow: exp1 → exp2? → statements → exp3
else if (x > 5) Expression inside the for loop are optional.
printf ("Condition 2: x > 5\n"); But 2 semicolons are compulsory.
else if (x > 0)
printf ("Condition 3: x > 0\n");
else
printf("Condition 4: x <= 0\n");
While

Valid syntax:
There is all the blocks condition are true. But we while(expression) {
check first condition which is if(x > 10) and it comes Statements;
}
true then we will not execute to the next level, even
expression is not optional it is mandatory.
if the next blocks like else if(x>5), else(x>0) are true.
When to use
• When number of iterations is not known in
advance

Page No:- 06
C-PROGRAMMING
GATE फर्रे

Do-while
• break is not a mandatory statement.
• The expression must evaluate to an integer, char, or
Enum (not float, double, or string).
it executes the loop body first, then checks the
• Each case must use a constant value (no variables or
condition
ranges allowed).
How It Works
• default is optional and executes when no cases match.
• Always runs once, even if the condition is
• The position of the default case doesn’t matter.
initially false. • continue cannot be used inside a switch statement.
• If there is any statement between two case labels, it is
• After executing, it checks the condition.
ignored (not executed) unless one of the cases above
• Continues if condition is true. falls through.
• switch is generally faster than if-else for fixed constant
Expression is mandatory not optional.
comparisons.
• If break is not used and one case matches, execution
will continue through all subsequent cases, including
default.
Continue: To skip the current iteration of a loop and go to
the next iteration, used in loops, but in switch it will give

break: To exit a loop or switch statement immediately,


skipping the remaining iterations or cases. Used in loops,

Switch Statement

switch (expression) {
case constant1:
// code
break;

default:
// code
}

Page No:- 07
C-PROGRAMMING
GATE फर्रे

PRIORITY OPERATORS Concept:


printf (“%d”, 1 || printf (“I’ll be rank 1”) && 0);
Operators Description Associativity In C:
• && has higher precedence than ||
(), [], . ,-> Function call, array Left to Right • So, the expression is grouped like this:
subscript, struct
1 || (printf("I'll be rank 1") && 0)
++, --, +, - Unary operators, type cast, Right to Left But when we see the short-circuiting, (printf ("I'll
, !, ~, *, &, dereference
(type),
be rank 1") && 0) will not execute.
sizeof () Output: 1.
*, /, % Multiplication, division,
modulus
print in C
+, - Addition, subtraction
• printf () is defined in the <stdio.h> header file.
<<, >> Bitwise shift left/right
• It returns the number of characters it prints.
< <=, > Relational operators Left to Right • If an error occurs, it returns a negative number
>=
(usually -1).
==, != Equality operators
• Format specifiers like %s (for strings), %d (for
& Bitwise AND integers), etc., are used to control what and
how values are printed.
^ Bitwise XOR
printf ("%s %d", "I'm the rank", 1);
output: I'm the rank 1
| Bitwise OR
Always ensure that the number and type of
format specifiers match the values you pass to
&& Logical AND
printf (). Mismatches can lead to undefined
|| Logical OR behaviour or runtime errors.

?: Ternary conditional Right to Left

= Assignment operators

, Comma (sequential Left to Right


evaluation)

Page No:- 08
C-PROGRAMMING
GATE फर्रे

Scanf in C
Syntax
• scanf () is defined in the <stdio.h> header file. return_type function_name(parameter_list) {
// body of function
• It is used to read input from the user.
}
• scanf () returns the number of input items
successfully assigned.
Prototype: A function prototype declares a
• If the input fails (like wrong format or EOF), function's name, return type, and parameters to
it returns 0 or EOF (-1). the compiler before its definition, enabling type
• Format specifiers like %d, %f, %c, %s is used checking and early function calls.
to specify the type of input expected. int add (int, int); // Function prototype
Note:
• Address-of operator & is used to pass the
• If you do not specify a return type, the
memory address of variables (except for default return type is considered as int.
strings). • If the definition or call mismatches the
• Do not use & with strings (character arrays), as prototype, the compiler throws an error.
the array name already represents the address.

Definition: it contains the code what the function


does.
Functions int add (int a, int b) // Function definition
A function is a block of code that performs a specific { ….. contains what the function does}
task. It promotes code reusability and modular Things to Include in Function Definition:
programming. 1. Return Type – What type of value the
function returns (int, float, void, etc.)
2. Function Name – The name you’ll use to
call the function
3. Parameter List – Input values the function
receives (can be empty)
4. Function Body – The block of code that
performs the task

5. Return Statement – (if not void) To send the


result back to the caller

Page No:- 09
C-PROGRAMMING
GATE फर्रे

Function calling: function_name (arguments);

Storage classes define the scope, lifetime, visibility,


and memory location of variables.

auto
• Default for local variables.
Call by Value • Scope: Inside block/function.
• Lifetime: Till the block ends.
Formal arguments are the parameters listed in the
auto int a = 10; // usually just written as int a = 10;
function definition. When a function is called, copies
of actual values are passed to them.

register
Changes made to formal arguments do not affect
1. Stored in CPU registers (if available) for faster
actual arguments.
access.
This is the default behaviour in C.
2. Cannot get the address using & register int
Separate memory is allocated for the formal
counter;
parameters.
register int counter;

Referenced Parameter Passing


static
In this method, instead of sending a copy, we send the
• Retains value between function calls.
address of the variable to the function using
• Scope: Local to block in which it is
pointers. This allows the function to modify the
declared.
original value.
• Lifetime: Entire program.
Any change made inside the function affects the
Static int count = 0;
original variable.
This is done using pointers in C.
Both actual and formal parameters point to the
same memory.

Page No:- 10
C-PROGRAMMING
GATE फर्रे

Storage Scope Lifetime Stored In Keyword Default


extern Initial Value

● Declares a variable defined in another file. auto Block Till Stack auto Garbage
(local) block (default) value
● Used for global sharing. ends (undefined)
extern int x; // Defined elsewhere
register Block Till CPU register Garbage
• If a variable is used before it is defined, (local) block Register value
ends (if (undefined)
you can declare it using extern. available)
• If a variable is used before it is defined, static Block / Entire Data static 0 (zero)

you can declare it using extern. File program Segment

extern Global Entire Data extern 0 (if defined


(across program Segment globally
files) without
initialization)

extern int count; global Global Entire Data — 0


int main () { (no (entire program Segment
keyword) program)
printf ("%d",
count);
return 0;
}
int count = 5; //
Defined later

1. You cannot initialize an extern variable


during declaration.
extern int x = 10; // Error

Page No:- 11
C-PROGRAMMING
GATE फर्रे

Array a[i] = *(a + i) = *(i + a) = i[a]


But remember: this is valid only for access, not for
• Array name represents the address of its first declaration.
element. i[a] is not valid during declaration — it will result in an
int arr [5]; error.
printf ("%p", arr); // Prints address of arr [0]); Also, expressions like:
arr means &arr[0] a++, a--, --a, ++a are invalid if a is an array, because
• Array name is constant, so it can’t be the left array names cannot be used as left-hand values.
value.
arr = value; → Invalid
• Array size must be a constant or fixed expression
Pointers
• Pointers are variables that store the address of
(at compile time). another variable or item.
int arr[10]; valid
• You can also have pointers to pointers, and even
int size; int arr[size]; invalid more levels (multiple indirection).
• variable can’t be used as a size in the array.
• We dereference a pointer using the * operator.
If an array has n dimensions, and:
• You use all n dimensions → you're accessing an int variable; // Normal integer variable
element.
• You use fewer than n dimensions → you're int *ptr; // Declaration of a pointer to int
referring to an address (sub-array).
ptr = &variable; // Storing the address of variable in
int a [2][3]; pointer
a [1][2]; // Element
a [1]; // Address of &a[1][0] // Or in a single line:
a; // Address of &a[0][0]
int *ptr = &variable;
• Initialization at Declaration → Size is Optional (for
first dimension) It Means:
If you initialize the array during declaration, the first
• int *ptr; → Declares ptr as a pointer to int
dimension’s size can be omitted — the compiler
will count it automatically. & A i h dd f
int arr [] = {1, 2, 3}; // Size = 3 (automatically)
int arr [3] = {1, 2, 3}; // Also OK This the value
stored in the
• Multidimensional Arrays → Only First Dimension 2500
Can Be Omitted
In multi-dimensional arrays:
This is the
• You can omit the first dimension if initializing. address of the
• All other dimensions must be specified. variable x

pt 100

30

Page No:- 12
C-PROGRAMMING
GATE फर्रे

We cannot perform arbitrary pointer arithmetic malloc(), calloc(), realloc(), and free() are used with
between unrelated pointers, but pointer - pointer is pointers for dynamic memory.
valid when both pointers point to elements of the int *p = (int *)malloc(sizeof(int) * 5);
same array. free(p);
In this case, the result is the difference in element
positions, not in bytes, because the compiler
automatically divides the address difference by the Dynamic memory allocation
size of the data type.
int a[10]; malloc () – Memory Allocation
int *p = &a[7]; Definition:
int *q = &a[2];
malloc (memory allocation) is used to dynamically
int diff = p - q;
allocate a single block of memory of a specified size (in
difference = (address at p - address at q) / sizeof(int)
bytes). It does not initialize the memory—it contains
garbage values.
Types of Pointers

int *ptr = (int*) malloc (5 * sizeof(int));


Null Pointer

calloc () – Contiguous Allocation


Points to nothing. Used for safety.
calloc (contiguous allocation) allocates memory for an
int *p = NULL;
array of elements, initializes all bytes to zero.
void* calloc (size_t num_elements, size_t
Dangling Pointer
element_size);
Points to memory that has been freed or is out of
scope.
realloc () – Reallocation
Wild Pointer
is used to resize a previously allocated memory block
Uninitialized pointer that points to a random memory
(from malloc or calloc). The contents are preserved up
location.
to the minimum of the old and new sizes.
void* realloc (void* ptr, size_t new_size);
Void Pointer (Generic Pointer)
All three functions return NULL if memory allocation
Can point to any data type. Needs to be typecasted
fails.
before dereferencing.
Always free () the allocated memory when done, to
avoid memory leaks.
void *ptr;
int *const p = &x; → constant pointer (address can't
change).
const int *p = &x; → pointer to constant (value can't String Representation in C
change). Strings in C can be represented in two ways:
const int *const p = &x; → both value and address are 1. Using a character array
constant.
2. Using a pointer to a string literal
Pointer Arithmetic
int a[5] = {1,2,3,4,5};
int *p = a;
p++; // moves to next integer (adds sizeof(int))

Page No:- 13
C-PROGRAMMING
GATE फर्रे

Feature Array Pointer → Both print the same address.


Also:
Declaration char str [] char *str
if (a == b)
= "hello"; =
printf ("Same location\n");
"hello";
Output: Same location
Memory Stored in Stored
Read / write memory
Location read/write in read-
Strings stored using arrays, e.g., char str [] = "hello";
memory only
Stored in stack or heap, which is read/write memory
memory
Duplicates are allowed — each array creates a separate
Modifying Allowed Not
copy of the string
individual allowed
characters
Strings in C can be represented in two ways:
Reassigning the Not Allowed
3. Using a character array
whole string allowed
4. Using a pointer to a string literal
Array name used Cannot Pointer
as l-value be used is an l- Example:
as l-value value char a [] = "hello";
char b [] = "hello";
Summary of Key Points // a and b have different memory addresses

• Arrays allow changing individual characters,


e.g., str [0] = 'H';
• Pointers may point to string literals, which are
often read-only
• You cannot assign a new string to an array
like: str = "new"; → invalid
• But with pointers: str = "new"; → valid

Memory Behaviour for Strings in C

Read-Only Memory (String Literals)


• Strings stored using pointers, e.g., char *str =
"hello";
• Stored in read-only (constant) memory
• Duplicate strings are not created — if two
literals are the same, they share the same
memory location

char *a = "hello";
char *b = "hello";

Both a and b point to the same memory address.


So
printf ("%p\n", a);
printf ("%p\n", b);

Page No:- 14
C-PROGRAMMING
GATE फर्रे

Note: "hello" is a string literal, which means it • Positive or negative difference of ASCII
represents the address of the first character ('h') in values where mismatch occurs
memory.
printf ("%s", "hello" + 1); strcmp ("papu", "pake")
output: ello Compares: 'p' == 'p', 'a' == 'a', 'p' != 'k'
"hello" is a pointer to the first character ('h') 'p' - 'k' = 112 - 107 = 5
"hello" + 1 moves the pointer one character ahead
— to 'e'
Return value: 5
So printf starts printing from 'e'

Structure in C

string.h Functions in C A structure is a user-defined data type in C.


strlen It allows you to group different types of variables
Get Length of String under one name.
unsigned int strlen(const char *str); by default, structure contains the 0 or null values.
Useful for representing real-world entities (e.g.,
student, book,
employee, etc.).

Returns the number of characters in the string struct Name {


(excluding the '\0' null terminator). data_type member1;
The parameter is const because strlen does not modify data_type member2;
the string. ...
};
strcpy struct Student s1; // variable of type struct Student
char *strcpy (char *destination, const char *source);
Copies the string from source to destination including
'\0'.
source is const because it should not be changed.
destination must be a writable array or memory block,
i.e we should pass the array because the string will be
in the r/w area.

strcat
Appends src string to the end of dest string, removing
'\0' of dest and adding one at the end.

strcmp
Compares two strings character by character.
Returns:
• 0 if both strings are equal

Page No:- 15
C-PROGRAMMING
GATE फर्रे
Feature Explanation struct {
int roll;
User-defined Unlike int, char, etc., created char name[20];
by the programmer } s1, s2;
This is anonymous and we can’t create object of
it but can use the variable s1 and s2 which we
declared.
Holds multiple e.g., int, float, char [], all
data types together

Memory layout All members stored


contiguously in memory

Struct name is not Unlike arrays, structure


an address names are not pointers

Can contain Yes


nested structures

typedef struct Student {


int roll;
char name[50];
float marks;
} Student;

Student s1; // now no need to write 'struct' again

Page No:- 16
C-PROGRAMMING
GATE फर्रे

Dynamic Scoping
struct Student {
int roll_num = 9; // Invalid
Variable scope is decided at runtime.
char str [] = "Kunal"; // Invalid
The program searches the call stack to find the most
};
recent variable definition.
This is incorrect, because:
• A struct is only a blueprint, it does not
allocate memory until an object (variable) x=5
is created. foo() {
• In C, you cannot assign values to structure print(x);
members inside the definition. }
• Memory is only allocated when you bar() {
create an object like:
local x=10
struct Student s1;
foo # Output: 10 – because bar called foo, and
x=10 in bar
Structure definition is just a template. You can’t assign }
values inside it — you assign values only after creating
a variable.
we access structure members using either the dot (.)
operator or the arrow (->) operator
Union in C
A union is a special data type in C that allows storing
different types of data in the same memory location.
union Data {
int i;
float f;
char str[20];
};
All members share the same memory, and the size of
the union is equal to the size of its largest member.

Scoping
• Scoping defines where a variable can be
accessed in a program (its visibility or lifetime).
Static scoping
Variable scope is decided at compile time.
Local to the block will be preferred.

int x = 10;
void func () {
int x = 20;
printf ("%d", x); // Output: 20 (local x used)
}

Page No:- 17

You might also like