Write an algorithm to convert a decimal number to its equivalent hexadecimal number
Write an algorithm to convert a decimal number to its equivalent hexadecimal number
#include<stdio.h>
int main()
{
int n1=0,n2=1,n3,i,number;
printf("Enter the number of elements:");
scanf("%d",&number);
printf("\n%d %d",n1,n2);//printing 0 and 1
for(i=2;i<number;++i)//loop starts from 2 because 0 and 1 are already printed
{
n3=n1+n2;
printf(" %d",n3);
n1=n2;
n2=n3;
}
return 0;
}
Write a program to search an element in a given list of 20 elements using linear search.
#include <stdio.h>
void main()
{ int num; int i, keynum, found = 0;
printf("Enter the number of elements ");
scanf("%d", &num);
int array[num];
printf("Enter the elements one by one \n");
for (i = 0; i < num; i++){
scanf("%d", &array[i]);
}
printf("Enter the element to be searched ");
scanf("%d", &keynum);
for (i = 0; i < num ; i++) {
if (keynum == array[i] ) {
found = 1;
break;
}
}
if (found == 1)
printf("Element is present in the array at position %d",i+1);
else
printf("Element is not present in the array\n");
}
Write a program to take a list of Nnumbers, separate even and odd numbers and put them in two separate files (even_file and odd_file). Use file
handling concept.
#include <stdio.h>
main(){
FILE *f1, *f2, *f3;
int number, i;
printf("Contents of DATA file\n\n");
f1 = fopen("DATA", "w"); /* Create DATA file */
for(i = 1; i <= 30; i++){
scanf("%d", &number);
if(number == -1) break;
putw(number,f1);
}
fclose(f1);
f1 = fopen("DATA", "r");
f2 = fopen("ODD", "w");
f3 = fopen("EVEN", "w");
while((number = getw(f1)) != EOF){
if(number %2 == 0)
putw(number, f3); /* Write to EVEN file */
else
putw(number, f2); /* Write to ODD file */
}
fclose(f1);fclose(f2);fclose(f3);
f2 = fopen("ODD","r");
f3 = fopen("EVEN", "r");
printf("\n\nContents of ODD file\n\n");
while((number = getw(f2)) != EOF)
printf("%4d", number);
printf("\n\nContents of EVEN file\n\n");
while((number = getw(f3)) != EOF)
printf("%4d", number);
fclose(f2);
fclose(f3);
}
Write a program to demonstrate passing a structure to a function.
A structure can be passed to any function from main function or from any sub function.
Structure definition will be available within the function only. Passing structure to a function by value
Passing structure to a function by address(reference)
No need to pass a structure – Declare structure variable as global
#include <stdio.h>
#include <string.h>
struct student {
int id;
char name[20];
float percentage;
};
void func(struct student record);
int main() {
struct student record;
record.id=1;
strcpy(record.name, "Raju");
record.percentage = 86.5;
func(record);
return 0;
}
void func(struct student record)
{
printf(" Id is: %d \n", record.id);
printf(" Name is: %s \n", record.name);
printf(" Percentage is: %f \n", record.percentage);
}
Write a program to perform the following operation on matrices : D = A + (B * C) where A, B and C are matrices of 3 × 3 size and D is the resultant
matrix.
Write a program to convert lower case letters to upper case in a given string.
#include <stdio.h>
#define MAX_SIZE 100 // Maximum string size
int main()
{
char str[MAX_SIZE];
int i;
/* Input string from user */
printf("Enter your text : ");
gets(str);
for(i=0; str[i]!='\0'; i++)
{
if(str[i]>='a' && str[i]<='z')
{
str[i] = str[i] - 32;
}
}
printf("Uppercase string : %s",str);
return 0;
}
Program to convert the uppercase string into lower case using for loop
#include <stdio.h>
#include <conio.h>
int main ()
{
char str[30];
int i;
printf (" Enter the string: ");
scanf (" %s", &str); // take a string
for ( i = 0; i <= strlen (str); i++) {
if (str[i] >= 65 && str[i] <= 90)
str[i] = str[i] + 32; /* add 32 to string character to convert into lower case. */
}
printf (" \n Upper Case to Lower case string is: %s", str);
return 0;
}
How ‘# define’ is used to create functional macros ? Illustrate with the help of a C program segment.
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. Whenever a macro name is
encountered by the compiler, it replaces the name with the definition of the macro. Macro definitions need not be terminated by a semi-colon( ;).
#include <stdio.h>
#define AREA(l, b) (l * b)
int main(){
int l1 = 10, l2 = 5, area;
area = AREA(l1, l2);
printf("Area of rectangle"
" is: %d",
area);
return 0;
}
Write a program to concatenate two strings without using the strcat( ) function
#include <stdio.h>
int main(){
char str1[100] = "Geeks", str2[100] = "World";
char str3[100]; int i = 0, j = 0;
printf("\nFirst string: %s", str1);
printf("\nSecond string: %s", str2);
while (str1[i] != '\0') {
str3[j] = str1[i];
i++;
j++;
} i = 0;
while (str2[i] != '\0') {
str3[j] = str2[i];
i++; j++; }
str3[j] = '\0';
printf("\nConcatenated string: %s", str3);
return 0;}
Write a C program to find the substring in a string without using a library function.
#include<stdio.h>
#include<string.h>
int search(char[], char[]);
int main() {
int loc;
char source[] = "maharashtra";
char target[] = "sht";
loc = search(source, target);
if (loc == -1)
printf("\nNot found");
else
printf("\nFound at location %d", loc + 1);
return (0);
}
int search(char src[], char str[]) {
int i, j, firstOcc;
i = 0, j = 0;
while (src[i] != '\0') {
while (src[i] != str[0] && src[i] != '\0')
i++;
if (src[i] == '\0')
return (-1);
firstOcc = i;
while (src[i] == str[j] && src[i] != '\0' && str[j] != '\0') {
i++;
j++; }
if (str[j] == '\0')
return (firstOcc);
if (src[i] == '\0')
return (-1);
i = firstOcc + 1;
j = 0;}}
Write a program to calculate the number of vowels (a, e, i, o, u) separately in the entered string and display their individual count.
#include <stdio.h>
#include <conio.h>
void main(){
char a[100];
int len,i,vow=0;
clrscr();
printf("\nENTER A STRING: ");
gets(a);
len=strlen(a);
for(i=0;i<len;i++){
if(a[i]=='a' || a[i]=='A' || a[i]=='e' || a[i]=='E' || a[i]=='i' || a[i]=='I' || a[i]=='o' || a[i]=='O' || a[i]=='u' || a[i]=='U')
vow=vow+1;
}
printf("\nTHERE ARE %d VOWELS IN THE STRING",vow);
getch();
}
#include <stdio.h>
#define LIMIT 5
int main(){
for (int i = 0; i < LIMIT; i++) {
printf("%d \n",i);}
return 0;}
2. File Inclusion
This type of preprocessor directive tells the compiler to include a file in the source code program. There are two types of files that can be included by the user
in the program:
Header files or Standard files: These files contain definitions of pre-defined functions like printf(), scanf(), etc. These files must be included to work with
these functions. Different functions are declared in different header files. For example, standard I/O functions are in the ‘iostream’ file whereas functions that
perform string operations are in the ‘string’ file.
Syntax:
#include< file_name >
3. Conditional Compilation
Conditional Compilation directives are a type of directive that helps to compile a specific portion of the program or to skip the compilation of some specific
part of the program based on some conditions. This can be done with the help of the two preprocessing commands ‘ ifdef‘ and ‘endif‘.
Syntax:
#ifdef macro_name
statement1;
statement2;
statement3;
.
.
statementN;
#endif
4. Other Directives
Apart from the above directives, there are two more directives that are not commonly used. These are:
#undef Directive: The #undef directive is used to undefine an existing macro. This directive works as:
#undef LIMIT
Using this statement will undefine the existing macro LIMIT. After this statement, every “#ifdef LIMIT” statement will evaluate as false.
#pragma Directive: This directive is a special purpose directive and is used to turn on or off some features. This type of directives are compiler-specific, i.e.,
they vary from compiler to compiler. Some of the #pragma directives are discussed below:
#pragma startup and #pragma exit: These directives help us to specify the functions that are needed to run before program startup (before the control
passes to main()) and just before program exit (just before the control returns from main()).
Discuss dynamic memory allocation in C. Write and explain dynamic allocation functions in C.
The concept of dynamic memory allocation in c language enables the C programmer to allocate memory at runtime. Dynamic memory allocation in c language
is possible by 4 functions of stdlib.h header file.
malloc():The malloc() function allocates single block of requested memory. It doesn't initialize memory at execution time, so it has garbage value initially.It returns
NULL if memory is not sufficient.The syntax of malloc() function is given below
ptr=(cast-type*)malloc(byte-size)
calloc():The calloc() function allocates multiple block of requested memory.It initially initialize all bytes to zero.It returns NULL if memory is not sufficient. The
syntax of calloc() function is given below:
ptr=(cast-type*)calloc(number, byte-size)
realloc():If memory is not sufficient for malloc() or calloc(), you can reallocate the memory by realloc() function. In short, it hanges the memory size.Let's see the
syntax of realloc() function. ptr=realloc(ptr, new-size)
free():The memory occupied by malloc() or calloc() functions must be released by calling free() function. Otherwise, it will consume memory until program
exit.Let's see the syntax of free() function. free(ptr)
Write a C program to implement STRING COPY operation that copies a string ‘‘str1’’ to another string ‘‘str2’’ without using library function.
#include<stdio.h>
#include<conio.h>
void main(){
char s1[100],s2[100],i;
clrscr();
printf(“enter string s1: “);
scanf(“%s”,s1);
for(i=0;s1[i]!=’\0’;++i) {
s2[i]=s1[i];
}
s2[i]=’\0’;
printf(“string s2: %s”,s2);
getch();
}
Define an Array. How do we declare and initialize a single-dimensional array and a 2-dimensional array ? Explain with an example for each.
Array in C can be defined as a method of clubbing multiple entities of similar type into a larger group. These entities or elements can be of int, float, char, or
double data type or can be of user-defined data types too like structures. However, in order to be stored together in a single array, all the elements should be of
the same data type. The elements are stored from left to right with the left-most index being the 0th index and the rightmost index being the (n-1) index.
Single Dimensional Arrays: Single dimensional array or 1-D array is the simplest form of arrays that can be found in C. This type of array consists of elements of
similar types and these elements can be accessed through their indices.
Multi-dimensional Arrays: The most common type of multi-dimensional array that is used in the C language is a 2-D array. However, the number of dimensions
can be more than 2 depending upon the compiler of the user’s system. These arrays consist of elements that are array themselves.
Array Declaration by Initializing Elements
An array can be initialized at the time of its declaration. In this method of array declaration, the compiler will allocate an array of size equal to the number of the
array elements. The following syntax can be used to declare and initialize an array at the same time.
// initialize an array at the time of declaration.
int my_array[] = {100, 200, 300, 400, 500}
In the above syntax, an array of 5 elements is created and even though the array size has not been specified here, the compiler will allocate a size of 5 integer
elements.
Array Declaration by Specifying the Size and Initializing Elements
An array can also be created by specifying the size and assigning array elements at the time of declaration. This method of array creation is different from the
previous one. Here, if the number of initialized elements is less than the size of the array specified, then the rest of the elements will automatically be initialized to
0 by the compiler. See the following syntax to understand this.
Examples of the 1-D Array in C
The following programs illustrate declaration, initialization, input/output operations, and basic operations like insertion, deletion, sorting, and searching in the 1-D
array in C.
Example 1: Array Declaration, Input, and Output
#include <stdio.h>
int main()
{
// declare an array.
int my_array[6];
printf("Enter array elements:\n");
// input array elements.
int i;
for (i = 0; i < 6; i++){
scanf("%d", &my_array[i]);
}
printf("\nArray elements are:\n");
// print array elements.
for (i = 0; i <= 5; i++) {
printf("%d ", my_array[i]);
}
return 0;
}
2 Dimensional Array in C: A 2-dimensional array or 2-D array is the simplest form of multi-dimensional array in C. Each element in a 2-D array can be
represented as a separate 1-D array. A 2-D array contains a certain number of rows and columns and the total number of array elements can be found by
multiplying the number of rows and columns. For example, if the array is my_array[2][3], then the total number of elements in the array is 6.
#include <stdio.h>
int main(){
int x[5][2] = {{0, 1}, {2, 3}, {4, 5}, {6, 7}, {8, 9}};
int i, j;
// print the value of each array element.
// outer loop- for rows.
for (i = 0; i < 5; i++)
{ for (j = 0; j < 2; j++)
{
printf("Element at x[ %d", i);
printf("][ %d", j);
printf("] :");
printf("%d", x[i][j]);
printf("\n");
}}
return 0;}
Write a C program that invokes this function to generate numbers between the given range.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(){
int lower = 1, upper = 6, count = 10;
srand(time(0));
printf("The random numbers are: ");
for (int i = 0; i < count; i++) {
int num = (rand() % (upper - lower + 1)) + lower;
printf("%d ", num);
}
return 0;}
Write a C function isodd(num) that accepts an integer argument and returns 1 if the argument is odd and 0 otherwise.
#include<stdio.h>
int isEven(int n){
if(n%2==0)
return 1;
else
return 0;
}
int main(){
int num,ans,i,z;
printf("/*How Many Numbers You \nWant to Check EVEN or ODD*/\n\nEnter Limit :
");
scanf("%d",&z);
for(i=1;i<=z;i++){
printf("\nEnter Number-%d : ",i);
scanf("%d",&num);
ans=isEven(num);
if(ans==1)
printf("%d is Even\n",num);
if(ans==0)
printf("%d is Odd\n",num);}
return 0;}
return 0;
}
Write an algorithm and draw corresponding flowchart to find the largest number among 3
numbers given as input.
1. Start
2. Read the three numbers to be compared, as A, B and C.
3. Check if A is greater than B.
Write a program using file-handling concept, to read and count the no. of characters in a .dot file.
#include <stdio.h>
#define MAX_FILE_NAME 100
int main(){
FILE* fp;
int count = 0;
char filename[MAX_FILE_NAME];
char c;
printf("Enter file name: ");
scanf("%s", filename);
fp = fopen(filename, "r");
if (fp == NULL) {
printf("Could not open file %s",
filename);
return 0;
}for (c = getc(fp); c != EOF; c = getc(fp))
count = count + 1;
fclose(fp);
printf("The file %s has %d characters\n ",
filename, count);return 0;
}
Write a C program to sort the given array of integers in ascending order, using any of the sorting algorithm. Explain the logic. 10
#include <stdio.h>
void main()
{
int i, j, a, n, number[30];
printf("Enter the value of N \n");
scanf("%d", &n);
printf("Enter the numbers \n");
for (i = 0; i < n; ++i)
scanf("%d", &number[i]);
for (i = 0; i < n; ++i) {
for (j = i + 1; j < n; ++j){
if (number[i] > number[j]) {
a = number[i];
number[i] = number[j];
number[j] = a;
}}}
printf("The numbers arranged in ascending order are given below \n");
for (i = 0; i < n; ++i)
printf("%d\n", number[i]);}
Write a C program using structures, to find the total, average and grade for 5 students
#include <stdio.h>
int main()
{
float eng, phy, chem, math, comp;
float total, average, percentage;
printf("Enter marks of five subjects: \n");
scanf("%f%f%f%f%f", &eng, &phy, &chem, &math, &comp);
total = eng + phy + chem + math + comp;
average = total / 5.0;
percentage = (total / 500.0) * 100;
printf("Total marks = %.2f\n", total);
printf("Average marks = %.2f\n", average);
printf("Percentage = %.2f", percentage);
return 0;
}
Write a program to : Find the length of a string and Print the reverse of the string.
#include <stdio.h>
#include <string.h>
int str_len( char *st);
void revstr( char *st);
int main() {
char st[50];
printf (" Enter a string to be reversed: ");
scanf( "%s", st);
revstr(st);
printf (" The reverse string is: %s", st);
return 0; }
void revstr (char *st) {
int len, i; char *start, *end, temp;
len = str_len (st);
start = st; end = st;
for (i = 0; i < len - 1; i++)
end++;
for (i = 0; i < len/2; i++) {
temp = *end; *end = *start;
*start = temp; start++; end--;
} }
int str_len (char *ptr)
{ int i = 0;
while ( *(ptr + i) != '\0')
i++;
return i; }
Write an interactive C program to perform the following operation on a 3 x 3 matrix with appropriate validation checks : 10 C = A * B
#include<stdio.h>
int main() {
int a[10][10], b[10][10], c[10][10], i, j, k;
int sum = 0;
printf("\nEnter First Matrix : n");
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
scanf("%d", &a[i][j]);} }
printf("\nEnter Second Matrix:n");
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
scanf("%d", &b[i][j]); }}
printf("The First Matrix is: \n");
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
printf(" %d ", a[i][j]); }
printf("\n");}
printf("The Second Matrix is : \n");
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
printf(" %d ", b[i][j]);}
printf("\n");}
for (i = 0; i <= 2; i++) {
for (j = 0; j <= 2; j++) {
sum = 0;
for (k = 0; k <= 2; k++) {
sum = sum + a[i][k] * b[k][j]; }
c[i][j] = sum; }}
printf("\nMultiplication Of Two Matrices : \n");
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
printf(" %d ", c[i][j]);}
printf("\n"); }
return (0);}
Using file handling concept, write a C program to read a file and count the no. of lines in it
#include <stdio.h>#define FSIZE 100
int main(){
FILE *fptr;
int ctr = 0; char fname[FSIZE];
char c;
printf("\n\n Read the file and count the number of lines :\n");
printf("--------------------------------------------------\n");
printf(" Input the file name to be opened : ");
scanf("%s",fname);
Write a program to find out square and cube of a given number using macros.
#include <stdio.h>
#define SQUARE(x) (x * x)
#define CUBE(x) (x * x * x)
int main(){
int num;
printf("Enter any number to find square and cube: ");
scanf("%d", &num);
printf("SQUARE(%d) = %d\n", num, SQUARE(num));
printf("CUBE(%d) = %d\n", num, CUBE(num));
return 0;}
Write a program in C to find the largest and smallest number in an array of 100 in
#include<stdio.h>
int main(){
int a[50],i,n,large,small;
printf(“\nEnter the number of elements : “);
scanf(“%d”,&n);
printf(“\nInput the array elements : “);
for(i=0;i<n;++i)
scanf(“%d”,&a[i]);
large=small=a[0];
for(i=1;i<n;++i){
if(a[i]>large)
large=a[i];if(a[i]<small) small=a[i];}
printf(“\nThe smallest element is %d\n”,small);
printf(“\nThe largest element is %d\n”,large);
return 0}
Define an array. How are arrays declared and initialized ? Write a C program tO add two metrices A and B of size 3 x
#include <stdio.h>
int main() {
int r, c, a[100][100], b[100][100], sum[100][100], i, j;
printf("Enter the number of rows (between 1 and 100): ");
scanf("%d", &r);
printf("Enter the number of columns (between 1 and 100): ");
scanf("%d", &c);
printf("\nEnter elements of 1st matrix:\n");
for (i = 0; i < r; ++i)
for (j = 0; j < c; ++j) {
printf("Enter element a%d%d: ", i + 1, j + 1);
scanf("%d", &a[i][j]);}
printf("Enter elements of 2nd matrix:\n");
for (i = 0; i < r; ++i)
for (j = 0; j < c; ++j) {
printf("Enter element b%d%d: ", i + 1, j + 1);
scanf("%d", &b[i][j]);}
for (i = 0; i < r; ++i)
for (j = 0; j < c; ++j) {
sum[i][j] = a[i][j] + b[i][j]; }
printf("\nSum of two matrices: \n");
for (i = 0; i < r; ++i)
for (j = 0; j < c; ++j) {
printf("%d ", sum[i][j]);
if (j == c - 1) {
printf("\n\n");
}}
return 0;}
What are global variables and static variables ? Explain with the help of an example.
Static variables are the variables that have the property to preserve their value from their previous scope. It means that its value does not get re-initialized every
time it is declared. It is different from normal variables because normal variables get destroyed as soon as the function in which it is declared completes its
execution. While the memory of normal variables is allocated in the stack segment, the memory of static variables is allocated in the data segment. That is the
reason why they are able to preserve the value of their previous scope.
Syntax of Static Variable in C
The syntax of declaring a static variable in the C programming language is given below.static int variable_name ;
Explain type-cast and size-of operators in C with an example to each. Define a preprocessor in C. How is it implemented ? Explain with the help of an example.
include <stdio.h>
int main() {
static int variable = 10;
variable++;
printf("%d \n",variable); // prints 11
variable = 0; // reinitializing the value of the static variable
printf("%d \n",variable); // prints 0
}
Global Variables
The variables declared outside any function are called global variables. They are not limited to any function. Any function can access and modify global variables.
Global variables are automatically initialized to 0 at the time of declaration. Global variables are generally written before main() function.
#include<stdio.h>
void func_1();
void func_2();
int a, b = 10; // declaring and initializing global variables
int main()
{
printf("Global a = %d\n", a);
printf("Global b = %d\n\n", b);
func_1();
func_2();
// signal to operating system program ran fine
return 0;
}
void func_1()
{
printf("From func_1() Global a = %d\n", a);
printf("From func_1() Global b = %d\n\n", b);
}
void func_2()
{
int a = 5;
printf("Inside func_2() a = %d\n", a);
}
What is the difference between a Highlevel language and a Low-level language ? Why C language is referred to as Middlelevel language ?
(i) Low Level Languages or Machine Oriented Languages: The language whose design is governed by the circuitry and the structure of the
machine is known as the Machine language. This language is difficult to learn and use. It is specific to a given computer and is different for different computers i.e.
these languages are machine-dependent. These languages have been designed to give a better machine efficiency, i.e. faster program execution. Such
languages are also known as Low Level Languages. Another type of Low-Level Language is the Assembly Language. We will code the assembly language
program in the form of mnemonics. Every machine provides a different set of mnemonics to be used for that machine only depending upon the processor that the
machine is using.
(ii) High Level Languages or Problem Oriented Languages: These languages are particularly oriented towards describing the procedures for
solving the problem in a concise, precise and unambiguous manner. Every high level language follows a precise set of rules. They are developed to allow
application programs to be run on a variety of computers. These languages are machineindependent. Languages falling in this category are FORTRAN, BASIC,
PASCAL etc. They are easy to learn and programs may be written in these languages with much less effort. However, the computer cannot understand them and
they need to be translated into machine language with the help of other programs known as Compilers or Translators.
Explain the differences between static, auto, register and global variables with an example for each.
static variables
Static variables have a property of preserving their value even after they are out of their scope! Hence, static variables preserve their previous value in their
previous scope and are not initialized again in the new scope.
Syntax:
static data_type var_name = var_value;
AUTO:(Called automatic variables.)
All variables declared within a block of code are automatic by default, but this can be made explicit with the auto keyword.[note 1] An uninitialized automatic
variable has an undefined value until it is assigned a valid value of its type.[1]
Using the storage class register instead of auto is a hint to the compiler to cache the variable in a processor register. Other than not allowing the referencing
operator (&) to be used on the variable or any of its subcomponents, the compiler is free to ignore the hint.
In C++, the constructor of automatic variables is called when the execution reaches the place of declaration. The destructor is called when it reaches the end of
the given program block (program blocks are surrounded by curly brackets). This feature is often used to manage resource allocation and deallocation, like
opening and then automatically closing files or freeing up memory.
Global Variables
The variables declared outside any function are called global variables. They are not limited to any function. Any function can access and modify global variables.
Global variables are automatically initialized to 0 at the time of declaration. Global variables are generally written before main() function.
register variables
Registers are faster than memory to access, so the variables which are most frequently used in a C program can be put in registers using register keyword.
The keyword register hints to compiler that a given variable can be put in a register. It’s compiler’s choice to put it in a register or not. Generally, compilers
themselves do optimizations and put the variables in the register.
Syntax:
register data_type var_name = var_value;
List the arithmetic, logical and relational operators in C. When a, b, c and d are integers and values of a, b and c are 8, 6 and 4 respectively. Find the
value of d, if d = a + (b — c)* a / c
Arithmetic Operators: These are used to perform arithmetic/mathematical operations on operands. The binary operators falling in this category
are:
Addition: The ‘+’ operator adds two operands. For example, x+y.
Subtraction: The ‘-‘ operator subtracts two operands. For example, x-y.
Multiplication: The ‘*’ operator multiplies two operands. For example, x*y.
Division: The ‘/’ operator divides the first operand by the second. For example, x/y.
Modulus: The ‘%’ operator returns the remainder when first operand is divided by the second. For example, x%y.
Logical Operators:
They are used to combine two or more conditions/constraints or to complement the evaluation of the original condition under consideration. They are
described below:
Logical AND operator: The ‘&&’ operator returns true when both the conditions under consideration are satisfied. Otherwise it returns false. For
example, a && b returns true when both a and b are true (i.e. non-zero).
Logical OR operator: The ‘||’ operator returns true even if one (or both) of the conditions under consideration is satisfied. Otherwise it returns
false. For example, a || b returns true if one of a or b or both are true (i.e. non-zero). Of course, it returns true when both a and b are true.
Logical NOT operator: The ‘!’ operator returns true the condition in consideration is not satisfied. Otherwise it returns false. For example, !
a returns true if a is false, i.e. when a=0.
Relational Operators
Relational operators are used for comparison of two values to understand the type of relationship a pair of number shares. For example, less than, greater
than, equal to etc. Let’s see them one by one
Equal to operator: Represented as ‘==’, the equal to operator checks whether the two given operands are equal or not. If so, it returns true.
Otherwise it returns false. For example, 5==5 will return true.
Not equal to operator: Represented as ‘!=’, the not equal to operator checks whether the two given operands are equal or not. If not, it returns
true. Otherwise it returns false. It is the exact boolean complement of the ‘==’ operator. For example, 5!=5 will return false.
Greater than operator: Represented as ‘>’, the greater than operator checks whether the first operand is greater than the second operand or not.
If so, it returns true. Otherwise it returns false. For example, 6>5 will return true.
Less than operator: Represented as ‘<‘, the less than operator checks whether the first operand is lesser than the second operand. If so, it returns
true. Otherwise it returns false. For example, 6<5 will return false.
Greater than or equal to operator: Represented as ‘>=’, the greater than or equal to operator checks whether the first operand is greater than or
equal to the second operand. If so, it returns true else it returns false. For example, 5>=5 will return true.
Less than or equal to operator: Represented as ‘<=’, the less than or equal tooperator checks whether the first operand is less than or equal to
the second operand. If so, it returns true else false. For example, 5<=5 will also return true.
What are the rules of using Big-Onotation ? How the performance of the algorithms are measured ?
In our previous articles on Analysis of Algorithms , we had discussed asymptotic notations, their worst and best case performance, etc. in brief. In this article,
we discuss the analysis of the algorithm using Big – O asymptotic notation in complete detail.
Big-O Analysis of Algorithms
We can express algorithmic complexity using the big-O notation. For a problem of size N:
N0te: O(g) is a set!Abuse of notation: f = O(g) does not mean f ∈ O(g).The Big-O Asymptotic Notation gives us the Upper Bound Idea, mathematically
a natural number n0 such that f (n) ≤ cg(n) for all n >= n 0 .
described below: f(n) = O(g(n)) if there exists a positive integer n 0 and a positive constant c, such that f(n)≤c.g(n) ∀ n≥n0 The general step wise procedure for
Big-O runtime analysis is as follows:
Constant Multiplication:
If f(n) = c.g(n), then O(f(n)) = O(g(n)) ; where c is a nonzero constant.
Polynomial Function:
If f(n) = a0 + a1.n + a2.n2 + —- + am.nm, then O(f(n)) = O(n m).
Basically, this asymptotic notation is used to measure and compare the worst-case scenarios of algorithms theoretically. For any algorithm, the Big-O
analysis should be straightforward as long as we correctly identify the operations that are dependent on n, the input size.
Runtime Analysis of Algorithms
In general cases, we mainly used to measure and compare the worst-case theoretical running time complexities of algorithms for the performance analysis.
The fastest possible running time for any algorithm is O(1), commonly referred to as Constant Running Time. In this case, the algorithm always takes the
same amount of time to execute, regardless of the input size. This is the ideal runtime for an algorithm, but it’s rarely achievable.
In actual cases, the performance (Runtime) of an algorithm depends on n, that is the size of the input or the number of operations is required for each input
item.
The algorithms can be classified as follows from the best-to-worst performance (Running Time Complexity):
A logarithmic algorithm – O(logn)
Runtime grows logarithmically in proportion to n.
A linear algorithm – O(n)
Runtime grows directly in proportion to n.
A superlinear algorithm – O(nlogn)
Runtime grows in proportion to n.
A polynomial algorithm – O(n c)
Runtime grows quicker than previous all based on n.
A exponential algorithm – O(c n)
Runtime grows even faster than polynomial algorithm based on n.
A factorial algorithm – O(n!)
Runtime grows the fastest and becomes quickly unusable for even
small values of n.
Explain switch statement with the help of a program segment. Also write its syntax
Switch statement in C tests the value of a variable and compares it with multiple cases. Once the case match is found, a block of statements associated with that
particular case is executed.Each case in a block of a switch has a different name/number which is referred to as an identifier. The value provided by the user is
compared with all the cases inside the switch block until the match is found.
switch( expression ){
case value-1:
Block-1;
Break;
case value-2:
Block-2;
Break;
case value-n:
Block-n;
Break;
default:
Block-1;
Break;
}
Statement-x;
#include <stdio.h>
int main() {
int num = 8;
switch (num) {
case 7:
printf("Value is 7");
break;
case 8:
printf("Value is 8");
break;
case 9:
printf("Value is 9");
break;
default:
printf("Out of range");
break; }
return 0;}
Differentiate between call-by value and call-by reference using an example program for each.
Call By Value
While calling a function, we pass values of variables to it. Such functions are known as “Call By Values”.
In this method, the value of each variable in calling function is copied into corresponding dummy variables of the called function.
With this method, the changes made to the dummy variables in the called function have no effect on the values of actual variables in the calling function.
#include <stdio.h>
void swapx(int x, int y);
int main(){
int a = 10, b = 20;
swapx(a, b);
printf("a=%d b=%d\n", a, b);
return 0;}
void swapx(int x, int y){
int t;
t = x;
x = y;
y = t;
printf("x=%d y=%d\n", x, y);
}
Thus actual values of a and b remain unchanged even after exchanging the values of x and y.In call-by-values, we cannot alter the values of actual variables
through function calls.Values of variables are passed by the Simple technique.
Call By Reference
While calling a function, instead of passing the values of variables, we pass address of variables(location of variables) to the function known as “Call By
References.In this method, the address of actual variables in the calling function are copied into the dummy variables of the called function.
With this method, using addresses we would have an access to the actual variables and hence we would be able to manipulate them.
#include <stdio.h>
void swapx(int*, int*);
int main(){
int a = 10, b = 20;
swapx(&a, &b);
printf("a=%d b=%d\n", a, b);
return 0;}
void swapx(int* x, int* y){
int t;
t = *x;
*x = *y;
*y = t;
printf("x=%d y=%d\n", *x, *y);}
Thus actual values of a and b get changed after exchanging values of x and y.In call by reference we can alter the values of variables through function calls.
Pointer variables are necessary to define to store the address values of variables.
What are Unions ? Give an example code segm initialize a union and to access a member of a union. Mention the difference between a structure and a
union.
Structures in C is a user-defined data type available in C that allows to combining of data items of different kinds. Structures are used to represent a record.
Defining a structure: To define a structure, you must use the struct statement. The struct statement defines a new data type, with more than or equal to one
member. The format of the struct statement is as follows:
struct [structure name]
{
member definition;
member definition;
...
member definition;
};
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.
Defining a Union: To define a union, you must use the union statement in the same way as you did while defining a structure. The union statement defines
a new data type with more than one member for your program. The format of the union statement is as follows:
};
Define a function in C. List and explain various categories of functions. Also, illustrate a function to find square root of a given n
A function is a block of statements that can perform a particular task. As we all know, there is always at least one function in C, and that is main().Depending on
whether arguments are present or not and whether a value is returned or not, functions are categorized into −
Functions without arguments and without return values
Functions without arguments and with return values
Functions with arguments and without return values
Functions with arguments and with return values
#include <math.h>
#include <stdio.h>
double findSQRT(double N) { return sqrt(N); }
int main(){
int N = 12;
printf("%f ", findSQRT(N));
return 0;}
Define a Variable.? What are the rules to name a vaitiable in C ? How to assign a value to the variable at the time of declaration ?
Variable Definition in C
A variable definition tells the compiler where and how much storage to create for the variable. A variable definition specifies a data type and contains a list of one
or more variables of that type as follows −type variable_list;Here, type must be a valid C data type including char, w_char, int, float, double, bool, or any user-
defined object; and variable_list may consist of one or more identifier names separated by commas. Some valid declarations are shown here −In C, there are
different types of variables (defined with different keywords), for example:int - stores integers (whole numbers), without decimals, such as 123 or -123float –
stores floating point numbers, with decimals, such as 19.99 or -19.99char - stores single characters, such as 'a' or 'B'. Char values are surrounded by single
quotes
int i, j, k;
char c, ch;
float f, salary;
double d;
The line int i, j, k; declares and defines the variables i, j, and k; which instruct the compiler to create variables named i, j and k of type int.Variables can be
initialized (assigned an initial value) in their declaration. The initializer consists of an equal sign followed by a constant expression as follows −