C Programming Language
C Programming Language
C
PREPROCESSOR DIRECTIVES
FORMAT SPECIFIERS
DATA TYPES
KEYWORDS
ARRAYS
STRING
1.PREPROCESSOR DIRECTIVES
• A program which processes the source code before it passes through
the compiler is known as preprocessor.
• The commands of the preprocessor are known as preprocessor
directives.
• It is placed before the main().
• It begins with a # symbol.
• They are never terminated with a semicolon.
The preprocessor directives are divided into four
different categories which are as follows:
1. Macro
Syntax:
#define name replacement text
Where,
name – it is known as the micro template.
replacement text – it is known as the macro expansion.
Example : Simple macro
#define LOWER 30
void main()
{
int i;
for (i=1;i<=LOWER; i++)
{
printf("\n%d", i);
}
}
Example : Macros with arguments
#define AREA(a) (3.14 * a * a)
void main()
{
float r = 3.5, x;
x = AREA (r);
printf ("\n Area of circle = %f", x);
}
TEST YOURSELF
Q1.Predict the output for the following program?
#include <stdio.h>
#define printd(x) printf(#x"\n")
int main(void)
{
printd("Hi");
return 0;
}
a) Hi
b) "Hi"
c) Compile time error
d) None of the above
Ans : B
Explanation: As we declare the printing statement in #define as a
parameter. So it print “Hi” in the printd method.
2.. Predict the output for the following program?
#include <stdio.h>
#define sqr(a) a * a;
int main(void)
{
printf("%d\n", sqr(3 * 2));
return 0;
}
a) 9
b) 5
c) 6
d) Compile error
Ans: d
Explanation: As the declaration of #define sqr(a) a*a is wrong instead of
that you have to declare the statement as #define sqr(a) (a *(a)) to get the
desired output as 36.
(3) (3*(2))
((3+3)*(2))
((6)*2)= 36
Interview Question in C
#include<stdio.h>
#define start main
void start()
{
printf("Hello, World!!!");
}
Lets see the program internally!!!
It shows how a programmer can defy the very important rule of having a
main() in c program and still make the program run. This illustrates the
concept on a simple program though it can be scaled to much bigger and
more complex programs.
#include<stdio.h>
#define decode(s,t,u,m,p,e,d) m##s##u##t
#define begin decode(a,n,i,m,a,t,e)
int begin()
{
printf(” hello “);
}
This program runs without main().
how??
Here we are using preprocessor(a program which processes the source code before compilation.) directive #define with arguments
to give an impression that the program runs without main. But in reality it runs with a hidden main function.
The ‘##‘ operator is called the token pasting or token merging operator. That is we can merge two or more characters with it.
This program runs without main().
how??
Here we are using preprocessor(a program which processes the source code before compilation.) directive #define with arguments
to give an impression that the program runs without main. But in reality it runs with a hidden main function.
The ‘##‘ operator is called the token pasting or token merging operator. That is we can merge two or more characters with it.
In the 2nd line of the program-
#define decode(s,t,u,m,p,e,d) m##s##u##t
What is the preprocessor doing here. The macro decode(s,t,u,m,p,e,d) is
being expanded as “msut” (The ## operator merges m,s,u & t into msut).
So actually C program can never run without a main() . We are just disguising the
main() with the preprocessor, but actually there exists a hidden main function in
the program.
DATA TYPES IN C
DATA TYPES
-C data types are defined as the data storage format that a
variable can store a data to perform a specific operation.
-Data types are used to define a variable before to use in a
program.
-Size of variable, constant and array are determined by data
types.
MODIFIERS IN C LANGUAGE:
-The amount of memory space to be allocated for a variable is derived by
modifiers.
-Modifiers are prefixed with basic data types to modify (either increase or
decrease) the amount of storage space allocated to a variable.
-There are 5 modifiers available in C language. They are,
1.short
2.long
3.signed
4.unsigned
5.long long
Example:
-Storage space for int data type is 4 byte for 32 bit processor.
-We can increase the range by using long int which is 8 byte.
-We can decrease the range by using short int which is 2 byte.
Integer Data Type
-2,147,483,648 to
int 4 %d
2,147,483,647
-2,147,483,648 to
long int 8 %ld
2,147,483,647
float c; sizeof(c)= 4
double d; sizeof(d)= 8
ENUMERATION:
-Enumeration is a user defined datatype in C language.
-Enumeration data type consists of named integer constants as a list.
-It start with 0 (zero) by default and value is incremented by 1 for the
sequential identifiers in the list.
-It is used to assign names to the integral constants which makes a
program easy to read and maintain.
-The keyword “enum” is used to declare an enumeration.
Syntax:
enum enum_name{const1, const2, ....... };
EXAMPLE:
enum week{sunday, monday, tuesday, wednesday,
thursday, friday, saturday};
enum week day;
day=friday
printf(“%d”,day);
OUTPUT: 5
EXAMPLE:
enum MONTH { Jan = 20, Feb, Mar };
Jan is assigned to 20. Feb and Mar variables will
be assigned to 21 and 22 respectively by default
enum MONTH month = Mar;
if(month == 20)
printf("Value of Jan");
else if(month == 21)
printf("Month is Feb");
if(month == 22)
printf("Month is Mar")
TCS NQT MCQs
DATATYPES
1.What is the output of this C code?
OPTIONS
int main()
{
A. 128
char chr;
B. - 128
chr = 128;
C. Depends on the compiler
printf("%d\n", chr);
D. None of the mentioned
return 0;
}
Answer: Option B
Explanation:
signed char will be a negative number.
Output:
$ cc pgm2.c
$ a.out
-128
2. Predict the output of this C code?
int main()
OPTIONS
{
float f1 = 0.1;
A. equal
if (f1 == 0.1)
B. not equal
printf("equal\n");
C. Output depends on compiler
else
D. None of the mentioned
printf("not equal\n");
}
Answer: Option B
Explanation:
0.1 by default is of type double which has different representation
than float resulting in inequality even after conversion.
Output:
$ cc pgm4.c
$ a.out
not equal
3. Predict the output of this C code?
union Student
{
int marks; OPTIONS
char grade;
}; A. 8
int main() B. 5
{ C. 9
union Student s; D. 4
printf("%d", sizeof(s));
return 0;
}
Answer: Option D
Explanation:
Since the size of a union is the size of its maximum datatype, here int
is the largest hence 4.
Output:
$ cc pgm7.c
$ a.out
4
4. Predict the output of this C code?
int main()
{
OPTIONS
float x = 'a';
printf("%f", x);
A. a
return 0;
B. a.00000
}
C. Run time error
D. 97.000000
Answer: Option D
Explanation:
Since the ASCII value of a is 97, the same is assigned to the float
variable and printed.
Output:
$ cc pgm8.c
$ a.out
97.000000
5. Predict the output of this C code?
int main()
{
short int i = 20;
char c = 97; OPTIONS
printf("%d, %d, %d\n", sizeof(i), sizeof(c), sizeof(c + i));
return 0; A. 2, 1, 2
} B. 2, 1, 1
C. 2, 1, 4
D. 2, 2, 8
Answer: Option C
Explanation:
As you know size of data types is compiler dependent in c. The size of data type
in 2 bytes compilers is as follow:
char : 1 byte
int : 2 byte
float : 4 byte
double : 8 byte
6. Predict the output of this C code?
int main()
{ OPTIONS
int a[5] = {1, 2, 3, 4, 5};
int i; A. The compiler will flag an error
for (i = 0; i < 5; i++) B. Program will compile and print the output 5
if ((char)a[i] == '5') C. Program will compile and print the ASCII value of 5
printf("%d\n", a[i]); D. Program will compile and print FAIL for 5 times
else
printf("FAIL\n");
}
Answer: Option D
Explanation:
The ASCII value of 5 is 53, the char type-casted integral value 5 is 5 only.
Output:
$ cc pgm1.c
$ a.out
FAIL
FAIL
FAIL
FAIL
FAIL
7. Predict the output of this C code?
For union
union temp
OPTIONS
{
char a;
A. char
int b;
B. int
float c;
C. float
};
D. Both (B) and (C)
The size is decided by:
Answer: Option D
Explanation:
According to the implementation of the integer and floating point
variable the size of union depends on both int and float datatype
8. Predict the output of this C code?
int main()
{
OPTIONS
float a = 5.477777777777;
printf("%f", a);
A. 5.477777
}
B. 5.477778
C. 5.478
D. 5.48
Answer: Option A
Explanation:
Floating point variable can store upto 6 digits after precision
9. Predict the output of this C code?
Explanation:
When you format floating point number to an integer format, junk
value will be printed and %f prints the floating point number with
6digits after precision
10. Predict the output of this C code?
Explanation:
When you assign double value to an integer variable the decimal value
is stored so when you print it with %d we get the number without
precision and %lf format will print 0.000000
printf() and scanf() in C
• The printf() and scanf() functions are used for input and output in C language.
Both functions are inbuilt library functions, defined in stdio.h (header file).
printf() function
• The printf() function is used for output. It prints the given statement to the
console.
printf("format string",argument_list);
scanf() function
• The scanf() function is used for input. It reads the input data from the
console.
scanf("format string",argument_list);
Program to print cube of given number
#include<stdio.h>
int main(){
int num;
printf("enter a number:");
scanf("%d",&num);
printf("cube of number is:%d ",num*num*num);
return 0;
}
Output
enter a number:5
cube of number is:125
Program to print cube of given number
Types of Variables in C
Local Variable
• A variable that is declared inside the function or block is called a local
variable.
• It must be declared at the start of the block.
void function1(){
int x=10;//local variable
}
Global Variable
• A variable that is declared outside the function or block is called a
global variable. Any function can change the value of the global
variable. It is available to all the functions.
• It must be declared at the start of the block.
int value=20;//global variable
void function1(){
int x=10;//local variable
}
Variables in C
Static Variable
• A variable that is declared with the static keyword is called static variable.
• It retains its value between multiple function calls.
void function1(){
int x=10;//local variable
static int y=10;//static variable
x=x+1;
y=y+1;
printf("%d,%d",x,y);
}
• The local variable will print the same value for each function call, e.g, 11,11,11 and
so on. But the static variable will print the incremented value in each function call,
e.g. 11, 12, 13 and so on.
Variables in C
Automatic Variable
• All variables in C that are declared inside the block, are automatic
variables by default. We can explicitly declare an automatic variable
using auto keyword.
void main(){
int x=10;//local variable (also automati
c)
auto int y=20;//automatic variable
}
External Variable
• We can share a variable in multiple C source files by using an external
variable. To declare an external variable, you need to use extern keyword.
extern int x=10;//external variable (also global)
Keywords in C
Function Aspects
• Function declaration A function must be declared globally in a c program to tell the compiler
about the function name, function parameters, and return type.
•
Function call Function can be called from anywhere in the program. The parameter list must not
differ in function calling and function declaration. We must pass the same number of functions as
it is declared in the function declaration.
•
Function definition It contains the actual statements which are to be executed. It is the most
important aspect to which the control comes when the function is called. Here, we must notice
that only one value can be returned from the function.
C Functions
Function Aspects
SN C function aspects Syntax
1 Function declaration return_type function_name
(argument list);
2 Function call function_name
(argument_list)
3 Function definition return_type function_name
(argument list) {function
body;}
syntax
return_type function_name(data_type parameter...){
//code to be executed
}
C Functions
Types of Functions
Variable arguments
<stdarg.h>
handling functions
Standard Input/Output
<stdio.h> functions
#include<stdio.h> A. How r u
int main() 7
{ 2
int a; B. How r u
a = printf("How r u\n"); 8
a = printf("%d\n", a); 2
printf("%d\n", a); C. How r u
return 0; 1
} 1
D. Error: cannot assign printf to
variable
Answer: Option B
Explanation:
In the program, printf() returns the number of charecters printed on the consolei
= printf("How r u\n"); This line prints "How r u" with a new line character and
returns the length of string printed then assign it to variable i.
So i = 8 (length of '\n' is 1).
i = printf("%d\n", i); In the previous step the value of i is 8. So it prints "8" with a
new line character and returns the length of string printed then assign it
to variable i. So i = 2 (length of '\n' is 1).
printf("%d\n", i); In the previous step the value of i is 2. So it prints "2".
Library Functions
#include<stdio.h>
A. 2, 3
#include<math.h>
B. 2.000000, 3
int main()
C. 2.000000, 0
{
D. 2, 0
float a = 2.5;
printf("%f, %d", floor(a), ceil(a)); return
0;
}
Answer: Option C
Explanation:
Both ceil() and floor() return the integer found as a double.
floor(2.5) returns the largest integral value(round down) that is not
greater than 2.5. So output is 2.000000.
ceil(2.5) returns 3, while converting the double to int it returns '0'.
So, the output is '2.000000, 0'.
Library Functions
#include<stdio.h> #include<stdlib.h>
int main() A. 55, 55.555
{ B. 66, 66.666600
char *i = "55.555"; C. 65, 66.666000
int r1 = 10; D. 55, 55
float r2 = 11.111;
r1 = r1+atoi(i); r2 = r2+atof(i);
printf("%d, %f", r1, r2);
return 0;
}
Answer: Option C
Explanation:
Function atoi() converts the string to integer.
Function atof() converts the string to float.
result1 = result1+atoi(i);
Here result1 = 10 + atoi(55.555);
result1 = 10 + 55;
result1 = 65;
result2 = result2+atof(i);
Here result2 = 11.111 + atof(55.555);
result2 = 11.111 + 55.555000;
result2 = 66.666000;
So the output is "65, 66.666000" .
Library Functions
#include<stdio.h> #include<string.h>
int main() A. Missed
{ B. Got it
char dest[] = {97, 97, 0}; C. Error in memcmp statement
char src[] = "aaa"; D. None of above
int i;
if((i = memcmp(dest, src, 2))==0)
printf("Got it");
else
printf("Missed");
return 0;
}
Answer: Option B
Explanation:
memcmp compares the first 2 bytes of the blocks dest and src as unsigned
chars. So, the ASCII value of 97 is 'a'.
Explanation:
Explanation:
A call stack or function stack is used for several related purposes, but the
main reason for having one is to keep track of the point to which each
active subroutine should return control when it finishes executing.
A stack overflow occurs when too much memory is used on the call stack.
Here function main() is called repeatedly and its return address is stored
in the stack. After stack memory is full. It shows stack overflow error.
Functions in C
Explanation:
Explanation:
Step 1: int i=0; The variable i is declared as in integer type and initialized
to '0'(zero).
Step 2: i++; Here variable i is increemented by 1. Hence i becomes
'1'(one).
Step 3: if(i<=5) becomes if(1 <=5). Hence the if condition is satisfied and
it enter into if block statements.
Step 4: printf("SMART"); It prints "SMART".
Step 5: exit(1); This exit statement terminates the program execution.
Hence the output is "SMART".
Strings
STRINGS IN C
Eg: char ch[10]={‘w', ‘e', ‘l', ‘c', ‘o', ‘m', ‘e', '\0'};
• array index starts from 0, so it will be represented as in the figure given below.
w e l c o m e ‘\0’
• While declaring string, size is not mandatory. So we can write the above code as
given below:
• char ch[]={‘w', ‘e', ‘l', ‘c', ‘o', ‘m', ‘e‘,'\0'};
• We can also define the string by the string literal in C language. For example:
Eg: char ch[]=“welcome";
• In such case, '\0' will be appended at the end of the string by the compiler.
Difference between char array and string literal
• There are two main differences between char array and literal.
o We need to add the null character '\0' at the end of the array by our self
whereas, it is appended internally by the compiler in the case of the
character array.
o The string literal cannot be reassigned to another set of characters
whereas, we can reassign the characters of the array.
String Example in C
#include<stdio.h>
#include <string.h>
int main(){
char ch[11]={‘w', ‘e', ‘l', ‘c', ‘o', ‘m', ‘e‘,'\0'};
char ch2[11]=“welcome";
printf("Char Array Value is: %s\n", ch);
printf("String Literal Value is: %s\n", ch2);
return 0;
}
Accepting string as the input
#include<stdio.h>
void main ()
{
char s[20]; Output:
• points which must be noticed while entering the strings by using scanf.
o The compiler doesn't perform bounds checking on the character array.
Hence, there can be a case where the length of the string can exceed the
dimension of the character array which may always overwrite some
important data.
o Instead of using scanf, we may use gets() which is an inbuilt function defined
in a header file string.h. The gets() is capable of receiving only one string at a
time.
Pointers with strings
Output:
#include<stdio.h> welcome
void main ()
{
char s[11] = “welcome";
char *p = s; // pointer p is pointing to string s.
printf("%s",p); // the string welcome is printed if we print p.
}
copy the content of a string into another
Output:
#include<stdio.h> welcome to c
void main () Copying the content of p into q...
welcome to c
{
char *p = “welcome to c";
printf("String p: %s\n",p);
char *q;
printf("copying the content of p into q...\n");
q = p;
printf("String q: %s\n",q);
}
Re-assignning to another set of characters
Output:
#include<stdio.h> C programming
hello
void main ()
{
char *p = “C programming";
printf("Before assigning: %s\n",p);
p = "hello";
printf("After assigning: %s\n",p);
}
C gets() functions
• The gets() function enables the user to enter some characters followed
by the enter key.
• All the characters entered by the user get stored in a character array.
The null character is added to the array to make it a string.
• The gets() allows the user to enter the space-separated strings.
• It returns the string entered by the user.
Example:
Output:
#include<stdio.h> Welcome to c
Welcome to c
void main ()
{
char s[30];
printf("Enter the string? ");
gets(s);
printf("You entered %s",s);
}
fgets()
Output:
Enter the string? C programming is
#include<stdio.h> the best
C programming is the
void main()
{
char str[20];
printf("Enter the string? ");
fgets(str, 20, stdin);
printf("%s", str);
}
C String Functions
#include<stdio.h>
#include <string.h>
int main(){
char ch[20]={‘s’,’m’,’a’,’r’,’t’, '\0'};
printf("Length of string is: %d",strlen(ch));
return 0;
}
Output:
Length of string is: 5
strcpy()
#include<stdio.h>
#include <string.h>
int main(){
char ch[20]={‘s’,’m’,’a’,’r’,’t’, '\0'};
char ch2[20];
strcpy(ch2,ch);
printf("Value of second string is: %s",ch2);
return 0;
}
Output:
Value of second string is: smart
C String Concatenation: strcat()
#include<stdio.h>
#include <string.h>
int main(){
char ch[10]={'h', 'e', 'l', 'l', 'o', '\0'};
char ch2[10]={'c', '\0'};
strcat(ch,ch2);
printf("Value of first string is: %s",ch);
return 0;
}
Value of first string is: hello
C Compare String: strcmp()
#include<stdio.h>
Output:
#include <string.h>
int main(){ Enter 1st string: hello
Enter 2nd string: hello Strings are
char str1[20],str2[20]; equal
printf("Enter 1st string: ");
gets(str1);//reads string from console
printf("Enter 2nd string: ");
gets(str2);
if(strcmp(str1,str2)==0)
printf("Strings are equal");
else
printf("Strings are not equal");
return 0;
}
C Reverse String: strrev()
#include<stdio.h> Output:
#include <string.h>
Enter string: smart
int main(){ String is: smart
char str[20]; Reverse String is: trams
printf("Enter string: ");
gets(str);//reads string from console
printf("String is: %s",str);
printf("\nReverse String is: %s",strrev(str));
return 0;
}
C String Lowercase: strlwr()
#include<stdio.h> Output:
#include <string.h> Enter string: SMARTprogramming
String is: SMARTprogramming
int main(){ Lower String is: smartprogramming
char str[20];
printf("Enter string: ");
gets(str);//reads string from console
printf("String is: %s",str);
printf("\nLower String is: %s",strlwr(str));
return 0;
}
C String Uppercase: strupr()
#include<stdio.h> Output:
#include <string.h> Enter string: smart
String is: smart
int main(){ Upper String is:SMART
char str[20];
printf("Enter string: ");
gets(str);//reads string from console
printf("String is: %s",str);
printf("\nUpper String is: %s",strupr(str));
return 0;
}
C Strings
• An array is defined as the collection of similar type of data items stored at contiguous
memory locations. Arrays are the derived data type in C programming language which
can store the primitive type of data such as int, char, double, float, etc. It also has the
capability to store the collection of derived data types, such as pointers, structure, etc.
• The array is the simplest data structure where each data element can be randomly
accessed by using its index number.
• C array is beneficial if you have to store similar elements.
• For example, if we want to store the marks of a student in 6 subjects, then we don't need
to define different variables for the marks in the different subject. Instead of that, we can
define an array which can store the marks in each subject at the contiguous memory
locations.
• By using the array, we can access the elements easily. Only a few lines of code are
required to access the elements of the array.
Arrays
Properties of Array
The array contains the following properties.
1. Each element of an array is of same data type and carries the same size, i.e., int
= 4 bytes.
2. Elements of the array are stored at contiguous memory locations where the
first element is stored at the smallest memory location.
3. Elements of the array can be randomly accessed since we can calculate the
address of each element of the array with the given base address and the size
of the data element.
Arrays
Declaration of C Array
• We can declare an array in the c language in the following way.
data_type array_name[array_size];
Example
int marks[5];
Initialization of C Array
The simplest way to initialize an array is by using the index of each element. We
can initialize each element of the array by using the index. Consider the following
marks[0]=80;//initialization o
example.
f array
marks[1]=60;
marks[2]=70;
marks[3]=85;
marks[4]=75;
Arrays
#include<stdio.h>
int main() A.2, 1, 15
{
B.1, 2, 5
int a[5] = {5, 1, 15, 20, 25};
int i, j, m; i = ++a[1]; C.3, 2, 15
j = a[1]++;
D.2, 3, 20
m = a[i++];
printf("%d, %d, %d", i, j, m);
return 0;
}
Answer: Option C
Explanation:
Step 1: int a[5] = {5, 1, 15, 20, 25}; The variable arr is declared as an integer array with a size of 5
and it is initialized to
a[0] = 5, a[1] = 1, a[2] = 15, a[3] = 20, a[4] = 25 .
Step 2: int i, j, m; The variable i,j,m are declared as an integer type.
Step 3: i = ++a[1]; becomes i = ++1; Hence i = 2 and a[1] = 2
Step 4: j = a[1]++; becomes j = 2++; Hence j = 2 and a[1] = 3.
Step 5: m = a[i++]; becomes m = a[2]; Hence m = 15 and i is incremented by 1(i++ means 2++ so
i=3)
Step 6: printf("%d, %d, %d", i, j, m); It prints the value of the variables i, j, m
Hence the output of the program is 3, 2, 15
Arrays
#include<stdio.h>
void fun(int **p);
int main() A. 1
{ B. 2
int a[3][4] = {1, 2, 3, 4, 4, 3, 2, 8, 7, 8, 9, 0};
int *ptr; ptr = &a[0][0]; C. 3
fun(&ptr); return 0; D. 4
}
void fun(int **p)
{
printf("%d\n", **p);
}
Answer: Option A
Explanation:
Step 1: int a[3][4] = {1, 2, 3, 4, 4, 3, 2, 8, 7, 8, 9, 0}; The variable a is declared as an multidimensional
integer array with size of 3 rows 4 columns.
Step 2: int *ptr; The *ptr is a integer pointer variable.
Step 3: ptr = &a[0][0]; Here we are assigning the base address of the array a to the pointer
variable *ptr.
Step 4: fun(&ptr); Now, the &ptr contains the base address of array a.
Step 4: Inside the function fun(&ptr); The printf("%d\n", **p); prints the value '1'.
because the *p contains the base address or the first element memory address of the array a (ie. a[0])
**p contains the value of *p memory location (ie. a[0]=1).
Hence the output of the program is '1'
Arrays
What will be the output of the program if the array begins 1200 in memory?
#include<stdio.h>
int main()
{ A.1200, 1202, 1204
int arr[]={2, 3, 4, 1, 6}; B.1200, 1200, 1200
printf("%u, %u, %u\n", arr, &arr[0], &arr);
return 0; C.1200, 1204, 1208
} D.1200, 1202, 1200
Answer: Option B
Explanation:
Step 1: int arr[]={2, 3, 4, 1, 6}; The variable arr is declared as an integer array and
initialized.
Step 2: printf("%u, %u, %u\n", arr, &arr[0], &arr); Here,
The base address of the array is 1200.
=> arr, &arr is pointing to the base address of the array arr.
=> &arr[0] is pointing to the address of the first element array arr. (ie. base
address)
Hence the output of the program is 1200, 1200, 1200
Arrays
#include<stdio.h>
int main()
{ A.5
float arr[] = {12.4, 2.3, 4.5, 6.7}; B.4
printf("%d\n", sizeof(arr)/sizeof(arr[0]));
return 0; C.6
} D.7
Answer: Option B
Explanation:
The sizeof function return the given variable. Example: float a=10; sizeof(a) is 4 bytes
Step 1: float arr[] = {12.4, 2.3, 4.5, 6.7}; The variable arr is declared as an floating point
array and it is initialized with the values.
Step 2: printf("%d\n", sizeof(arr)/sizeof(arr[0]));
The variable arr has 4 elements. The size of the float variable is 4 bytes.
Hence 4 elements x 4 bytes = 16 bytes
sizeof(arr[0]) is 4 bytes
Hence 16/4 is 4 bytes
Hence the output of the program is '4'.
Arrays
#include<stdio.h>
int main()
{ A.1
int arr[1]={10}; B.10
printf("%d\n", 0[arr]);
return 0; C.0
} D.6
Answer: Option B
Explanation:
Step 1: int arr[1]={10}; The variable arr[1] is declared as an integer array
with size '2' and it's first element is initialized to value
'10'(means arr[0]=10)
Step 2: printf("%d\n", 0[arr]); It prints the first element value of the
variable arr.
Hence the output of the program is 10.
Answer: Option B
Explanation:
Step 1: int arr[1]={10}; The variable arr[1] is declared as an integer array
with size '2' and it's first element is initialized to value
'10'(means arr[0]=10)
Step 2: printf("%d\n", 0[arr]); It prints the first element value of the
variable arr.
Hence the output of the program is 10.
TCS NQT ARRAYS AND STRING
Que – 1. What does the following fragment of C-
program print?
(A) T, 1
char c[] = “TEST2020"; (B) T, T
char *p =c; (C) TEST2020
printf("%c,%c", *p,*(p+p[3]- (D) None of the above
p[1]));
Answer: option (A)
• Solution: As given in the question, p points to character array c[] which can be
represented as: T E S T 2 0 2 0 \0
s
• p[i] = s[6-0] and s[6] is ‘\0’
Therefore, p[0] becomes ‘\0’. As discussed, ‘\0’ means end of string.
Therefore, nothing is printed as first character of string is ‘\0’.
Que – 4. What will be the output of the following
C code?
const char a) First matching character
str1[]="ABCDEF1234567"; is at 8
const char str2[] = "269"; b) First matching character
len = strcspn(str1, str2); is at 7
printf("First matching c) First matching character
character is at %d\n", len is at 9
+ 1); d) First matching character
is at 12
Answer: Option (A)
Explanation:
size_t strcspn(const char *str1, const char *str2) is used to calculate
the length of the initial segment of str1, which consists entirely of
characters not in str2.
Que – 5. Which of the following is the variable type
defined in header string. h?
a) sizet
b) Size
c) size_t
d) size-t
Answer: Option(C)
Explanation:
This is the unsigned integral type and is the result of the sizeof keyword.
Ques 6. What is the prototype of strcoll() function?
Explanation:
The prototype of strcoll() function is int strcoll(const char *s1,const
char *s2).
Ques 7. If the two strings are identical, then strcmp() function returns
A. -1
B. 1
C. 0
D. Yes
Answer: Option (C)
A. strnstr()
B. laststr()
C. strrchr()
D. strstr()
Answer: Option C
Explanation:
• Declaration: char *strrchr(const char *s, int c);
• It scans a string s in the reverse direction, looking for a specific
character c.
Ques 9. Which of the following function is used to find the first occurrence of
a given string in another string?
A. strchr()
B. strrchr()
C. strstr()
D. strnset()
Answer: Option (C)
• Solution:
Strings are compared using strcmp() function defined
under string.h header file.
Ques 12. What will be the output of the program ?
#include<stdio.h> A. 3, 2, 15
void main() { B. 2, 3, 20
int a[5] = {5, 1, 15, 20, 25}; C. 2, 1, 15
int i, j, m; D. 1, 2, 5
i = ++a[1];
j = a[1]++;
m = a[i++];
printf("%d, %d, %d", i, j, m);
}
Answer: Option A
Solution:
>> int a[5] = {5, 1, 15, 20, 25}; The variable arr is declared as an integer array with a
size of 5 and it is initialized to
a[0] = 5, a[1] = 1, a[2] = 15, a[3] = 20, a[4] = 25.
>> int i, j, m; The variable i, j, m are declared as an integer type.
>> i = ++a[1]; becomes i = ++1; Hence i = 2 and a[1] = 2
>> j = a[1]++; becomes j = 2++; Hence j = 2 and a[1] = 3.
>> m = a[i++]; becomes m = a[2]; Hence m = 15 and i is incremented by 1(i++ means
2++ so i=3)
>> printf("%d, %d, %d", i, j, m); It prints the value of the variables i, j, m
Hence the output of the program is 3, 2, 15.
Ques 13. What will be the output of following
program code?
A. 5
#include <stdio.h>
int main(void) {
B. 6
char p; C. 9
char buf[10] = {1, 2, 3, 4, 5, 6, 9, 8}; D. Error
p = (buf + 1)[5];
printf("%d", p); E. None of the above
return 0;
}
Answer: Option C
• Solution:
x[i] is equivalent to *(x + i),
so (buf + 1)[5] is *(buf + 1 + 5), i.e. buf[6].
14.Let x be an array. Which of the following operations are illegal?
I. ++x A. I and II
II. x+1 B. I, II and III
III. x++ C. II and III
IV. x*2 D. I, III and IV
E. III and IV
Answer: Option D
• Solution:
int x[10]; * x will store the base address of array. *
Statement I, III and IV is invalid.
Statement I and III : ++x and x++ are throwing en error while compile (lvalue
required as increment operand )
Since, x is storing in the address of the array which is static value which cannot be
change by the operand.
Statement IV : x*2 is also throw an error while compile (invalid operands to binary
* (have 'int *' and 'int') )
Statement II : x+1 is throw a warning: assignment makes integer from pointer
without a cast [enabled by default]
Ques 15. What are the disadvantages of arrays?
Explanation:
Arrays are of fixed size. If we insert elements less than the allocated
size, unoccupied positions can’t be used again. Wastage will occur in
memory.
Ques 16. Choose a correct statement about C language arrays.
• strcmp("ABC", "ABC");
A. 33
B. -1
C. 1
D. 0
E. Compilation Error
Answer: Option D
• Solution:
strcmp(s1, s2);
returns int as follows:
== 0, when s1 == s2
< 0, when s1 < s2
> 0, when s1 > s2
Ques 18. What will be the output of the program if
the array begins at address 65486?
A.65486, 65488
#include void main() B.65486, 65490
{ C.65486, 65487
int arr[] = {12, 14, 15, 23, D.65486, 65486
45}; E.None of these
printf("%u, %u", arr,
&arr);
}
Answer: Option D
• Solution:
>> int arr[] = {12, 14, 15, 23, 45}; The variable arr is declared as an
integer array and initialized.
>> printf("%u, %u", arr, &arr); Here,
The base address of the array is 65486.
=> arr, &arr is pointing to the base address of the array arr.
Hence the output of the program is 65486, 65486.
Ques 19. Which of the following is correct way to
define the function fun() in the below program?#
include<stdio.h> • A.void fun(int p[][4]){}
void main() • B.void fun(int *p[4]){}
{ • C.void fun(int *p[][4]){}
int a[3][4]; • D.void fun(int *p[3][4]){}
fun(a); • E.None of these
}
Answer: Option A
• Solution:
void fun(int p[][4]){ } is the correct way to write the function fun().
while the others are considered only the function fun() is called by
using call by reference.
Ques 20.Which of the following statements are correct about an array?
Solution:
• The array int num[26]; can store 26 elements. This statement is true.
• The expression num[1] designates the very first element in the array. This
statement is false, because it designates the second element of the array.
• It is necessary to initialize the array at the time of declaration. This
statement is false.
• The declaration num[SIZE] is allowed if SIZE is a macro. This statement is
true, because the MACRO just replaces the symbol SIZE with given value.
Hence the statements '1' and '4' are correct statements.