0% found this document useful (0 votes)
30 views45 pages

Code of Important Exam

The document discusses various C programming concepts including: 1. Header files can be included using <> which searches in standard directories or "" which searches in the current directory. 2. Preprocessor directives like #define, #include, #undef, #ifdef and #ifndef are described. 3. The main aspects of C operators, data types, control statements like if-else and switch case, loops like for, while and do-while are covered. 4. Storage classes in C like auto, register, static, and extern and their usage is explained. 5. Functions in C including declaration, definition, parameters, return types and calling functions are discussed.

Uploaded by

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

Code of Important Exam

The document discusses various C programming concepts including: 1. Header files can be included using <> which searches in standard directories or "" which searches in the current directory. 2. Preprocessor directives like #define, #include, #undef, #ifdef and #ifndef are described. 3. The main aspects of C operators, data types, control statements like if-else and switch case, loops like for, while and do-while are covered. 4. Storage classes in C like auto, register, static, and extern and their usage is explained. 5. Functions in C including declaration, definition, parameters, return types and calling functions are discussed.

Uploaded by

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

c programmig

************

1. how many ways we can include a header file


1. <>
2. ""
Ex:
#include <stdio.h> //The compiler will search for this file in special directories
(software installed path)
#include "stdio.h" //The compiler will search for this file in current folder, if
not found then search in special directories

List of Preprocessor Directives


#define: It substitutes a preprocessor using macro.
#include: It helps to insert a certain header from another file.
#undef: It undefines a certain preprocessor macro.
#ifdef: It returns true if a certain macro is defined.
#ifndef: It returns true if a certain macro is not defined.

2. What is a header file


It is also called libraries provided by compiler
stdio.h -> printf,scanf,FILE,....
conio.h -> getch()
stdlib.h -> malloc,calloc,realloc,free,....
string.h -> strcpy,strlen,strrev,strtok,strcat,...
math.h -> Mathematical related functions

3. C program execution starts from ?


main
4. What is the syntax of main function
int main()
int main(int argc,char *argv[])
5. what is the use of return 0 in main function
return 0; //informing the compiler that the program executed successfully

************
day-2

Types of operators in C language:


1. Arithmetic operators
2. relational operators
3. logical operators
4. bit-wise operators
5. increment and decrement operator
6. conditional operator
7. assignment operators
8. Hierarchy of operators

1. Arithmetic operators
+
-
*
/
%
2. relational operators
>
>=
<
<=
==
!= (not equal to)
3. logical operators
&& (logical and)
|| (logical or)
! (logical not)
4.bit-wise operator:
| (bitwise or)
& (bitwise and)
^ (bitwise xor)
>> (right shift)
<< (left shift)
5. increment and decrement operator
i=i+1
i++ (post increment)
++i (pre increment)
i-- (post decrement)
--i (pre decrement)
6.conditional operator (?)
exp1 ? exp 2: exp 3
a>b ? printf("a is big") : printf("b is big")
7.assignment operators
a=a+b
a+=b; (a=a+b)
a-=b; (a=a-b)
a*=b; (a=a*b)
a%=b; (a=a%b)

8. Hierarchy of operators (BODMAS)


*
/
%
+
-

5. Program to find greatest of three numbers


6. C Program to check if number is odd or even
7. C Program to find out the ASCII value of a character
8. C Program to find the size of int, float, double and char
9. C Program to check whether an alphabet is vowel or consonant

Control Statements:
-> if condition
-> switch case

if condition:
-> simple if
-> if ...else
-> nested if
-> Simple if:
if (i==10)
{
printf("I value is 10");
}
-> if ..else:
if (i==10)
{
printf("I value is 10");
}
else
{
printf(" I value is not 10");
}
-> nested if
if (i<10)
{
if (i>5)
{
printf("I is greater than 5");
}
else
{
printf("I is not grear than 5");
}
}
else
{
printf("I value is grear than 10);
}

10. Write a C program explaining the use of relational operators


11. Write a C program explaining the use of:
-> simple if
-> if ...else
-> nested if

switch:

switch case
syntax:
switch (expr)
{
case 1:
break;
case 2:
break;
case 3:
break;
default:

nested switch:

int main()
{
int i,j;
printf("\n Enter the value of i,j");
scanf("%d%d",&i,&j);
switch(i)
{
case 1:
switch (j)
{
case 1:
printf("I am in inside switch case 1");
break;
case 2:
printf("I am in inside switch case 2");
break;
default:
printf("I am in default case");
break;
}
break;
case 2:
break;
default:
printf("Default");
}
return 0;
}

14.Write a C program to explain the use of switch case also


also explain the use of break
15. Write a C program to explain the use of switch case using a character also

loops:
repetetion of a logic
1. initial value
2. condition
3. increment/decrement (i=i+1)
ex:
print the values from 1 to 100
1,2,3,4,5
2,4,6,8,10,.....50
initial value: 2
condition : 50
increment : i=i+2
for
while
do ...while
1. for loop
for(initial value;condition;increment/decrement)
{
}
print the values from 1 to 100
for(i=1;i<100;i=i+1)
{
printf("\n %d",i);
}

Syntax 1. for loop


for(initial value;condition;increment/decrement)
{
}
print the values from 1 to 100
for(i=1;i<100;i=i+1)
{
printf("\n %d",i);
}
Syntax 2:
initial value
for(;condition;increment/decrement)
{
}

Syntax 3:

for(initial value;condition;)
{
increment/decrement;
}

Syntax 4:
initial value;
for(;condition;)
{
increment/decrement;
}

the loop will be executing infinite times (no limit), it will be keep on executing

While:
initial value
condition
increment/decrement

Syntax:
initial value;
while(condition)
{
increment;
}
========
do -- while
initial value;
condition
increment/decrement;

syntax
do
{
i=i+1;
}
while(condition);

control statements:
1. if conditions,
2. switch case
3. break; -> it will cut the loop execution
4. continue; -> it will skip the execution of the loop
5. goto

17.Write a C program to do following activities:


18. print the numbers from 100 to 200
19. print the numbers from 100 to 50
20. print the even numbers from 2 to 100
21. print the multiples of 5 from 40 to 80
22. print the multiples of 8 from 80 to 160
23. to show the different ways of using for loop syntax.
24.Write a C program to do following activities using while loop:
-> print the numbers from 100 to 200
-> print the numbers from 100 to 50
-> print the even numbers from 2 to 100
-> print the multiples of 5 from 40 to 80
-> print the multiples of 8 from 80 to 160

25. Write a C program to do following activities using do ..while loop:


-> print the numbers from 100 to 200
-> print the numbers from 100 to 50
-> print the even numbers from 2 to 100

There are 4 storage classes in C language:


1. auto
2. static
3. extern
4. register

1. auto:
By default all the variables are auto.
-> life time (with in a block/function)
-> what is the default value (garbage)
-> what is the scope (with in the block/function)
-> when it will die (once you come out of the block/function

6. Write a C program explaining the use of Auto Storage Class

2. Register:
We are telling the compiler that store this variable in CPU register memory.
Frequently used varibales should be store in CPU Register.
Syntax:
register int i;
-> life time (with in a block/function)
-> what is the default value (garbage)
-> what is the scope (with in the block/function)
-> when it will die (once you come out of the block/function

7. Write a C program explaining the use of register Storage Class

3.Static:
it will store the previous value.

-> life time (with in a program)


-> what is the default value (0)
-> what is the scope (with in the block/function)
-> when it will die (once you come out of the program)

The static keyword in c is used to specify that a variable or a function has static
storage duration.
A variable declared as static inside a function retains its value even after the
function has returned,
which means the variable remains in memory throughout the life of the program
Static variables are initialized only once. The compiler persists with the variable
till the end of the program.
The static variables are alive till the execution of the program.

A static function in C is a function that has a scope that is limited to its object
file.
This means that the static function is only visible in its object file.

int main()
{
static int i=1;
if(i>5)
{
exit(0);
}
else
{
printf("\n The value is %d",i);
i=i+1;
main();
}
return 0;
}

void display()
{
static int i=1;
printf("
The i value is %d",i);
i=i+1;
}
int main()
{

display();
display();
display();
return 0;
}

6. Write a C program explaining the use of Auto Storage Class


7. Write a C program explaining the use of register Storage Class
8. Write a C program explaining the use of static Storage Class

Write a C program explaining the use of extern Storage Class

Extern:

Step 1:
open a project - console application -> main.c
Step 2:
right click on the project -> add files -> right click on main.c -> paste ->
renamed the file (file1.c)
-> the file file1.c will be added to your project
-> double click on the file1.c file
-> remove every thing, and add
int i=100;
void display()
{
printf("\n I am in display function");
}
-> save the file
Step 3:
-> open main.c file
-> extern i;
extern display();
-> in the main function
printf("\n The value of i is %d",i);
display();

Functions:
Piece of code, which can be used many times,
reusable code.
syntax:
returntype functioname(parameters)
ex:
int addition();
int addition(int i,int j);
void display();

-> declaration of a function


-> definition of a function

Declaration:
we are telling the compiler that that
is the :
-> return type
-> name of the function
-> parameters/arguments

int addition();
int addition(int i,int j);
void display();
Defintion: Body of the function (logic)
ex:
int addition()
{
printf("xyz");
}
2.
int addition(int i,int j)
{
printf("The sum is %d",i+j);
}

Function Call:
we will call the function using the
name of the function itself along with
arguments.
ex:
display();
addition(10,20);

#include <stdio.h>
#include <stdlib.h>
void myfunction()
{
printf("\n My name is Sudhakar");
}
int main()
{
myfunction();
return 0;
}

10. Write a C program to display your name


inside a function.
11. Write a C program to add 2 integers using function
12. Write a C program for the following:
1. Addition
2. Subtraction
3. Multiplication
4. Divison
13. Write a C program to swap two integers
14. Write a C program to display numbers from 1 to 10
15. Write a C program to Print Multiplication Table of input Number in a function
16. Write a C Program to Check Whether a Number is Palindrome or Not Using While
Loop and function.
17. Write a C program to Reverse a Number Using While Loop in a function
18. Write a C program for a Calculator using functions
19. Write a C program for Temperature Conversion Celcius to Fahrenheit and Vice
Versa
20. Write a C program to Find LCM of Two Numbers Using While Loop

1. Write a C program explaining the use of nesting of functions


nesting of functions:
->calling a function with in another function.
-> we can't define a function within another function.

calling a function with arguments:


1. Call by value
2. Call by reference (Pointer concept

2. Write a C program to call a function using arguments like below:


1. send one integer
2. send one character.
3. send one float
4. send one string

3. Write a C program to explain call by value in functions

Call by value:
When you call function using a parameter, then the function
receives the value, and another duplicate local variable
will be created in the function.

4. Write a C program to explain call by reference in Functions.

-> sending a variable to a function is call by value


-> sending the address of a variable to a function , it is called call by
reference

Call by Reference: (Address -> *)


-> When you call a function using the address of the parameter,
and the function receives it as a pointer.
-> if you modify the variable inside a function, it will
effect the value in main function
-> here & is called Ambersent
-> here * this called astrik

in one line:

-> sending a variable to a function is call by value


-> sending the address of a variable to a function ,
it is called call by reference

5. Write a C program to swap two integers using call by reference


in functions

Pointer:
pointer is a variable which stores the address of another variable

Pointers reduce the length and complexity of a program.


Pointers make possible to return more than one value from the function. Pointers
increase the processing speed. In other words,
Execution time with pointers is faster because data are manipulated with the
address, that is, direct access to memory location.

type *var-name;
Ex:
int i=10;
int *j=&i;
Here j is a pointer which stores the address of variable i.

What is dangling pointer in C?

When a pointer is pointing to non-existing memory location is called dangling


pointer.
Dangling Pointers are the pointers that point to some freed/deleted location from
the program's memory (memory that is currently not in the use of the program).

What is null pointer in C?

A pointer that is assigned NULL is called a null pointer.


The NULL pointer is a constant with a value of zero defined in several standard
libraries.
Null pointer is a pointer which is pointing to nothing. Null pointer points to
empty location in memory. Value of null pointer is 0.
int *p = NULL;
char *p = NULL;

Void pointer is a generic pointer that can be used to point another variable of any
data type.
Void pointer can store the address of variable belonging to any of the data type
int main()
{
int a = 10;
char b = 'x';

void* p = &a; // void pointer holds address of int 'a'


p = &b; // void pointer holds address of char 'b'
}
What is wild pointer in C?
Uninitialized pointers are called as wild pointers in C which points to arbitrary
(random) memory location

int main()
{
int *p; /* wild pointer */
int a = 10;
p = &a; /* p is not a wild pointer now*/
*p = 12; /* This is fine. Value of a is changed */
}

7. Write a C program to take a int pointer,assign the value, and print


8. Write a C program to take a float pointer,assign the value, and print
9. Write a C program to take a double pointer,assign the value, and print

#include <stdio.h>
#include <stdlib.h>

int main()
{
int i=10;
int *j=&i; //Single pointer
int **k=&j; //double pointer
int ***m=&k; //Thriple pointer
printf("%d -> %d -> %d -> %d",i,*j,**k,***m);
return 0;
}

-> Single pointer


ex:
int i;
int *j=&i;
-> Double pointer
int i;
int *j=&i;
int **k=&j; -> Double pointer
-> Triple pointer
int i;
int *j=&i;
int **k=&j; -> Double pointer
int ***m=&k; -> Triple pointer

10. Write a C program to declare


-> Single pointer
-> double pointer
-> Triple pointer
print the value of i using all the pointers

11.Write a program in C to find the square of any number using


the function, send the argument using call by reference.
12. Write a program in C to check a given number is even or odd
using the function, send the argument using call by reference.

13.Write a C program to Print Multiplication Table of input Number


in a function, send the argument by call by reference.
14.Write a C program to Reverse a Number Using While Loop in a
function, send the argument by call by reference.
15.Write a C program to explain the use of nested for loop like
display all its positions.
16. Write a C program to display
*****
*****
*****
*****
*****
17. Write a C program to display
*
**
***
****
*****

for pattern refrence:

https://www.javatpoint.com/star-program-in-c

Day 6:
int i=10;
i=20;
i=30;
printf("%d",i);
This printf will print 30, because at a time we can store only
one value inside this variable i.

Is it possible to store multiple values inside a normal variable?


Nooooo, we can't store,
why?
because we have only one memory location, hence we can store
only one value.

if we want to store multiple values inside a single variable,then


we need to use Arrays.

Array:
An array is nothing but collection of homogenious(Similar) group
of values stored in a continuous memory.
or
we can say array is nothing but collection of similar values
10,20,30,40,50,60 -> group of integers
'a','b','c','d','e' -> group of characters
2.34,4.56,7.89,9.0 -> group of floats

Syntax:

int i; ->single variable , can store only one value at a time


int a[10]; -> group of 10 integers, also called integer array
float a[15] -> group of 15 floats, also called float array
char a[40] -> group of 40 characters,also called char array
double a[10] -> group of 10 doubles, also known as double array

Index -> position in the array, always starts from 0


ex:
int a[10];
here a is the name of the array, group of 10 integers.
its index starts from 0 and ends at 9

initialize an array:
int a[10]={100,200,300,400,500,600,650,700,750,800};

1. Write a C program to initialize a one dimensional array and


print the numbers from array
2. Write a Program to see the default values stored in array
3. Write a Program to take the elements of array from the
keyboard and print the values
4. Write a C Program to find the sum of all the elements
of a 1D array.

5. Write a C program to display the elements of an array in reverse order


6. Write a C program to display only even numbers from an array.
7. Write a C Program to find out the largest element in the array
8. Write a C program to find out the smallest element in the array

9. Write a program in C to copy the elements of one array into another array.

10. Write a C program to initialize the array without


array size and display the results.
11. Write a C program to initialize the array and copy
even numbers to even array.
12. Write a C program to initialize the array and copy
even numbers to even array.
13. Write a C program to initialize the array and copy
even numbers to even array and odd numbers to odd array.
14. Write a C program to reverse all the elements of an array.
15. Write a C program to display the values of an array using functions.

Important questions:
1. initialize one dimentional array
2. print all the elements of array
3. print all the elements of array in reverse order

1. for loop 2. initializing array 3. printing elements of arry

#include <stdio.h>
#include <stdlib.h>

int main()
{
int a[10]={100,200,300,400,500,600,650,700,750,800};
printf("\n Elements of array");

for(int i=0;i<10;i++)
{
printf("\n %d",a[i]);
}
return 0;
}

Linar search alogithm:


-> initialize the array
-> take the element to search
-> run a loop from 0th index to n-1 and
find if the element is found or not
-> if element is found , print element found
otherwise
print element not found

16. Write a C program for linear search.

Every alorithm is having


best case time complexity
worst case time complexity
avg case time complexity

pointer:
int i;
int *j=&i;

int a[10];

memory allocation:
memory allocation can happen in 2 ways in C Language:

-> Static memory allocation (Compile time)


-> Dynamic memory allocation (Run time)

memory allocation:
memory allocation can happen in 2 ways in C Language:

-> Static memory allocation (Compile time):


Memory allocation happens at compile time
bookmyshow
ex:
int a[5];
-> Dynamic memory allocation (Run time)
Memory allocation happens at run time (Execution time)
ex:
using pointers

memory allocation functions:


->malloc()
->calloc()
->realloc()
->free()

header files:
stdlib.h;
malloc.h;

Day 7:
memory allocation:
memory allocation can happen in 2 ways in C Language:

-> Static memory allocation (Compile time):


Memory allocation happens at compile time
bookmyshow
ex:
int a[5];
int i;
char c;
double d;
-> Dynamic memory allocation (Run time)
Memory allocation happens at run time (Execution time)
ex:
using pointers
C Language supports 4 functions for dynamic memory allocation
these 4 functions are available in below header files:
-> stdlib.h
-> malloc.h

Memory allocation functions:


1. malloc
2. calloc
3. realloc
4. free
malloc:
syntax:
pointer=(void *)malloc(noofblocks*sizeof(datatype));
ex:
to allocate memory for integer array.
1. int *a;
a=(int *)malloc(10*sizeof(int));
2. Allocate memory for float array.
float *a;
a=(float *)malloc(10*sizeof(float));
3. allocate memory for char array.
char *a;
a=(char *)malloc(10*sizeof(char));
4. allocate memory for double array.
double *a;
a=(double *)malloc(10*sizeof(double));

The malloc() function takes a single argument, which is the number of bytes to
allocate.
The calloc() function takes two arguments: the number of elements to allocate, and
the size of each element in bytes.

The malloc() function allocates uninitialized memory, which means that the contents
of the allocated memory are undefined.
The calloc() function allocates zero-initialized memory, which means that the
contents of the allocated memory are set to zero.

The calloc() function is generally slower than the malloc() function,

calloc() allocates zero-initialized memory and takes two arguments, while malloc()
allocates uninitialized memory and takes one argument.

1. Write a C program to scanf integer array and print all the elements.
Use dynamic memory allocation.
2. Write a C program to take a int pointer,assign the value, and print
3. Write a C program to take a float pointer,assign the value, and print
4. Write a C program to take a double pointer,assign the value, and print
5. WCP to allocate memory for an array of 5 intergers ,take the inputs from
keyboard, display the values
6. WCP to find the greatest element of an integer array(using dynamic memory
allocation).
7. WCP to copy the contents of one array into another Array (using dynamic memory
allocation).
8. WCP to print the elements of an array using dynamic memory allocation.
9. WCP to allocate memory for an array of 5 intergers ,take the inputs from
keyboard, display the values,udr calloc for dynamic allocation
10. WCP to copy the contents of one array into another Array (using dynamic memory
allocation, calloc function).
11.WCP to allocate memory for an array of 5 integers(using malloc/calloc), increase
the size of the array to 10 using realloc, print all the values.
12. Write a C program to allocate memory for 2 arrays, add them and display the
results in a function
13. Write a C program to allocate memory for 1D array, find out of the sum of all
the elements in a function

for(int i=0;i<5;i++)
{
for(int j=0;j<5-i-1;j++)
{
if(a[j] < a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}

16. WCP to search for an element in the array using linear search
17. WCP to search for an element in the array using binary search

Search:

to search for a given element in an array

We have 2 alogithms for searching


1. linar serach (sequential Search)
2. Binary Search

*****c****

2 dimensional array (2d array):


how to declare:
int a[3][3]; //total sizeis 36
how to initialize 2D array:
2D is nothing but collection of 1D arrays:
int a[3][3]= {
{10,20,30},
{40,50,60},
{70,80,90}
};

how to print all the elements from 2D array:


for (int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
printf("%d ",a[i][j]);
}
printf("\n");
}

2D array using dynamic memory allocatio


2 steps:
1.allocate memory for entire block.
2.allocate memory for internaal 1d array.

int **p;
p=(int **)malloc(9*sizeof(int));

for(i=0;i<9;i++)
{
p[i]=(int *)malloc(3*sizeof(int)
}

16. Write a C program to Initialize 2D array and display the matrix


17. Write a C program to take the elements of 2D from keyboard , display the values

18. Write a C program to scan 2D array, search for an element.


19. Write a C program to scan 2D array and find out the sum of all the elements
20. Matrix addition
21. Matrix Multiplication

23. WCP to find out max and min element in 2D array.

24. Write a C program to allocate memory for 2D array, scan the elements and print
them in matrix format.
25. Write a C program to allocate memory for 2D array, scan the elements and print
them in matrix format.
26. Sort array of 2D strings using dynamic memory allocation

*********************************************************************************

Functions:
-> push the return address to the stack
-> push all the arguments to the stack
-> go to the function definition
-> take out the parameters from stack
-> execute the function
-> pop the address
-> come back to the calling function

Preprocessor directives:
-> macros
-> file inclusions (<stdio.h>,"stdio.h")
-> conditional compilation
-> other directivies
Macro:
-> variables
-> Block (functions)

A macro is a piece of code in a program that is replaced by the value of the macro.
Macro is defined by #define directive.

Types Of Macros

1. Object-like Macros: (VARAIBALE TYPE)

// Macro definition
#define DATE 31
int main()
{
printf("Lockdown will be extended"
" upto %d-MAY-2020",
DATE);

return 0;
}

2.Chain Macros: Macros inside macros are termed as chain macros. In chain macros
first of all parent macro is expand then child macro is expanded

#define INSTAGRAM FOLLOWERS


#define FOLLOWERS 138
int main()
{
printf("Geeks for Geeks have %dK"
" followers on Instagram",
INSTAGRAM);
return 0;
}

Multi-line Macros: An object-like macro could have a multi-line. So to create a


multi-line macro you have to use backslash-newline.

#include <stdio.h>
#define ELE 1, \
5, \
3
int main()
{
int arr[] = { ELE };
printf("Elements of Array are:\n");
for (int i = 0; i < 3; i++) {
printf("%d ", arr[i]);
}
return 0;
}

4.Function-like Macro: These macros are the same as a function call. It replaces
the entire code instead of a function name.

#include <stdio.h>
#define min(a, b) (((a) < (b)) ? (a) : (b))
int main()
{
int a = 18;
int b = 76;
printf("Minimum value between"
" %d and %d is %d\n",
a, b, min(a, b));
return 0;
}

compiler will paste the code where the macro is called.


syntax:
#define
Variable:
#define i 100
macro Block:
#define sum(i,j) i+j

1. Area of a rectangle using macros


2. C program explaining conditional compilation
3. undef a variable

conditional compilation:
#define i 100
#ifdef i
printf("I am good");
#else
printf("I am not good");
#endif
-> #ifdef
-> #else
-> #ifndef
-> #undef

File operations:
1. open a file
2. close a fille
3. open a file for reading
4. open a file for writing
5. Open a file for appending
6. create a new file
7. open a file, copy the content paste in another file.

1. FILE *ptr;
2. fopen:
ptr=fopen("filepath","r");
3. fgetc -> getting a character from a file
Syntax:
ch=fgetc(fptr)
4. fclose
r -> read mode
w-> write
a -> append
r+

#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *ptr;
char ch;
ptr=fopen("C://Users/Linus/Downloads/testing.txt","r");
if (ptr == NULL)
{
printf("Not able to open the file");
}
else
{
printf("Able to open the file");
while((ch=fgetc(ptr))!=EOF)
{
printf("%c",ch);
}
fclose(ptr);
}

return 0;
}

r+ : Opens a text file for both reading and writing.


r :Opens an existing text file for reading purpose.
w: Opens a text file for writing. If it does not exist, then a new file is created.
Here your program will start writing content from the beginning of the file.
a: Opens a text file for writing in appending mode. If it does not exist, then a
new file is created. Here your program will start appending content in the existing
file content.

7. copy the contents of one file to another file


hint: open first file in read mode, second file in write mode
read the file line by line using fgets
write the data to second file using fputs
close first file
close second file

read write execute


- - - 0
- - x 1
- w - 2
- w x 3
r - - 4
r - x 5
r w - 6
r w x 7

-> chmod u=rwx file3.txt


chmod g=rx file3.txt
chmod o=x file3.txt
chmod u=rwx,g=rx,o=x file3.txt

Bitwise Operators:

Bitwise Or (|)
Bitwise and (&)
bitwise xor (or+not) ^
Bitwise not (~)
Left shift (<<)
shift right(>>)

ex: int i=6;


int j=4;

bitwise or : i|j (or gate)


bitwise and: i&j (and gate)
bitwise xor : i^j (xor gate)
bitwise not : ~i (not gate)
left sift : i<<3 (i will be left shifted 3 times) -> multiplication
right shift: i>>2 (i will be right shifted 2 times) -> divison

int a[]={10,20,30,40,50};
int pos=3;
int val=100;
for(int i=4;i>=pos;i--)
{
a[i+1]=a[i];
}
a[pos]=val;
for(int i=0;i<6;i++)
{
printf("\n %d",a[i]);
}

stucture:
Structures (also called structs) are a way to group several related variables into
one place.
Each variable in the structure is known as a member of the structure.

Self Refrential structure is a structure contains pointer to a structure of same


type.

#include <stdlib.h>
struct student
{
int i;
float f;
};
int main()
{
struct student s;
s.i=100;
s.f=10.25;

printf("\n The size of the structure is %u",sizeof(s));


printf("\n The value are %d %f",s.i,s.f);
return 0;
}

#include <stdio.h>
#include <stdlib.h>
struct myStruct {
int field1;
char field2;
};

int main() {
struct myStruct myArray[10];
for (int i = 0; i < 10; i++) {
myArray[i].field1 = i;
myArray[i].field2 = 'a' + i;
}
for (int i = 0; i < 10; i++)
{
printf("\n %d",myArray[i].field1);
printf("\n %c",myArray[i].field2);
}
return 0;
}

#include <stdio.h>
#include <stdlib.h>
struct myStruct {
int field1;
char field2;
};

int main() {
struct myStruct myArray[10];
for (int i = 0; i < 10; i++) {
myArray[i].field1 = i;
myArray[i].field2 = 'a' + i;
}
for (int i = 0; i < 10; i++)
{
printf("\n %d",myArray[i].field1);
printf("\n %c",myArray[i].field2);
}
return 0;
}

8. Definie a struct and declare a variable,initialize and print the values

Array of structures:
A student information -> single structure
multiple students information -> array of structures

9. WCP for array of structures


10. WCP for array of structures using dynamic memory allocation

struct student *s;


s= (struct student *)malloc(1*sizeof(struct student));

s->val1=100;
s->var2=10.25;

I have structure with one integer and one float;


i want to access these variables using
.
->
. (if it is a object of a structure)
-> (if it is a pointer of a structure)

C Array of Structures
struct student{
int rollno;
char name[10];
};
int main(){
int i;
struct student st[5];

for(i=0;i<5;i++){
printf("\nEnter Rollno:");
scanf("%d",&st[i].rollno);
printf("\nEnter Name:");
scanf("%s",&st[i].name);
}
printf("\nStudent Information List:");
for(i=0;i<5;i++){
printf("\nRollno:%d, Name:%s",st[i].rollno,st[i].name);
}
return 0;
}

Union:
it is similar to structure

union student
{
int i;
float f;
};
main()
{
union student s;

}
size of the union is the maximum size of the variable present inside that union

11. WCP to define a union and use that


12 WCP to define array of unions

int i=10,j=20;
int k=i+j;
char str[80];
//printf("The value of i is %d j is %d",i,j);
sprintf(str,"The sum of %d and %d is %d",i,j,k);
printf("The str value is %s",str);

enums:
user definied data type.
it is mainly used for assign names to integral constatnts.
#include <stdio.h>
#include <stdlib.h>
enum week{Sunday,monday,tuesday,wednesday,thursday,friday,saturday};
int main()
{
enum week w;
for(int i=Sunday;i<=saturday;i++)
printf("\n %d",i);
return 0;
}

#include <stdio.h>
#include <stdlib.h>
enum week{Sunday=10,monday,tuesday,wednesday=5,thursday=5,friday,saturday};
int main()
{
enum week w;
w=wednesday;
printf("The value of w is %d",w);
return 0;
}

enum month{january,feb,mar,apr,may,june,july,aug,sept};

#include <stdio.h>
#include <stdlib.h>
enum week{Sunday=10,monday,tuesday,wednesday=5,thursday=5,friday,saturday};
int main()
{
enum week w;
w=wednesday;
printf("The value of w is %d",w);
return 0;
}

Printing the values of linked list in reverse order:


void displaylist(struct node *temp)
{
if(temp==NULL)
return;
else
{
displaylist(temp->next);
printf("%d -> ",temp->data);
}
}

printing the values of linked list in normal order:void displaylist(struct node


*temp)
{
if(temp==NULL)
return;
else
{
printf("%d -> ",temp->data);
displaylist(temp->next);
}
}

Type Casting is basically a process in C in which we change a variable belonging to


one data type to another one.
int x;
float y;
y = (float) x;

// Given a & b
int a = 15, b = 2;
char x = 'a';

double div;

// Explicit Typecasting in double


div = (double)a / b;

linked list:

single node

#include<stdio.h>
#include<stdlib.h>

struct node
{
int data;
struct node *next;
};
int main()
{
struct node *head;
head=(struct node *)malloc(sizeof(struct node));

head->data=100;
head->next=NULL;

printf("%d",head->data);

return 0;
}

#include<stdio.h>
#include<stdlib.h>
struct node
{
int d;
struct node *next;
};

int main()
{
struct node *head=NULL; -->head node point to structure(first node will
create)
struct node *ptr,*temp;

for(int i=0;i<5;++i)
{
ptr=(struct node *)malloc(1*sizeof(struct node));
ptr->d=100+i;
if(head==NULL)
{
head=ptr;
temp=ptr;

}
else
{
temp->next=ptr;
temp=ptr;
}
}
temp=head;
while(temp!=NULL)
{
printf("%d->",temp->d);
temp=temp->next;
}
}

#include<stdio.h>
#include<stdlib.h>

struct node
{
int data;
struct node *next;
};
int main()
{
struct node *head;
int i;
for(i=0;i<5;i++)
{
head=(struct node *)malloc(sizeof(struct node));

head->data=100+i;
head->next=NULL;

printf("%d->",head->data);
}
return 0;
}
Linear Data Structures:
Stack
Queue
Arrays

Stack:
push (element)
pop()(removing element)
top - index
=====
top=-1
void push(int x)
{
if(top==size)
{
printf("Size is full or stack over flow");
}
else
{
top++;
a[top]=x;
}
}
====
int pop()
{
if(top==-1)
{
printf("Stack is empty");
}
else
{
x=a[top];
top--;
return x;
}
}

What is self referencing structure?


Self Referential structures are those structures that have one or more pointers
which point to the same type of structure, as their member.
In other words, structures pointing to the same type of structures are self-
referential in nature.
struct node {
int data1;
char data2;
struct node* link; -->self referencing structure
};
int main()
{
struct node ob;
return 0;
}

strncpy copies upto null or specified no. of bytes, whichever is less. But memcpy
overlooks null, and copies all specified no. of bytes.
None of them adds null in destination string by itself.

What is the difference between memcpy() & strcpy() functions in C?

memcpy() function is used to copy a specified number of bytes from one memory to
another. Whereas, strcpy() function is used to copy the contents of one string into
another string.
memcpy() function acts on memory rather than value. Whereas, strcpy() function acts
on value rather than memory.

The strcpy ( ) function is designed to work exclusively with strings. It copies


each byte of the source string to the destination string and
stops when the terminating null character (\0) has been moved. On the other hand,
the memcpy () function is designed to work with any type of data.

Because not all data ends with a null character, you must provide the memcpy ( )
function with the number of bytes you want to copy from the source to the
destination. The following program shows examples of both the strcpy ( ) and the
memcpy ( ) functions:

What is Macro? Why do we use macro?

Macro is a name which is given to a value or to a piece of code/block in a program.

Instead of using the value, we can use macro which will replace the value in a
program.

What is dangling pointer in C?

When a pointer is pointing to non-existing memory location is called dangling


pointer.

What is null pointer in C?

Null pointer is a pointer which is pointing to nothing. Null pointer points to


empty location in memory. Value of null pointer is 0.
int *p = NULL;
char *p = NULL;

Void pointer is a generic pointer that can be used to point another variable of any
data type.
Void pointer can store the address of variable belonging to any of the data type.

What is wild pointer in C?


Uninitialized pointers are called as wild pointers in C which points to arbitrary
(random) memory location

Memory leak occurs when programmers create a memory in heap and forget to delete
it.

The consequences of memory leak is that it reduces the performance of the computer
by reducing the amount of available memory.
void f()
{
int *ptr = (int *) malloc(sizeof(int));

/* Do some work */

free(ptr);
return;
}

The memory leak occurs, when a piece of memory which was previously allocated by
the programmer. Then it is not deallocated properly by programmer.

Constant:
Constants refer to fixed values that the program may not alter during its
execution. These fixed values are also called literals.
In C programming language, a constant is a value that cannot be changed during the
execution of a program. Constants can be used to represent fixed values,

Numeric constants:
const int MAX = 100;

Symbolic constants:
#define PI 3.14159

Defining Constants
?
There are two simple ways in C to define constants −

Using #define preprocessor.

Using const keyword.

const int LENGTH = 10;

Typedef:
The C programming language provides a keyword called typedef, which you can use to
give a type a new name.
typedef unsigned char BYTE;

You can use typedef to give a name to your user defined data types as well.
typedef struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
} Book;

diffrence between printf, fprintf, sprintf?

printf is a simple print statement it will display the given string.


printf("hello geeksquiz");

sprintf the string is stored to buffer insted of printing it.


sprintf: String print function instead of printing on console store it on char
buffer which is specified in sprintf.
sprintf(char *str, const char *string,...);
sprintf(buffer, "Sum of %d and %d is %d", a, b, c);

// The string "sum of 10 and 20 is 30" is stored


// into buffer instead of printing on stdout

fprintf: fprintf is used to print the string content in file but not on the stdout
console.
fprintf(FILE *fptr, const char *str, ...);
fprintf(fptr, "%d.%s\n", i, str);

quik-sort

Step 1 − Choose the highest index value has pivot


Step 2 − Take two variables to point left and right of the list excluding pivot
Step 3 − left points to the low index
Step 4 − right points to the high
Step 5 − while value at left is less than pivot move right
Step 6 − while value at right is greater than pivot move left
Step 7 − if both step 5 and step 6 does not match swap left and right
Step 8 − if left ≥ right, the point where they met is new pivot

Array

#include <stdio.h>
int main() {
int n;
double arr[100];
printf("Enter the number of elements (1 to 100): ");
scanf("%d", &n);

for (int i = 0; i < n; ++i) {


printf("Enter number%d: ", i + 1);
scanf("%lf", &arr[i]);
}

// storing the largest number to arr[0]


for (int i = 1; i < n; ++i) {
if (arr[0] < arr[i]) {
arr[0] = arr[i];
}
}

printf("Largest element = %.2lf", arr[0]);

return 0;
}

/* C Program to Remove All Duplicate Character in a String */

#include <stdio.h>
#include <string.h>

int main()
{
char str[100];
int i, j, k;

printf("\n Please Enter any String : ");


gets(str);

for(i = 0; i < strlen(str); i++)


{
for(j = i + 1; str[j] != '\0';)
{
if(str[j] == str[i])
{
for(k = j; str[k] != '\0'; k++)
{
str[k] = str[k + 1];
}
}
else
{
j++;
}
}
}
printf("\n The Final String after Removing All Duplicates = %s ", str);

return 0;
}

remove all special character.

#include <stdio.h>
#include <string.h>

int main()
{
char str[100];
int i, j, k;

printf("\n Please Enter any String : ");


scanf("%s",&str);

for(i = 0; i < strlen(str); i++)


{
while(!(str[i]>='a'&&str[i]<='z') &&!(str[i]>='A'&&str[i]<='Z')&&!
(str[i]=='\0'))
{
for(j = i; str[j] != '\0'; j++)
{
str[j]=str[j+1];
}
str[j]='\0';
}
}
printf("\n The Final String after Removing All Duplicates = %s ", str);

return 0;
}

// display dup in array


#include <iostream>
using namespace std;
int main() {
int a[10];
int i,j,k,n;
n=10;
for(i=0;i<n;i++)
{
cin>>a[i];
}
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(a[i]==a[j])
{
cout << a[i]<<endl;
}
}
}

return 0;
}

delete dup ele from array

// Online C++ compiler to run C++ program online


#include <iostream>
using namespace std;
int main() {
int a[10];
int i,j,k,n;
n=5;
cout<<"values";
for(i=0;i<n;i++)
{
cin>>a[i];
}
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(a[i]==a[j])
{
for(k=j;k<n;k++)
{
a[k]=a[k+1];
}
n--;
j--;
}

}
}
cout <<"values"<<endl;
for(i=0;i<n;i++)
{
cout <<a[i]<<endl;
}
return 0;
}

// Bubble sort in C

#include <stdio.h>

// perform the bubble sort


void bubbleSort(int array[], int size) {

// loop to access each array element


for (int step = 0; step < size - 1; ++step) {

// loop to compare array elements


for (int i = 0; i < size - step - 1; ++i) {
// compare two adjacent elements
// change > to < to sort in descending order
if (array[i] > array[i + 1]) {

// swapping occurs if elements


// are not in the intended order
int temp = array[i];
array[i] = array[i + 1];
array[i + 1] = temp;
}
}
}
}

// print array
void printArray(int array[], int size) {
for (int i = 0; i < size; ++i) {
printf("%d ", array[i]);
}
printf("\n");
}

int main() {
int data[] = {-2, 45, 0, 11, -9};

// find the array's length


int size = sizeof(data) / sizeof(data[0]);

bubbleSort(data, size);

printf("Sorted Array in Ascending Order:\n");


printArray(data, size);
}

void main()
{
char str[100]; /* Declares a string of size 100 */
int l,i;

printf("\n\nPrint individual characters of string in reverse order:\n");


printf("------------------------------------------------------\n");

printf("Input the string: ");


fgets(str, sizeof str, stdin);
l=strlen(str);
printf("The characters of the string in reverse are: \n");

for(i=l;i>=0;i--)
{
printf("%c ", str[i]);
}
printf("\n");
}
void main()
{
char str[100]; /* Declares a string of size 100 */

int l=0;

printf("\n\nPrint individual characters of string in reverse order:\n");


printf("------------------------------------------------------\n");

printf("Input the string: ");


fgets(str, sizeof str, stdin);
l=strlen(str);
printf("The
characters of the string in reverse are: \n");
for(str[l]='\0';l>=0;l--)
{
printf("%c ", str[l]);

}
printf("\n");
}

// Iterative C program to reverse a linked list


#include <stdio.h>
#include <stdlib.h>

/* Link list node */


struct Node {
int data;
struct Node* next;
};

/* Function to reverse the linked list */


static void reverse(struct Node** head_ref)
{
struct Node* prev = NULL;
struct Node* current = *head_ref;
struct Node* next = NULL;
while (current != NULL) {
// Store next
next = current->next;

// Reverse current node's pointer


current->next = prev;

// Move pointers one position ahead.


prev = current;
current = next;
}
*head_ref = prev;
}

// Online C compiler to run C program online


#include <stdio.h>
int main() {

int a=30, b=20, c=0;


// Iterate until no carry
while (b != 0)
{
// carry now stores common
//set bits of a and b
c = a & b;
a = a ^ b;
// Carry to be shifted by one so that on adding
// it to a, we get the required sum
b = c << 1;
}
printf("%d \n",a);
return 0;
}

#include <stdio.h>
int main() {
int a[10], n;
int largest1, largest2, i;
scanf("%d", &n);
printf("enter elements");
for (i = 0; i < n; i++) {
scanf("%d", &a[i]);
}
largest1 = a[0];
for (i = 0; i < n; i++) {
if (a[i] > largest1) {
largest1 = a[i];
}
}
largest2 = a[0];
for (i = 1; i < n; i++) {
if (a[i] > largest2 && a[i] < largest1)
largest2 = a[i];
}
printf("First and second largest number is %d and %d ", largest1, largest2);
}

// C program to find maximum and minimum in a Binary Tree


#include <limits.h>
#include <stdio.h>
#include <stdlib.h>

// A tree node
struct Node {
int data;
struct Node *left, *right;
};

// A utility function to create a new node


struct Node* newNode(int data)
{
struct Node* node
= (struct Node*)malloc(sizeof(struct Node));
node->data = data;
node->left = node->right = NULL;
return (node);
}
// Returns maximum value in a given Binary Tree
int findMax(struct Node* root)
{
// Base case
if (root == NULL)
return INT_MIN;

// Return maximum of 3 values:


// 1) Root's data 2) Max in Left Subtree
// 3) Max in right subtree
int res = root->data;
int lres = findMax(root->left);
int rres = findMax(root->right);
if (lres > res)
res = lres;
if (rres > res)
res = rres;
return res;
}

// Driver code
int main(void)
{
struct Node* NewRoot = NULL;
struct Node* root = newNode(2);
root->left = newNode(7);
root->right = newNode(5);
root->left->right = newNode(6);
root->left->right->left = newNode(1);
root->left->right->right = newNode(11);
root->right->right = newNode(9);
root->right->right->left = newNode(4);

// Function call
printf("Maximum element is %d \n", findMax(root));

return 0;
}

1010
10100
=
00000
c=0;
1010
10100
=11110
a=11110
a=30

b=000000 <<1

Revers a bit

// C implementation to reverse bits of a number


#include <stdio.h>
// function to reverse bits of a number
unsigned int reverseBits(unsigned int n)
{
unsigned int rev = 0;
int i;
// traversing bits of 'n' from the right

for(i=0;i<8;i++)
{
// bitwise left shift 'rev' by 1
rev <<= 1;

// if current bit is '1'


if ((n & 1) == 1)
rev++;

// bitwise right shift 'n' by 1


n >>= 1;
}
// required number
return rev;
}

// Driver program to test above

int main()
{
unsigned int n =10;
printf("%u", reverseBits(n));
return 0;
}

#include <stdio.h>
int main() {
int i, j, rows;
printf("Enter the number of rows: ");
scanf("%d", &rows);
for (i = rows; i >= 1; --i) {
for (j = 1; j <= i; ++j) {
printf("* ");
}
printf("\n");
}
return 0;
}

Example 6: Full Pyramid of *

#include <stdio.h>
int main() {
int i, j, n, k = 0;
printf("Enter the number of rows: ");
scanf("%d", &n);
for (i = 1; i <= n; ++i, k = 0) {
for (j = 1; j <= n - i; ++j) {
printf(" ");
}
while (k != 2 * i - 1) {
printf("* ");
++k;
}
printf("\n");
}
return 0;
}

*
* * *
* * * * *
* * * * * * *
* * * * * * * * *

what is memcpy and strncpy.


Strncpy will copy up to NULL even you specified the number of bytes to copy ,
but memcpy will copy up to specified number of bytes .
The main difference is that memcpy will copy all N characters you ask for, while
strncpy will copy
up to the first null terminator inclusive, or N characters, whichever is fewer.

key difference between memcpy() and strncpy() is that memcpy() copies a specified
number of bytes from the source buffer to the destination buffer,
while strncpy() copies a specified number of characters or until a null character
is encountered in the source buffer.
If you need to copy a fixed number of bytes and do not need null termination,
memcpy() is the appropriate choice.
If you need to copy a fixed number of characters and want null termination,
strncpy() is the appropriate choice.

diffrent between inline and macro?


Inline functions are similar to macros bcs they both are expanded at compile time
but the macro are expanded by the pre-processor
while inline functions are parased by the compiler.

The main difference between inline and macro functions is that inline functions are
parsed by the compiler,
whereas macros in a program are expanded by the preprocessor.
The keyword "inline" is used to define an inline function, whereas "#define" is
used to define a macro.

An inline function is a normal function that is defined by the inline keyword.


An inline function is a short function that is expanded by the compiler. And its
arguments are evaluated only once.
An inline functions are the short length functions that are automatically made the
inline functions without using the inline keyword inside the class.

inline return_type function_name ( parameters )


{
// inline function code
}

2. Macro :
It is also called preprocessors directive. The macros are defined by the #define
keyword. Before the program compilation,
the preprocessor examines the program whenever the preprocessor detects the macros
then preprocessor replaces the macro by the macro definition.

Difference between Inline and Macro in C++ :

S.NO Inline Macro


1. An inline function is defined by the inline keyword.
Whereas the macros are defined by the #define keyword.
2. Through inline function, the class’s data members can be accessed.
Whereas macro can’t access the class’s data members.
3. In the case of inline function, the program can be easily debugged.
Whereas in the case of macros, the program can’t be easily debugged.
4. In the case of inline, the arguments are evaluated only once.
Whereas in the case of macro, the arguments are evaluated every time whenever
macro is used in the program.
5. In C++, inline may be defined either inside the class or outside the class.
Whereas the macro is all the time defined at the beginning of the program.
6. In C++, inside the class, the short length functions are automatically made
the inline functions. While the macro is specifically defined.
7. Inline is not as widely used as macros. While
the macro is widely used.
8. Inline is not used in competitive programming. While
the macro is very much used in competitive programming.
9. Inline function is terminated by the curly brace at the end.
While the macro is not terminated by any symbol, it is terminated by a new
line.

Difference between Inline function and Normal function in C++


S.No. Inline Function Normal
Function

1. It is expanded inline when it is invoked.


It is a function that provides modularity to the program.
2. It is generally used to increase the execution time of the program.
It is generally used to improve the reusability of code and make it more
maintainable.
3. It is basically a function that is used when functions are small and called
very often. It is basically a group of statements that performs a particular task.
It is used when functions are big.
4. It requires ‘inline‘ keyword in its declaration.
It does not require any keyword in its declaration.
5. It generally executes much faster as compared to normal functions.
It generally executes slower than inline function for small size function.
6. In this, the body of functions is copied to every context where it is used
that in turn reduces the time of searching the body in the storage device or hard
disk. In this, the body of the function is stored in the storage device and when
that particular function is called every time, then CPU has to load the body from
hard disk to RAM for execution.
7. The compiler always places a copy of the code of that function at each point
where the function is called at compile time. It does not provide such a type of
functionality.
8. It generally includes only 2–3-line codes.
When the number of line codes is real massive I.e., normal functions contain
much code as per need.
9. It is a little harder to understand and test as compared to normal function.
It is much easier to understand and test as compared to the inline
function.
10. Functions that are present inside a class are implicitly inline.
Functions that are present outside class are considered normal functions.
11. Too many inline functions affect file size after compilation as it duplicates
the same code. Too many normal functions do not affect file size after
compilation.

What goes inside the compilation process?


A compiler converts a C program into an executable. There are four phases for a C
program to become an executable:

Pre-processing
Compilation
Assembly
Linking

Step 1: Creating a C Source File


$ vi filename.c

Step 2: Compiling using GCC compiler


We use the following command in the terminal for compiling our filename.c source
file
$ gcc filename.c –o filename

Step 3: Executing the program


$ ./filename

how to check in linux ssh is it's connected or not.

naming mechanism in function overlading.


Name Mangling
C++ differentiates functions with name and parameter both. It generates a new name
for each function.
The new name depends on the original C++ function name and parameters. Given a
function name of a set of parameters, it will always generate a unique name.
If parameters (number of params, type of params or order of params) change then it
will generate another name even if the original C++ function name is the same.
This process of encoding the function name is known as name mangling.

The process of name mangling is compiler dependent. Compilers can use different
strategies.
The name mangled by a compiler may not be same as mangled by other compilers.

Here are few examples of mangled name for g++ compiler:-


Original name: void myFun(); Mangled name: _Z5myFunv
Original name: void myFun(int a, char c); Mangled name: _Z5myFunic

looking at the mangled name we can observe the pattern. The pattern looks like: -
_Z numberOfCharsInOriginalFunctionName OriginalFunctionName parameter_names_encoded

diff between union and struct.


A Structure does not have a shared location for all of its members.
It makes the size of a Structure to be greater than or equal to the sum of the size
of its data members.
A Union does not have a separate location for every member in it.

Union in C is a special data type available in C that allows storing different data
types in the same memory location.
You can define a union with many members, but only one member can contain a value
at any given time.
Unions provide an efficient way of using the same memory location for multiple
purposes.

Difference between Structure and Union


Let's summarize the above discussed topic about the Struct and Union in the form of
a table that highlight the differences between structure and union:

Struct Union
The struct keyword is used to define a structure. The union keyword
is used to define union.
When the variables are declared in a structure, the compiler allocates memory to
each variables member.
The size of a structure is equal or greater to the sum of the sizes of each data
member.

When the variable is declared


in the union, the compiler allocates memory to the largest size
variable member. The size of
a union is equal to the size of its largest data member size.
Each variable member occupied a unique memory space. Variables members
share the memory space of the largest size variable.
Changing the value of a member will not affect other variables members.
Changing the value of one member will also affect other variables members.
Each variable member will be assessed at a time. Only one variable
member will be assessed at a time.
We can initialize multiple variables of a structure at a time. In union,
only the first data member can be initialized.

static , const casting?

The static_cast operator converts variable j to type float . This allows the
compiler to generate a division with an answer of type float .
All static_cast operators resolve at compile time and do not remove any const or
volatile modifiers.

const_cast
can be used to remove or add const to a variable. This can be useful if it is
necessary to add/remove constness from a variable.

static_cast
This is used for the normal/ordinary type conversion. This is also the cast
responsible for implicit type coersion and can also be called explicitly.
You should use it in cases like converting float to int, char to int, etc.

dynamic_cast
This cast is used for handling polymorphism. You only need to use it when you're
casting to a derived class.
This is exclusively to be used in inheritence when you cast from base class to
derived class.
reinterpret_cast
This is the trickiest to use. It is used for reinterpreting bit patterns and is
extremely low level.
It's used primarily for things like turning a raw data bit stream into actual data
or storing data in the low bits of an aligned pointer.

global and static.

Global variables have global scope, which means that they can be accessed from any
part of the program, including other files.
Static variables have block scope, which means that they can only be accessed from
within the block where they are defined.

Global variables have a lifetime that extends for the entire duration of the
program.
Static variables have a lifetime that extends for the entire duration of the
program, but are only initialized once when the program starts.

Global variables can be accessed by any part of the program, even if they are
defined in a different file.
Static variables can only be accessed within the block where they are defined.

Overall, global variables are useful when you need to define a variable that can be
accessed from multiple parts of the program,
while static variables are useful when you need to define a variable that is only
accessed within a specific block.

By making a variable static, you can limit its scope to the current file.
This can help prevent naming conflicts and improve encapsulation, since the
variable is only accessible within the file where it is defined.

By making a variable static, you can hide its implementation details from other
parts of the program.
This can help improve the security and maintainability of your code.

Static global variables are initialized to zero by default


Static global variables can be faster than non-static global variables,

In C, a static function is a function that is only visible within the file where it
is defined.
A static function cannot be called from other files using the function name, and it
does not conflict with functions of the same name in other files.

char *c="Hello world";


char i=o;

#include<stdio.h>

int main()
{
char c[]="Helloo woorlod";
char a='o';
for(int i=0;c[i]!='\0';)
{
if(c[i]==a)
{
for(int j=i;c[j]!='\0';j++)
{
c[j]=c[j+1];
}
}
else
{
i++;
}
}
printf("%s",c);
return 0;
}

insert the value in nth position using single linked list;


#include <stdio.h>
#include <stdlib.h>

struct Node {
int data;
struct Node* next;
};

void insertNth(struct Node** headRef, int n, int value) {


// Create a new node with the given value
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = value;

if (n == 1) {
// Insert the new node at the head of the list
newNode->next = *headRef;
*headRef = newNode;
} else {
// Traverse the list to find the (n-1)th node
struct Node* prevNode = *headRef;
for (int i = 2; i < n; i++) {
if (prevNode == NULL) {
// n is greater than the length of the list, so insert at the end
break;
}
prevNode = prevNode->next;
}

// Insert the new node after the (n-1)th node


newNode->next = prevNode->next;
prevNode->next = newNode;
}
}

void printList(struct Node* node) {


while (node != NULL) {
printf("%d ", node->data);
node = node->next;
}
printf("\n");
}

int main() {
struct Node* head = NULL;

// Insert some values into the list


insertNth(&head, 1, 10); // Insert 10 at the beginning
insertNth(&head, 2, 20); // Insert 20 in the second position
insertNth(&head, 3, 30); // Insert 30 in the third position
insertNth(&head, 5, 50); // Insert 50 in the fifth position (after the end of
the list)

// Print the list


printList(head);

return 0;
}

how u find linked list is circular linked list.

A circular linked list is a linked list where the last node points back to the head
node, forming a loop.
To check if a linked list is a circular linked list in C,
we can use the "Floyd's cycle-finding algorithm" (also known as the "tortoise and
hare algorithm"),
which involves traversing the list with two pointers at different speeds. Here's
how the algorithm works:

Initialize two pointers, slow and fast, to the head of the list.
Traverse the list using the slow pointer, moving one node at a time, and the fast
pointer, moving two nodes at a time.
If the fast pointer encounters a NULL node, the list is not circular.
If the fast pointer ever points to the same node as the slow pointer, the list is
circular.

class design and sequence design in c++

In C++, "class" is used to define a new data type. A class is a user-defined type
that can contain data members (variables)
and member functions (methods). The syntax for defining a class in C++ is as
follows:

class ClassName {
private:
// private data members and functions
public:
// public data members and functions
};

"Sequence design" refers to the process of designing the flow of execution of a


program. In C++,
this is typically done using control structures such as loops and conditional
statements, as well as function calls and object instantiation.
The design of the sequence of execution depends on the specific requirements of the
program and the design of its classes and functions.
Here is an example of a simple sequence design in C++:
To delete the nth element in a linked list in C, you need to traverse the list to
find the nth node, then update the previous node's "next" pointer to skip over the
nth node and point to the (n+1)th node. Here's an example of a function that
deletes the nth node in a linked list:

gradle
Copy
struct Node {
int data;
struct Node* next;
};

void deleteNthNode(struct Node** head_ref, int n) {


// if the list is empty, return
if (*head_ref == NULL)
return;

struct Node* temp = *head_ref;

// if the head node is to be deleted


if (n == 1) {
*head_ref = temp->next; // change head
free(temp); // free old head
return;
}

// find the previ

ous node of the node to be deleted


for (int i = 1; temp != NULL && i < n - 1; i++)
temp = temp->next;

// if position is more than number of nodes


if (temp == NULL || temp->next == NULL)
return;

// delete the node at position n


struct Node* next = temp->next->next;
free(temp->next); // free the node
temp->next = next; // unlink the deleted node
}

You might also like