0% found this document useful (0 votes)
172 views

C Programming Language

Uploaded by

Karthikeyan K
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
172 views

C Programming Language

Uploaded by

Karthikeyan K
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 191

C Programming Language

TOPICS FOR TODAY’s SESSION

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

 Can we run a program without a main function in C?


 Yes
 No
Yes we can! Lets see the program in Simplest Way
Macro is defined by #define directive.

Yes! we can run a program without a main function in C


The C preprocessor is a micro processor that is used by compiler to transform your code before
compilation. It is called micro preprocessor because it allows us to add macros.

Macro is defined by #define directive.

#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).

The logic is when you pass (s,t,u,m,p,e,d) as argument it merges the


4th,1st,3rd & the 2nd characters(tokens)
Now look at the third line of the program –
#define begin decode(a,n,i,m,a,t,e)
Here the preprocessor replaces the macro “begin” with the expansion
decode(a,n,i,m,a,t,e). According to the macro definition in the previous line the
argument must be expanded so that the 4th,1st,3rd & the 2nd characters must be
merged. In the argument (a,n,i,m,a,t,e) 4th,1st,3rd & the 2nd characters are ‘m’, ’a’, ’i’ &
‘n’.

So the third line “int begin” is replaced by “in


t main” by the preprocessor before the program is passed on for the compiler. That’s
it…

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

-Integers are used to store whole numbers.


-“int” keyword is used to refer integer data type.
-Integers are whole numbers that can have both zero, positive and negative values.
-The size of int is usually 4 bytes (32 bits).
- It can take 2^32 distinct states from -2147483648 to 2147483647.
EXAMPLE:
int regno=104001;
Integer Data Type(…contd)
-The storage size of int data type is 2 or 4 or 8 byte.
-It varies depending upon the processor in the CPU that we use. 
- If we are using 16 bit processor, 2 byte  (16 bit) of memory will be
allocated for int data type.
-Like wise, 4 byte (32 bit) of memory for 32 bit processor and 8 byte (64
bit) of memory for 64 bit processor is allocated for int datatype.
Size and Range on 32 bit gcc compiler:
DATA TYPE MEMORY (BYTES) RANGE FORMAT SPECIFIER

short int 2 -32,768 to 32,767 %hd


unsigned short int 2 0 to 65,535 %hu

unsigned int 4 0 to 4,294,967,295 %u

-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

unsigned long int 8 0 to 4,294,967,295 %lu

long long int 8 -(2^63) to (2^63)-1 %lld


0 to
unsigned long long
8 18,446,744,073,709, %llu
int
551,615
NOTE:

Range of data types

=>The minimum and maximum range of a signed type is given by


-(2^N-1) to 2^(N-1) - 1
(Where N is sizeof(type) * 8 i.e. total number of bits used by the type)
EXAMPLE:
long long int =>size 8 bytes
N=8*8=64 bits
range is= -(2^(64-1)) to (2^(64-1))-1
=-(2^63) to (2^63)-1
Range of data types
=>The minimum and maximum range of an unsigned
type is given by 0 to (2^N-1) + (2^(N-1) - 1)
EXAMPLE
unsigned short int=>size=2 bytes
N=2*8=16 bits
range is =0 to (2^(16-1))+(2^(16-1))-1
=0 to (2^15)+(2^15)-1
Floating Point Data Type:
-They are used to hold real numbers.
-Floating-point numbers can be represented in exponential or decimal
form.
-It can be either +ve or -ve.
-Floating point data type consists of 2 types. They are,
1.float
2.double
EXAMPLES:
– 254.175,      -16.47  ,-0.5e-7     +4.1e8
 1. FLOAT:
-Float data type allows a variable to store decimal values with
single precision.
-Storage size of float data type is 4. 
-This also varies depend upon the processor in the CPU.
-We can use upto 6 digits after decimal using float data type.
-Example :float a= 10.456789;
2. DOUBLE:
-Double data type is also same as float data type with double
precision.
-It allows up-to 10 digits after decimal.
-The range for double datatype is from 1E–37 to 1E+37.
EXAMPLE: double r=13.456784321;
RANGE AND SIZE OF FLOATING POINT VALUES
Type Storage size Value range Precision

float 4 byte 1.2E-38 to 6 decimal places


3.4E+38

double 8 byte 2.3E-308 to 15 decimal places


1.7E+308

long double 10 byte 3.4E-4932 to 19 decimal places


1.1E+4932
Character Type
-The most basic data type in C
-Character types are used to store characters value.
-Keyword char is used for declaring character type variables
-The size of the character variable is 1 byte.
-Character values are enclosed within single quotes.
Example of character values:‘A’       ‘a’     ‘ b’      ‘8’     ‘#’
Declaration: char ans=‘y’;
Size and Range of character type:
Type Storage Value range
size

char 1 byte -128 to 127 or 0 to 255

unsigned 1 byte 0 to 255


char

signed 1 byte -128 to 127


char
void type
-void is an incomplete type.
-It means "nothing" or "no type".
-void type means no value.
-This is usually used to specify the type of functions which returns
nothing.
-You cannot create variables of void type.
SIZEOF() FUNCTION IN C LANGUAGE:
-sizeof() function is used to find the memory space allocated for each C data
types in bytes.
EXAMPLE:
int a; sizeof(a) =4
char b; sizeof(b)= 1

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?

    void main()


    {
OPTIONS
        float x = 0.1;
        printf("%d, ", x);
A. 0.100000, junk value
        printf("%f", x);
B. junk value, 0.100000
    } 
C. 0.100000, 0
D. 0, 0.100000
Answer: Option B

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?

    void main()


    { OPTIONS
        double x = 123828749.66;
        int y = x; A. 0, 0.0
        printf("%d\n", y); B. 123828749, 123828749.66
        printf("%lf\n", y); C. 123828749, 0.000000
    } D. 12382874, 12382874.0
Answer: Option C

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

•The scanf("%d",&number) statement reads integer number


from the console and stores the given value in number variable.

•The printf("cube of number is:%d


",number*number*number) statement prints the cube of
number on the console.
Variables in C

• A variable is a name of the memory location. It is used to store data.


Its value can be changed, and it can be reused many times.
• It is a way to represent memory location through symbol so that it can
be easily identified.

syntax to declare a variable:


type variable_list; 

• example of declaring the variable


•int a;  
•float b;  
•char c;  
Here, a, b, c are variables. The int, float, char are the
data types.
Variables in C

Rules for defining variables

• A variable can have alphabets, digits, and underscore.


• A variable name can start with the alphabet, and underscore only. It
can't start with a digit.
• No whitespace is allowed within the variable name.
• A variable name must not be any reserved word or keyword, e.g. int,
float, etc.
Variables in C

Types of Variables in C

There are many types of variables in c:


1. local variable
2. global variable
3. static variable
4. automatic variable
5. external variable
6. Register Variable
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  
}  

• You must have to initialize the local variable before it is used.


Variables in C

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

• A keyword is a reserved word. You cannot use it as a variable name,


constant name, etc. There are only 32 reserved words (keywords) in
the C language.
• A list of 32 keywords in the c language is given below:

auto break case char const continue default do

double else enum extern float for goto if


int long register return short signed sizeof static

struct switch typedef union unsigned void volatile while


C Identifiers

• C identifiers represent the name in the C program, for example, variables,


functions, arrays, structures, unions, labels, etc.
• An identifier can be composed of letters such as uppercase, lowercase letters,
underscore, digits, but the starting letter should be either an alphabet or an
underscore.
Internal identifier:
• If the identifier is not used in the external linkage, then it is called as an internal
identifier.
External identifier:
• If the identifier is used in the external linkage, then it is called as an external
identifier.
total, sum, average, _m _, sum_1, etc.
• Example
TCS NQT
PRINTF AND SCANF
1. #include<stdio.h>
int main()
{
char str[25];
printf(" %d ",printf(“SMART"));
return 0;
}
Explanation:Inner printf() will print first and then outer printf will display
the length of the inner printf's string.
OUTPUT: SMART5
2.#include <stdio.h>
int main()
{
int main = 3;
printf("%d", main);
return 0;
}
Explanation: A C program can have same function name and same
variable name.
OUTPUT : 3
3.
#include <stdio.h>
int main()
{
int a, b;
printf("%d", scanf("%d%d",&a,&b));
return 0;
}
Explanation: In C, scanf returns the number of inputs it has successfully
read.
OUTPUT: 2
4. .#include <stdio.h>
int main()
{
printf("%d", main);
return 0;
}
OUTPUT: ADDRESS OF MAIN FUNCTION
#include<stdio.h>
int main()
{
printf("%d", 5.00);
return 0;
}
OUTPUT: 0
when we print the integer with .000 and many zero's as an extension then
output will be 0.
Functions
C Functions

• In c, we can divide a large program into the basic building blocks


known as function.
• The function contains the set of programming statements enclosed by
{}.
• A function can be called multiple times to provide reusability and
modularity to the C program.
• In other words, we can say that the collection of functions creates a
program. The function is also known as procedureor subroutinein
other programming languages.
C Functions

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

There are two types of functions in C programming:


• Library Functions: are the functions which are declared in the C
header files such as scanf(), printf(), gets(), puts(), ceil(), floor() etc.

• User-defined functions: are the functions which are created by the C


programmer, so that he/she can use it many times. It reduces the
complexity of a big program and optimizes the code.
Library Functions
Library Functions

• C Standard library functions or simply C Library functions are inbuilt


functions in C programming.
• The prototype and data definitions of these functions are present in
their respective header files. To use these functions we need to include
the header file in our program. For example,
• If you want to use the printf() function, the header file <stdio.h> should
be included.
• If you try to use printf() without including the stdio.h header file, you
will get an error.
C Header Files
Library Functions <assert.h> Program assertion functions

<ctype.h> Character type functions


Library Functions in Different
<locale.h> Localization functions
Header Files
<math.h> Mathematics functions

<setjmp.h> Jump functions

<signal.h> Signal handling functions

Variable arguments
<stdarg.h>
handling functions

Standard Input/Output
<stdio.h> functions

<stdlib.h> Standard Utility functions

<string.h> String handling functions

<time.h> Date time functions


Library Functions

What will be the output of the program?

#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

What will be the output of the program?

#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

What will be the output of the program?

#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

What will be the output of the program?

#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'.

if((i = memcmp(dest, src, 2))==0) When comparing the


array dest and src as unsigned chars, the first 2 bytes are same in both
variables.so memcmp returns '0'.
Then, the if(0=0) condition is satisfied. Hence the output is "Got it".
Functions in C

What is the notation for following functions?

1. int f(int x, float y) { /* Some code */ } A.1. KR Notation


2. int f(x, y) int x; float y; { /* Some code
2. ANSI Notation
*/ }
B.1. Pre ANSI C Notation
2. KR Notation
C.1. ANSI Notation
2. KR Notation
D.1. ANSI Notation
2. Pre ANSI Notation
Answer: Option C

Explanation:

KR Notation means Kernighan and Ritche Notation.


In KR notation first we need to give prototype declaration then function
call then comes function definition where as in ASCII notation 1st we need
to define the the function defination and then function call.
Functions in C

How many times the program will print “SMART" ?

#include<stdio.h> A. Infinite times


int main()
{ B. 32767 times
printf(“SMART"); C. 65535 times
main();
return 0; D. Till stack overflows
}
Answer: Option D

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

What will be the output of the program?

#include<stdio.h> A. prints "SMART, C-Program“


int main()
{ int a=1; infinitely
if(!a) printf(“SMART,"); B. prints "C-Program" infinetly
else
{ C. prints "C-Program, SMART“
a=0; infinitely
printf("C-Program");
main(); D. Error: main() should
} Not inside else statement
return 0;
}
Answer: Option B

Explanation:

Step 1: int i=1; The variable i is declared as an integer type and initialized


to 1(one).
Step 2: if(!i) Here the !(NOT) operator reverts the i value 1 to 0. Hence
the if(0) condition fails. So it goes to else part.
Step 3: else { i=0; In the else part variable i is assigned to value 0(zero).
Step 4: printf("C-Program"); It prints the "C-program".
Step 5: main(); Here we are calling the main() function.
After calling the function, the program repeats from step 1 to step
5 infinitely.
Hence it prints "C-Program" infinitely.
Functions in C

What will be the output of the program?


#include<stdio.h>
int addmult(int ii, int jj)
{ int kk, ll; A. 12, 12
kk = ii + jj; B. 7, 7
ll = ii * jj;
return (kk, ll); C. 7, 12
} D. 12, 7
int main()
{
int i=3, j=4, k, l;
k = addmult(i, j);
l = addmult(i, j);
printf("%d, %d\n", k, l);
return 0;
}
Answer: Option A
Explanation:
Step 1: int i=3, j=4, k, l; The variables i, j, k, l are declared as an integer
type and variable i, j are initialized to 3, 4 respectively.
The function addmult(i, j); accept 2 integer parameters.
Step 2: k = addmult(i, j); becomes k = addmult(3, 4)
In the function addmult(). The variable kk, ll are declared as an integer
type int kk, ll;
kk = ii + jj; becomes kk = 3 + 4 Now the kk value is '7'.
ll = ii * jj; becomes ll = 3 * 4 Now the ll value is '12'.
return (kk, ll); It returns the value of variable ll only.
The value 12 is stored in variable 'k'.
Step 3: l = addmult(i, j); becomes l = addmult(3, 4)
kk = ii + jj; becomes kk = 3 + 4 Now the kk value is '7'.
ll = ii * jj; becomes ll = 3 * 4 Now the ll value is '12'.
return (kk, ll); It returns the value of variable ll only.
The value 12 is stored in variable 'l'.
Step 4: printf("%d, %d\n", k, l); It prints the value of k and l
Hence the output is "12, 12".
Functions in C

What will be the output of the program?


#include<stdio.h>
#include<stdlib.h>
int main() A. Prints "SMART" 5 times
{ B. Function main() doesn't calls
int a=0;
a++; itself
if(a<=5) C. Infinite loop
{
printf("SMART"); D. Prints "SMART"
exit(1);
main();
}
return 0;
}
Answer: Option D

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

• The string can be defined as the one-dimensional array of characters


terminated by a null ('\0').
• The character array or the string is used to manipulate text such as word or
sentences.
• Each character in the array occupies one byte of memory, and the last
character must always be 0.
• The termination character ('\0') is important in a string since it is the only
way to identify where the string ends.
• When we define a string as char s[10], the character s[10] is implicitly
initialized with the null in the memory.
Ways to declare a String

• There are two ways to declare a string in c language.


o By char array
o By string literal
Example:

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:

    printf("Enter the string?");   Enter the String?


welcome to c
    scanf("%s",s);   welcome
    printf("You entered %s",s);  
}  
Note:

• 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() are declared in the header file stdio.h.


• Both the functions are involved in the input/output operations of the
strings.
• Declaration:
o char[] gets(char[]);
C gets() function

• 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

No. Function Description

1) strlen(string_name) returns the length of string name.


2) strcpy copies the contents of source string to
(destination, source) destination string.
3) strcat(first_string, concats or joins first string with second
second_string) string. The result of the string is stored
in first string.
C String Functions

No. Function Description


4) strcmp(first_string, compares the first string with second
second_string) string. If both strings are same, it
returns 0.
5) strrev(string) returns reverse string.
6) strlwr(string) returns string characters in lowercase.
7) strupr(string) returns string characters in uppercase.
strlen() function

#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

• The string can be defined as the one-dimensional array of characters terminated by a


null ('\0'). The character array or the string is used to manipulate text such as word
or sentences. Each character in the array occupies one byte of memory, and the last
character must always be 0. The termination character ('\0') is important in a string
since it is the only way to identify where the string ends. When we define a string as
char s[10], the character s[10] is implicitly initialized with the null in the memory.

There are two ways to declare a string in c language.


1. By char array
2. By string literal
Arrays
Arrays

• 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

What will be the output of the program ?

#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

What will be the output of the program ?

#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

What will be the output of the program?

#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

What will be the output of the program?

#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

• As p is a pointer of type character, *p will print ‘G’


• Using pointer arithmetic,
*(p+p[3]-p[1]) = *(p+75-69) (Using ascii values of K and E) = *(p+6) = 1(as we know p
is holding the address of base string means 0th poision string, let assume the address
of string starts with 2000 so p+6 means the address of p(we are adding 6 in 2000 that
means 2006, and in 2006 the “1”is stored that is why answer is 1).
Therefore, the output will be G, 1.
Que – 2. Which of the following C code snippet is
not valid?

(A)char* p = “string1”; printf(“%c”, *++p);


(B) char q[] = “string1”; printf(“%c”, *++q);
(C) char* r = “string1”; printf(“%c”, r[1]);
(D) None of the above
Answer: Option (A)

• Solution: Option (A) is valid as p is a pointer pointing to character ‘s’


of “string1”. Using ++p, p will point to character ‘t’ in “string1”.
Therefore, *++p will print ‘t’.
Option (B) is invalid as q being base address of character array, +
+q(increasing base address) is invalid.
Option (C) is valid as r is a pointer pointing to character ‘s’ of “string1”.
Therefore,
• r[1] = *(r+1) = ‘t’ and it will print ‘t’.
Que – 3. Consider the following C program segment: (GATE CS 2004)

char p[20]; The output of the program is:


char *s = "string"; (A) gnirts
int length = strlen(s); (B) gnirt
(C) string
int i;
(D) no output is printed
for (i = 0; i < length; i++)
p[i] = s[length — i];
printf("%s",p);
Answer: Option (D)
• Solution: In the given code, p[20] is declared as a character array and
s is a pointer pointing to a string. The length will be initialized to 6. In
the first iteration of for loop (i = 0),
s t r i n g \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?

a) int strcoll(const char *s1,const char *s2)


b) int strcoll(const char *s1)
c) int strcoll(const *s1,const *s2)
d) int strcoll(const *s1)
Answer: Option (A)

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)

• Declaration: strcmp(const char *s1, const char*s2);


The strcmp return an int value that is
if s1 < s2 returns a value < 0
if s1 == s2 returns 0
if s1 > s2 returns a value > 0
Ques 8. The library function used to find the last occurrence of a character in
a string is

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)

• The function strstr() Finds the first occurrence of a substring in


another string
Declaration: char *strstr(const char *s1, const char *s2);
Return Value:
On success, strstr returns a pointer to the element
in s1 where s2 begins (points to s2 in s1).
On error (if s2 does not occur in s1), strstr returns null.
Ques 10. Which of the following function is correct
that finds the length of a string?
A. int xstrlen(char *s) C.int xstrlen(char *s)
{ int length=0; { int length=0;
while(*s!='\0') while(*s!='\0')
{ length++; s++; length++;
} return (length); return (length);
} }
B.int xstrlen(char s) D.int xstrlen(char *s)
{ int length=0; { int length=0;
while(*s!='\0') while(*s!='\0')
length++; s++; s++;
return (length); return (length);
} }
Answer: Option (A)
• Option A is the correct Example:
#include<stdio.h> int xstrlen(char
function to find the length *s)
of given string. { int length=0;
while(*s!='\0')
{ length++;
• Output: length=8 s++;
} return (length);
}
int main()
{ char d[] = "IndiaBIX";
printf("Length = %d\n", xstrlen(d));
return 0;
}
Ques 11. What will be the output of the following
program?
void main() { A. Equal
char str1[] = "abcd"; B. Unequal
char str2[] = "abcd"; C. Error
if(str1==str2) D. None of these.
printf("Equal");
else
printf("Unequal");
}
Answer: Option B

• 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?

a) Data structure like queue or stack cannot be implemented


b) There are chances of wastage of memory space if elements inserted
in an array are lesser than the allocated size
c) Index value of an array can be negative
d) Elements are sequentially acces
Answer: Option (B)

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.

A) An array size can not changed once it is created.


B) Array element value can be changed any number of times
C) To access Nth element of an array students, use students[n-1] as the
starting index is 0.
D) All the above

Answer: Option (D)


Ques 17. What is the return value of the following statement if it is placed in C
program?

• 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?

• The array int num[26]; A.1


can store 26 elements. B.1, 4
• The expression num[1] C.2, 3
designates the very first D.2, 4
element in the array.
E.None of these
• It is necessary to
initialize the array at
the time of declaration.
• The declaration
num[SIZE] is allowed if
SIZE is a macro.
Answer: Option B

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.

You might also like