1. What is C language?

The C programming language is a standardized programming language developed in the early 1970s by Ken Thompson and Dennis Ritchie for use on the UNIX operating system. 

Uses:

  • Operating system development

  • Compilers and Assemblers

  • Network drivers

  • Interpreters

2.printf() Function.
What is the output of printf(“%d”)?

In C programming language, printf() function is used to print the (“character, string, float, integer, octal and hexadecimal values”) onto the output screen and returns the number of characters it successfully prints on the console. 

The output of printf(“%d”) is garbage.

3. What is the difference between “calloc(…)” and “malloc(…)”?

The name malloc and calloc() are library functions that allocate memory dynamically. It means that memory is allocated during runtime(execution of the program) from the heap segment.

malloc() in C
“malloc” or “memory allocation” method in C is used to dynamically allocate a single large block of memory with the specified size. It returns a pointer of type void which can be cast into a pointer of any form. It initializes each block with default garbage value.

Syntax:
ptr = (cast-type*) malloc(byte-size);

For Example:
ptr = (int*) malloc(100 * sizeof(int));

Since the size of int is 4 bytes, this statement will allocate 400 bytes of memory. And, the pointer ptr holds the address of the first byte in the allocated memory.

calloc() in C
“calloc” or “contiguous allocation” method in C is used to dynamically allocate the specified number of blocks of memory of the specified type. It initializes each block with a default value ‘0’.

Syntax:
ptr = (cast-type*)calloc(n, element-size);

For Example:
ptr = (float*) calloc(25, sizeof(float));

This statement allocates contiguous space in memory for 25 elements each with the size of the float.

4. printf() Function- What is the difference between “printf(…)” and”sprintf(…)”?
sprintf(…) writes data to the character array whereas printf(…) writes data to the standard output device.

5. Compilation How to reduce a final size of executable?
Size of the final executable can be reduced using dynamic linking for libraries.

6. POP(Procedural Oriented Programming Language) Vs OOP(Object Oriented Programming Language).

POP(Procedural Oriented Programming Language)
a.Structure oriented.
b.Program is divided into function.
c.Top-down approach.
d.Inheritence is not allowed.
e.It does not use access specifier.
f.No data hiding.
g.No virtual function.
h.Example:C,Pascal.


OOP(Object Oriented Programming Language)
a.Object oriented.
b.Program is divided into object.
c.Bottom-up approach.
d.Inheritance property is used.
e.It uses access specifier.
f.Encapsulation is used to hide data.
g.Concept of virtual data.
h.Example:C++,Java.

 

7. What is token in C?

Each and every smallest individual unit in C program are known as C tokens.

C tokens are of six types. C supports following tokens:
1.Keywords: Words which are specific to the C language.[Ex- int,while]
2.Identifiers: User defined names/abbreviations. [Ex- main,total]
3.Constants:Values which dont change.[Ex-10,20]
4.Strings: Sequence of characters.[Ex-“hello”,”c program”]
5.Operators: Act on operands and generates output.[Ex: +,-,/,*]
6.Special symbols:[Ex- (),{},#]

8. What is keywords?

All keywords are basically the sequences of character that have a particular meaning.
a. Keywords are reserved words.[It must have special meaning]
b. In c there are 32 keywords.
c. All keywords are written in lowercases.
Example: int,default,while,break,continue.

9. How many keywords in C?

32.

10. What is constants?

Fixed values that do not change during execution of a C program.

Constants:- i)Numeric Constants[a)Integer,b)Real]
ii)Character Constants[a)Single Character Contants,b)String Contants]

11. Types of operator in C?

  1. Arithmetic operators

  2. Relational operators

  3. Logical operators

  4. Bitwise operators

  5. Assignment operators

  6. Conditional operators

  7. Special operators

  8. Unary Operator

12. Character array Vs string.

13. Datatype in c.

i)Datatypes in C language are defined as the data storage format that a variable can store data to perform a specific operation.
ii)Datatypes are used to define a variable before using it in a program.
iii)Size of variable, constant, and array are determined by data types.
Example:char,int,short,long.

14. Size of the datatype.

char:1 byte,int:2/4 bytes,short:2 bytes,long:8 bytes.

15. Types of Error?

a)Syntax Error: Violation of grammar, missing brackets, missing semicolon(;).
b)Logical Error: Errors occur during the coding process.
c)Runtime Error: Error occurs when we attempt to run the ambiguous instruction. Like b=0; when c=a/b;

16. Decision making and branches statement in C?

C has three major decision making-
i)simple if statement.
ii)if-else.
iii)if-else-if later.
iv)switch.
v)Using conditional operator/ternary.

17. Difference b/w three-loop in c.

18. Break vs continue vs exit.

19. Example of Break Statement.

20. Example of Continue statement.

21. Example of Exit Statement.

22. goto statement and limitation/disadvantage.

goto statement is used to transfer the normal flow of a program to the specified
label in the program.
Syntax:
{

goto label;
……
……
LABEL:
statements;
}


There are two types of jump in goto statement:
1. Forward jump
2. Backward jump
goto makes the program logic very complex
goto should be avoilded

23. Storage class in C?

A storage class defines the scope and life-time of variables and/or functions within a C program.They
precede the type that they modify.We have four different storage classes in a C program-
i)auto-The auto storage class is the default storage class for all loacl variables.
{
int mount;
auto int month;
}
ii)register: The register storage class is used to define local variables that should be stored in a register instead of RAM. This means that the variable has a maximum size equal to the register size and can’t have the unary ‘&’ operator applied to it(as it does not have a memory location).
{
register int miles;
}
iii)Static: The static storage class instructs the compiler to keep a local variable in existence during the
a life-time of the program instead of creating and destroying it each time it comes into and goes out of scope.
Therefore, making local variables static allows them to maintain their values between function calls.
iv)extern: The extern storage class is used to give a reference to a global variable that is visible to all the
program files. When you use ‘extern’, the variable cannot be initialized however, it points the variable name at a
storage location that has been previously defined.

24. Local variable, Global variable, Constant variable.

i)Local variable:
a.The variables which are having scope/life only within the function are called local variables.
b.This variables are declared within the function and can’t be accessed outside the function.
ii)Global variable:
a.The variable which is having scope/life throughout the program are called global variables.
b.Global variable is defined outside the main function. So, this variable is visible to the main function
and all other functions.
iii)Constant Variable: Variables can be declared as constants by using the “const” keyword before the data type
of the variable. The constant variables can be initialized once only. The default value of the constant variable is
zero. A program that demonstrates the declaration of constant variables in C using the const keyword is given as follows.

25. What is an Array?

i)An array in a collection of elements of similar datatype which are stored in contiguous
memory locations.
ii)Every element in an array has a specific index.
iii)Size of array is fixed at the time of definition.
Syntax: int a[10]; //single dimensional array.
int a[10][10];//double dimensional array. 

26. What is a function?

a.Functions are blocks of code which are used to perform specific tasks.
b.In C a function needs to be declared before its used.
c.Functions have a function definition,function body and a return type.
d.Functions with return type not as void need to return a value at the end.
e.Functions with return type void do not return any value.

27. Types of function in C?

There are two types of functions in C.
1.Built-in(library) Functions:
i)The system provided these functions and stored in library. Therefore it is also called library functions.
Ex: scanf(),printf(),strcpy.strlwr,strcmp,strlen,strcat etc.
ii)To use these functions,you just need to include the appropriate C header files.
2.User Defined function: These functions are defined by the user at the time of writing the program.

28. What in pointer in C?

Pointer is a variable that holds the address of another variable.

Syntax: int a=10;
int *p = &a;

29. What is NULL pointers?

NULL pointer is a pointer that is pointing to nothing. NULL pointer points  to empty location in memory.The value of null pointer is 0. we can make a pointer to point to NULL.

30. What is Void Pointer?

The void pointer in C is a pointer which is not associated with any data types. It points to some data location in the storage means points to the address of variables. It is also called general purpose pointer. In C, malloc() and calloc() functions return void * or generic pointers.

31. What is Dangling Pointer?

A dangling pointer is a pointer that is pointing to a non-existing memory location is called Dangling pointer.

32. What is Integer Pointer?

Integer pointer only stores the address of an integer variable.
Syntax: int *pointer_name;

33. How to declare pointer in C?

There are a few important operations which we will do with the help of pointers very frequently.
a.We define a pointer variable.
b.assign the address of a variable to a pointer
c.Finally access the value at the address available in the pointer variable.This is done by using unary
operator * that returns the value of the variable located at the address specified by its operand.

Suppose,
int *p;
that means p is an integer pointer.
int a;
that means a is an integer variable.
p=&a;
it means p holds the address of a.

34. What is pointer to an array ?
Pointer to an array is also known as array pointer. We are using the pointer to access the components of the array.
int a[3] = {3, 4, 5 }; int *ptr = a;
We have a pointer ptr that focuses to the 0th component of the array. We can likewise declare a pointer that can point to whole array rather than just a single component of the array.


Syntax:
data type (*var name)[size of array];


Declaration of the pointer to an array:
// pointer to an array of five numbers

int (* ptr)[5] = NULL;
The above declaration is the pointer to an array of five integers. We use parenthesis to pronounce pointer to an array. Since subscript has higher priority than indirection, it is crucial to encase the indirection operator and pointer name inside brackets.

35. What is Array of pointer?

“Array of pointers” is an array of the pointer variables. It is also known as pointer arrays.
Syntax

int *var_name[array_size];

Declaration of an array of pointers:

int *ptr[3];

We can make separate pointer variables which can point to the different values or we can make one integer array of pointers that can point to all the values.

 

Output:

Value of arr[0] = 1
Value of arr[1] = 2
Value of arr[2] = 3

 

36. What is String Function?

Strings are stored in an array of characters along with the terminating character NULL at the end.

Some of the most commonly used String functions are:

strlen: Finds out the length of a string.

strlwr: It converts a string to lowercase.

strupr: It converts a string to uppercase.

strcat: It appends one string at the end of another.

strncat: It appends the first n characters of a string at the end of another.

strcpy: Use it for copying a string into another.

strncpy: It copies the first n characters of one string into another.

strcmp:it compares two strings.

strncmp: It compares the first n characters of two strings.

strcmpi: It compares two strings without regard to case(i denotes that this function ignores case).

stricmp: It compares two strings without regard to case.(identical to strcmpi).

strnicmp: It compares the first n characters of two strings, it’s not case sensitive.

strdup: Used for Duplicating a string.

strchr: Finds out the first occurrence of a given character in a string.

strrchr: Finds out the last occurrence of a given character in a string.

strstr: Finds first occurrence of a given string in another string.

strset: It sets all characters of a string to a given charcter.

strnset: It sets the first n characters of a string to a given character.

strrev: It reverses a string.

37. Structure, Union, Enum.

Structure: Structure is a group of variables of different data types represented by a single name. We can create
a structure that has members for the name, id, address, and age, and then we can create the variables of this structure for each student. The structure is a user-defined data type
Union: Like structures, the union is a user-defined data type. In a union, all members share the same memory location.
for example, both x and y share the same location, If we change x, we can see the changes being reflected in y.
Enum: Enumeration is a data type that consists of named integer constants as a list.
It starts with 0 by default and the value is incremented by 1 for the sequential identifiers in the list.

38. Class vs Structure

39. What is a file?
A file represents a sequence of bytes on the disk where a group of related data is stored.
The file is created for the permanent storage of data. It is a ready-made structure.

40. Types of files?

There are 2 kinds of files in which data can be stored in 2 ways either in characters coded in their ASCII
character set or in binary format.They are
1.Text files
2.Binary files

41. malloc(),calloc(),realloc(),free

malloc() :  The malloc() function is used allocated the single block of memeory during the execution of the program.

It does not initialize the conent of memory so it carries the garbage value.

It returns a null pointer if it could not be able to allocate the requested space.

Syntax: ptr = (cast_type *)malloc(byte size);

calloc() : The calloc() is same as malloc() but the difference only is that it initializes ther meomory with zero value.

Syntax: ptr = (cast_type *)calloc(n,ele_size);

realloc(): Modify the size of previously allocated space.
Syntax: ptr = realloc(ptr.newsize);

free() : free is previously allocated space.
Syntax: ptr = free(ptr);

 

42. Static vs dynamic array.

Static Array: An array created at compile time by specifying the size in the source code has a fixed size and can’t
be modified at run time. The process of allocating memory at compile time is known as static memory allocation
and the arrays that receive static memory allocation are called static arrays.


Dynamic Array: In C, it is possible to allocate memory to arrays at run time. This feature is known as dynamic
memory allocation and the arrays created at run-time are called dynamic arrays. Dynamic arrays are created
using pointer variables and memory management functions malloc, calloc and realloc.

43. What is Volatile.

i)The volatile keyword is a qualifier that prevents the objects, from compiler optimization and
tells the compiler that the value of the object can change at any time without any action being
taken by the code.
ii)It prevents the cache from a variable into a register and ensures that every access variable
is fetched from the memory.

Declaration of volatile in C:
int volatile data1;
volatile int data2;

44. User-define datatype.

The datatypes that are defined by the user are called the derived datatype or user-defined
derived datatype.
these types include:
a.Class
b.Structure
c.Union
d.Enum
e.Typedef

45. Array vs linked list.

46. What is Macro?

Macro is a name which is given to value or to a piece of code/block in a program.Instead of
using the value,we can use macro which will replace the value in a program.

Syntax: #defineVALUE
Example:Original declaration-#define AGE 50
Modified declaration-#define AGE 60
Another Example:


#include<stdio.h>
#define NUMBER 10
int main()
{
printf(“%d”,NUMBER);
return 0;
}
Output: 10

47. Macro vs function.

48. Pre-process directive.

The C preprocessor is a macro processor that is used automatically by the C compiler to transform the program before actual compilation(Proprocessor directives are executed before compilation). It is called a macro processor because it allows you to define macros, which are brief abbreviations for longer constructs. A macro is a segment of code that is replaced by the value of the macro. Macro is defined by the #define directive.

Preprocessing directives are lines in your program that start with #. The # is followed by an identifier that is the directive name.
For example, #define is the directive that defines a macro. Whitespace is also allowed before and after the #.

The # and the directive name cannot come from a macro expansion.
For example, if foo is defined as a macro expanding to define, that does not make #foo a valid preprocessing
directive.

All preprocessor directives starts with hash # symbol.

Example of Preprocessor directives:
1.#include 2.#define 3.#undef 4.#ifdef 5.#ifndef 6.#if 7.#else 8.#elif 9.#endif 10.#error 11.#pragma

49. Alternative of void main().

When some value is returned from main(),it is returned to operating system. The void main() indicates that
the main() can function will not return any value, but the int main() indicates that the main() can return
integer type data.So it is good practice to use int main() over the void main().

50 .Top down vs bottom-up.

51. c vs c++.

52.Assembler, Compiler, interpreter.

 53. printf,fprintf().

printf:printf function is used to print character stream of data on stdout console.
Syntax: int printf(const char* str, …);
Example:

#include<stdio.h>
int main()
{
printf(“hello”);
return 0;
}
Output: hello

fprintf: fprintf is used to print the string content in file but not on stdout console.
Syntax: int fprintf(FILE *fprintf,const char *str, …);
Example:

#include<stdio.h>
int main()
{ int i,x=4;
char s[20];
FILE *f = fopen(“new.txt”,”W”);
if(f==NULL)
{
printf(“Could not open file”);
return 0;
}
for (i=0;i<x;i++)
{
puts(“Enter text: “);
gets(s);
fprintf(f,”%d.%s\n”,i,s);
}
fclose(f);
return 0;
}

return 0;
}
Output:
Enter text: hello world!
Enter text: demo

54. scanf,fscanf().

scanf:The function scanf() is used to read formatted input from stdin C language.It retuns the whole number of
characters written in it otherwise, returns a negative value.
Syntax: int scanf(const char *characters_set);
Example:

#include<stdio.h>
int main()
{ char s[20];
printf(“Enter a string: “);
scanf(“%s”,s);
printf(“\nEntered String: %s\n”,s);
return 0;
}
Output:
Enter a string: hello!
Entered String: hello!

fscanf:The function fscanf() is used to read the formatted input from the given stream in C language.It returns
0,if unsuccessful.Otherwise,it returns the input string,if successful.
Syntax:int fscanf(FILE *stream_name, const char *set_of_characters);
Example:
#include<stdio.h>
#include<stdio.h>
int main()
{
char str1[10];
int year;
FILE * fp;
fp = fopen(“file.txt”,”w+”);
fputs(“This is demo text!”,fp);
rewind(fp);
fscanf(fp,”%s”,str1);
printf(“First word = \n%s\n,str1”);
fclose(fp);
return 0;
}
Output:
First word: This

55. getc(),getchar(),getch(),getche().

getc()

It reads a single character from the input and return an integer value. If it fails, it returns EOF.

Here is the syntax of getc() in C

int getc(FILE *stream);

Here is an example of getc() in C language,

Example

#include<stdio.h>
int main () {
   char val;
   printf("Enter the character: \n");
   val = getc(stdin);
   printf("Character entered: ");
   putc(val, stdout);
   return(0);
}

Output

Enter the character: a
Character entered: a

getchar()

The function getchar() reads the character from the standard input while getc() reads from the input stream. So, getchar() is equivalent to getc(stdin).

Here is the syntax of getchar() in C language,

int getchar(void);

Here is an example of getchar() in C language,

Example

#include 
int main() {
   char val;
   val = getchar();
   printf("Enter the character : \n");
   printf("Entered character : %c", val);
   return 0;
}

Output

Enter the character : n
Entered character : n

getch()

The function getch() is a non-standard function. It is declared in “conio.h” header file. Mostly it is used by Turbo C. It is not a part of C standard library. It immediately returns the entered character without even waiting for the enter key.

Here is the syntax of getch() in C language,

int getch();

Here is an example of getch() in C language,

Example

#include 
#include
int main() {
   char val;
   val = getch();
   printf("Enter the character : ");
   printf("Entered character : %c", val);
   return 0;
}

Output

Enter the character : m
Entered character : m

getche()

Like getch(), the getche() function is also a non-standard function and declared in “conio.h” header file. It reads a single character from the keyboard and returns it immediately without even waiting for enter key.

Here is the syntax of getche() in C language,

int getche(void);

Here is an example of getche() in C language,

Example

#include 
#include
int main() {
   char val;
   val = getche();
   printf("Enter the character : ");
   printf("Entered character : %c", val);
   return 0;
}

Output

Enter the character : s Entered character : s

56. Mode of file.

There are many modes in opening a file.Based on the mode of file,it can be opened for reading or writting
or appending the texts.
r Opens a file in read mode and sets pointer to the first character in the file. It returns null if file
does not exist.
w Opens a file in write mode. It returns null if file could not be opened. If file exists, data are
overwritten
aOpens a file in append mode. It returns null if file couldn’t be opened.
r+ Opens a file for read and write mode and sets pointer to the first character in the file.
w+ Opens a file for read and write mode and sets pointer to the first character in the file.
a+ Opens a file for read and write mode and sets pointer to the first character in the file.But,it can’t
modify existing contents.

57.File function.

a.fopen(): fopen() function is used to open a file to perform operations such as reading,writing etc.In a C
program,wr declare a file pointer and use fopin().fopen() function creates a new file if the
mentioned file name does not exist.
Syntax: FILE *fopen(const char *filename,const char *mode);
b.fclose():fclose() function closes the file that is being pointed by file pointer fp.In a C program,we close
a file.
Syntax: int fclose(FILE *fp);
c.fgets(): fgets function is used to read a file line by line.
Syntax: char *fgets(char *string,int n,FILE *fp);
d.fprint():fprint() function writes string into a file pointed by fp.
Syntax:int fprintf(FILE *fp,const char *format,…);

58. What is header file.

C language has numerous liabraries that include predefined function to make programming easier.In C
language,header files contain the set of predefined standard library functions.Your request to use a header
file in your program by including it with the C preprocessing directive “#include”.All the header file have a
‘.h’ an extension but in C,all the header files must necessarily end with the ‘.h’ extension.
A header file contains:
1.Function definitions.
2.Data type definitions.
3.Macros.
In C program should necessarily contain the header file which stands for standard input and output used to
take input with the help of scanf() and printf() function respectively.

There are of 2 types of header files:
1.Pre-existing header files:Files which are already available ic C compiler we just need to import them.
2.User-defined header

files:These files are defined by the user and can be imported using “inclued”.

Syntax:
include
include”filename.h”

 

59. Uses of c programming language.

C language is used to develop system applications that forms major portion of operating systems such as
windows,UNIX,Linux.Operating systems,C compiler and all UNIX application progarms are written in C language.
Below are some examples of uses of C language:
a.Database Systems.
b.Graphics packages.
c.Word processor.
d.Spread sheets.
e.Operating system development.
f.Compilers and assemblers.
g.Network drivers.
h.Interpreters.

60. Bitwise operator.

i)Bitwise operators are used to perform bit operations.Decimal values are converted into binary values
which are the sequence of bits and bitwise operators work on these bits.
ii)Bitwise operators in C language are &(bitwise AND),|(bitwise OR), ~(bitwise NOT),^(XOR),<<(left shift),
and >>(right shift).

61. ##operator

## is a pre-processor macro in C.It is used to concatenate 2 tokens into one token.
Example:
#include<stdio.h>
#define concatenation(a,b) a ## b
int main()
{

int ab = 1000;
printf(“The concatenated value is: %d \n”);
return 0;

}

62. What is Pragma?

#pragma is a pre-processor macro in C.It is used to call a function before and after main function in a C
program.
Example:
#include<stdio.h>

void f1(); //pragma startup f1
void f2(); //pragma exit f2

int main()
{
printf(“\n Now we are in main function”);
return 0;
}
Void f1()
{
printf(“\nFunction1 is called before main function call”);
}
Void f2()
{
printf(“\nFunction2 is called just before end of main function “);
}
Output: Function1 is called before main function call
Function2 is called just before end of main function.

63. What is a Memory leak.

The memory leak occurs,when a piece of memmory which was previously allocated by the programmer.Then it is
not deallocated properly by programmer.That memory is no longer in use by the program.So that place is reserved
for no reason.Thats why this is called the memory leak.
For the memory leak,some block of memory may have wasted.If the system has enough memory,in that case
also this may slow down the performance.

void my_func() //Here the problem is *data pointer is never deleted,so memory is wasted.
{
int *data = new int;
*data = 50;
}
#include
int main()
{ auto int my func();
my_func();
printf(“Main function\n”);
int my_func()
{
printf(“my_func function\n”);
}
printf(“done”);
return 0;
}
Output: my_func function
Main function
done

64. What is Constant pointer.

Const pointer is a pointer thst can’t change the address of the variable that is pointing to once const
pointer is made to point one variable,We can’t change this pointer to point to any other variable.This pointer
is called const pointer.
Syntax:*const;
int *const ptr;

Example:
#include
int manin()
{int a=1;
int b=2;
int *const ptr;
ptr=&a;
ptr=&b;
printf(“Value of ptr is: %d”,*ptr);
return 0;
}

65. Mathematical function in C.

“math.h” header file supports all the mathematical related functions in C language.All the arithmetic
functions used in C language are given below.
1.abs():This function returns the absolute value of an integer.The absolute value of a number is always
positive.Only integer values are supported in C.
Syntax:
Example: 

abs(-6) will return 6 and abs(6) also return 6.

 

2.floor():This function returns the nearest integer which is less than or equal to the arguement passed to
this function.
Syntax:double floor(double x);
Example: 

#include<stdio.h>
int main()
{ float a=5.1,b=-6.9;
printf(“floor of %f is %f\n”,a,floor(a));
printf(“floor of %f is %f\n”,b,floor(b);
return 0;
}
Output: floor of 5.100000 is 5.000000
floor of -6.900000 is -7.000000


3.round():This function returns the nearest integer value of the float/double/long double argument passed to
this function.If decimal value is from “.1 to .5”,it returns integer value less than the argument.If decimal
value is from “.6 to .9”,it returns the integer value greater than the argument.

66. Null vs 0.

NULL is a macro, defined as a null pointer constant.

0 is an integer.

67. What is Searching?

1.Searching is the process of finding a given value position in a list of values.
2.It decides whether a search key is present in the data or not.
3.It is the algorithmic process of finding a particular item in a collection of items.
4.It can be done on internal data structure or on external data structure.

To search an element in a given array,it can be done in following ways:
1.Linear Search.
2.Binary Search.

68. Searching, sorting,complexity.

69. Linear search and binary search. Why to use?

In Linear search, there is no need for sorting before searching but in the case of binary search, binary search can be done only on the sorted array. In the case of linear search, the Base time complexity is O(1), Average time complexity is O(n) and Worst Time complexity is O(n) and in the case of Binary search, the best time complexity is O(1), Average time complexity is O(log n), the Worst time complexity is O(log n).

70. What is Command line argument?

Command line argument is a parameter supplied to the program when it is invoked. Command line argument is an important concept in C programming. It is mostly used when you need to control your program from outside. Command line arguments are passed to the main() method.

Syntax:

int main(int argc, char *argv[])

Here argc counts the number of arguments on the command line and argv[ ] is a pointer array which holds pointers of type char which points to the arguments passed to the program.

Example for Command Line Argument

#include <stdio.h>
#include <conio.h>

int main(int argc, char *argv[])
{
    int i;
    if( argc >= 2 )
    {
        printf("The arguments supplied are:\n");
        for(i = 1; i < argc; i++)
        {
            printf("%s\t", argv[i]);
        }
    }
    else
    {
        printf("argument list is empty.\n");
    }
    return 0;
}

Remember that argv[0] holds the name of the program and argv[1] points to the first command line argument and argv[n] gives the last argument. If no argument is supplied, argc will be 1.

71. Call by value vs Call by reference.

Check Out More

C QA

Mostly Asked

DS QA

Mostly Asked

DBMS QA

Mostly Asked

ML QA

Mostly Asked

Leave a Reply

Your email address will not be published. Required fields are marked *