Вы находитесь на странице: 1из 21

C- TUTORIAL

C is a programming language invented in the early 1970s by Dennis Ritchie as a language for writing
operating systems.
The purpose of C is to precisely define a series of operations that a computer can perform to accomplish a
task. Most of these operations involve manipulating numbers and text, but anything that the computer can
physically do can be programmed in C.

Identifiers are names given to various elements of a program, such as variables, functions and arrays.
Identifiers consist of digits and letters, in any order but the rule is first character should be a letter.

Rules to be followed for constructing the identifier names

1. They must begin with a letter.


2. It must consist of single letter or sequence of letters, digits or underscore character.
3. Uppercase and lowercase are significant. For ex: Sum, SUM and sum are three distinct
variables.
4. Keywords are not allowed in variable names.
5. Special characters except the underscore are not allowed.
6. White space is also not allowed.
7. The variable name must be 8 characters long. But some recent compilers like ANSI C
supports 32 characters for the variable names.

keywords are certain reserved words that have standard, predefined meanings in C. These keywords can
be used only for their intended purpose; they cannot be used as programmer- defined identifiers. The
standard keywords are listed below:
auto extern size of break float static
case for struct const typedef if
switch char goto unsigned default long
continue int union void do register
volatile double return while else short
signed enum
It should be kept in mind that keywords are all in lowercase.

DATA TYPES: .

The four basic data types are


· INTEGER
these are whole numbers, both positive and negative. Unsigned integers (positive values only) are
supported. In addition, there are short and long integers.
The keyword used to define integers is,
int
An example of an integer value is 32. An example of declaring an integer variable called sum is,
int sum;
sum = 20;

· FLOATING POINT
These are numbers which contain fractional parts, both positive and negative. The keyword used
to define float variables is,
C- TUTORIAL

float
An example of a float value is 34.12. An example of declaring a float variable called money is,
float money;
money = 0.12;
· DOUBLE
These are exponential numbers, both positive and negative. The keyword used to define double
variables is,
double
An example of a double value is 3.0E2. An example of declaring a double variable called big is,
double big;
big = 312E+7;

CHARACTER
These are single characters. The keyword used to define character variables is,

char
An example of a character value is the letter A. An example of declaring a character variable called letter
is,
char letter;
letter = 'A';

Note the assignment of the character A to the variable letter is done by enclosing the value in single
quotes. Remember the golden rule: Single character - Use single quotes.

What is a variable? How do you declare variables? Give examples


A variable is a data name that may be used to store data value. A value or a quantity which may vary
during the program execution can be called as a variable. Each variable has a specific memory location in
memory unit, where numerical values or characters can be stored. A variable is represented by a symbolic
name. Thus variable name refers to the location of the memory in which a particular data can be stored.
Variables names are also called as identifiers since they identify the varying quantities.

For Ex : sum = a+b. In this equation sum, a and b are the identifiers or variable names representing the
numbers stored in the memory locations.

Variable Declaration:

Each variable used in a C program must be declared. Such declarations are necessary to indicate to the C
Compiler, the type of the variable used and specific number of memory locations required to hold
different constants or values. In other words, the variable name can store constants in its memory
locations belong to any four data types such as int, float, double and char.

Syntax of variable declaration:


Datatype variablename;
Examples:
int a;
char c;
double price, amount;
float average, variance;
C- TUTORIAL

Sample program illustrating each data type


#include < stdio.h >
void main()
{
int sum;
float money;
char letter;
double pi;
sum = 10; /* assign integer value */
money = 2.21; /* assign float value */
letter = 'A'; /* assign character value */
printf("value of sum = %d\n", sum );
printf("value of money = %f\n", money );
printf("value of letter = %c\n", letter );
}
Sample program output
value of sum = 10
value of money = 2.210000
value of letter = A

Operators Introduction

An operator is a symbol which helps the user to command the computer to do a certain mathematical or
logical manipulations. Operators are used in C language program to operate on data and variables. C has a
rich set of operators which can be classified as

1. Arithmetic operators 5. Increments and Decrement Operators


2. Relational Operators 6. Conditional Operators
3. Logical Operators 7. Bitwise Operators
4. Assignment Operators 8. Special Operators
1. Arithmetic Operators

All the basic arithmetic operations can be carried out in C. All the operators have almost the same meaning as in
other languages. Both unary and binary operations are available in C language. Unary operations operate on a singe
operand, therefore the number 5 when operated by unary – will have the value –5.

Arithmetic Operators

Operator Meaning
+ Addition or Unary Plus
– Subtraction or Unary Minus
* Multiplication
/ Division
% Modulus Operator
C- TUTORIAL
Examples of arithmetic operators are

x+y
x-y
-x + y
a*b+c
-a * b

etc., here a, b, c, x, y are known as operands. The modulus operator is a special operator in C language which
evaluates the remainder of the operands after division.

2. Relational Operators

Often it is required to compare the relationship between operands and bring out a decision and program accordingly.
This is when the relational operator come into picture. C supports the following relational operators.

Operator Meaning
< is less than
<= is less than or equal to
> is greater than
>= is greater than or equal to
== is equal to
!= is not equal to

It is required to compare the marks of 2 students, salary of 2 persons, we can compare them using relational
operators.

A simple relational expression contains only one relational operator and takes the following form.

exp1 relational operator exp2

Where exp1 and exp2 are expressions, which may be simple constants, variables or combination of them. Given
below is a list of examples of relational expressions and evaluated values.

6.5 <= 25 TRUE


-65 > 0 FALSE
10 < 7 + 5 TRUE

Relational expressions are used in decision making statements of C language such as if, while and for statements to
decide the course of action of a running program.
3. Logical Operators
C has the following logical operators; they compare or evaluate logical and relational expressions.

Operator Meaning
&& Logical AND
|| Logical OR
! Logical NOT

Logical AND (&&)


This operator is used to evaluate 2 conditions or expressions with relational operators simultaneously. If both the
expressions to the left and to the right of the logical operator is true then the whole compound expression is true.

Example
C- TUTORIAL
a > b && x = = 10

The expression to the left is a > b and that on the right is x == 10 the whole expression is true only if both
expressions are true i.e., if a is greater than b and x is equal to 10.

Logical OR (||)

The logical OR is used to combine 2 expressions or the condition evaluates to true if any one of the 2 expressions is
true.

Example

a < m || a < n

The expression evaluates to true if any one of them is true or if both of them are true. It evaluates to true if a is less
than either m or n and when a is less than both m and n.

Logical NOT (!)

The logical not operator takes single expression and evaluates to true if the expression is false and evaluates to false
if the expression is true. In other words it just reverses the value of the expression.

For example

! (x >= y) the NOT expression evaluates to true only if the value of x is neither greater than or equal to y

4. Assignment Operators

The Assignment Operator evaluates an expression on the right of the expression and substitutes it to the value or
variable on the left of the expression.

Example

x=a +b

Here the value of a + b is evaluated and substituted to the variable x.

In addition, C has a set of shorthand assignment operators of the form.

var oper = exp;

Here var is a variable, exp is an expression and oper is a C binary arithmetic operator. The operator oper = is known
as shorthand assignment operator

Increment and Decrement Operators

The increment and decrement operators are one of the unary operators which are very useful in C language. They are
extensively used in for and while loops. The syntax of the operators is given below

1. ++ variable name
2. variable name++
3. – –variable name
4. variable name– –
C- TUTORIAL
The increment operator ++ adds the value 1 to the current value of operand and the decrement operator – – subtracts
the value 1 from the current value of operand. ++variable name and variable name++ mean the same thing when
they form statements independently, they behave differently when they are used in expression on the right hand side
of an assignment statement.

Consider the following

m = 5;
y = ++m; (prefix)

In this case the value of y and m would be 6. Suppose if we rewrite the above statement as

m = 5;
y = m++; (post fix)

Then the value of y will be 5 and that of m will be 6. A prefix operator first adds 1 to the operand and then the result
is assigned to the variable on the left. On the other hand, a postfix operator first assigns the value to the variable on
the left and then increments the operand.

CONDITIONAL STATEMENTS:

A conditional statement controls the sequence of statements, depending on the condition.

1) Simple If statement
2) If-else statement
3) if-else if statement
4) Nested if statement

SIMPLE IF STATEMENT: It execute if condition is TRUE

Syntax:

if(condition)
{
Statement1;
.....
Statement n;
}

Example:

void main()
{
int a,b;
printf(“Enter a,b values:”);
scanf(“%d %d”,&a,&b);
if(a>b)
printf(“\n a is greater than b”);
}

OUTPUT:
Enter a,b values:20
10
a is greater than b
C- TUTORIAL
IF-ELSE STATEMENT: It execute IF condition is TRUE.IF condition is FLASE it execute ELSE part

Syntax:
if(condition)
{
Statement1;
.....
Statement n;
}
else
{
Statement1;
.....
Statement n;
}
Example:
void main()
{
int a,b;
printf(“Enter a,b values:”);
scanf(“%d %d”,&a,&b);
if(a>b)
printf(“\n a is greater than b”);
else
printf(“\nb is greater than b”);
}
OUTPUT:
Enter a, b values:10
20
b is greater than a

IF-ELSE IF STATEMENT: It execute IF condition is TRUE.IF condition is FLASE it checks ELSE IF part .ELSE
IF is true then execute ELSE IF PART. This is also false it goes to ELSE part.
Syntax:
if(condition)
{
Statement1;
.....
Statementn;
}
else if
{
Statement1;
.....
Statementn;
}
else
{
Statement 1;
.....
Statement n;
}
Example:
void main()
{
C- TUTORIAL
int a,b;
printf(“Enter a,b values:”);
scanf(“%d %d”,&a,&b);
if(a>b)
printf(“\n a is greater than b”);
else if(b>a)
printf(“\nb is greater than b”);
else
printf(“\n a is equal to b”);
}
OUTPUT:
Enter a,b values:10
10
a is equal to b

NESTED IF STATEMENT: To check one condition within another. Take care of brace brackets within the
conditions.
Synatax:
if(condition)
{
if(condition)
{
Statement 1;
...
Statement n;
}
}
else
{
Statement 1;
....
Statement n;
}
Example:
void main()
{
int a,b;
printf(“\n Enter a and b values:”);
scanf(“%d %d ”,&a,&b);
if(a>b)
if((a!=0) && (b!=0))
printf(“\na and b both are +ve and a >b);
else
printf(“\n a is greater than b only”)
else
printf(“ \na is less than b”);
}
Output:
Enter a and b values:30
20
a and b both are +ve and a > b
C- TUTORIAL
LOOP STATEMENT: Loops are used to repeat a block of code. Being able to have your program repeatedly
execute a block of code is one of the most basic but useful tasks in programming

The for loop

The “for loop” loops from one number to another number and increases by a specified value each time.
The “for loop” uses the following structure:

for (Start value; end condition; increase value)


statement;

Example

#include<stdio.h>

void main()
{
int i;
for (i = 0; i < 10; i++)
{
printf ("Hello\n");
printf ("World\n");
}
return 0;
}

Note: A single instruction can be placed behind the “for loop” without the curly brackets.

Let’s look at the “for loop” from the example: We first start by setting the variable i to 0. This is where we start to
count. Then we say that the for loop must run if the counter i is smaller then ten. Last we say that every cycle i must
be increased by one (i++).

In the example we used i++ which is the same as using i = i +1. This is called incrementing. The instruction i++ adds
1 to i. If you want to subtract 1 from i you can use i–. It is also possible to use ++i or –i. The difference is is that with
++i the one is added before the “for loop” tests if i < 10. With i++ the one is added after the test i < 10.

The while loop:The while loop can be used if you don’t know how many times a loop must run. Here is an example:

#include<stdio.h>

void main()

{
int counter, howmuch;

scanf("%d", &howmuch);
counter = 0;
while ( counter < howmuch)
{
counter++;
printf("%d\n", counter);
C- TUTORIAL
}
return 0;
}

Let’s take a look at the example: First you must always initialize the counter before the while loop starts ( counter =
1). Then the while loop will run if the variable counter is smaller then the variable “how much”. If the input is ten,
then 1 through 10 will be printed on the screen. A last thing you have to remember is to increment the counter inside
the loop (counter++). If you forget this the loop becomes infinitive.

The do while loop: The “do while loop” is almost the same as the while loop. The “do while loop” has the following
form:

do
{
do something;
}
while (expression);

Do something first and then test if we have to continue. The result is that the loop always runs once. (Because the
expression test comes afterward). Take a look at an example:

#include<stdio.h>

void main()
{
int counter, howmuch;
scanf("%d", &howmuch);
counter = 0;
do
{
counter++;
printf("%d\n", counter);
}
while ( counter < howmuch);
return 0;
}

Note: There is a semi-colon behind the while line.

Break and continue:

To exit a loop you can use the break statement at any time. This can be very useful if you want to stop running a loop
because a condition has been met other than the loop end condition. Take a look at the following example:

#include<stdio.h>

void main()
{
int i;

i = 0;
C- TUTORIAL
while ( i < 20 )
{
i++;
if ( i == 10)
break;
}
return 0;
}
In the example above, the while loop will run, as long i is smaller then twenty. In the while loop there is an if
statement that states that if i equals ten the while loop must stop (break).

With “continue;” it is possible to skip the rest of the commands in the current loop and start from the top again. (the
loop variable must still be incremented). Take a look at the example below:

#include<stdio.h>

void main()
{
int i;

i = 0;
while ( i < 20 )
{
i++;
continue;
printf("Nothing to see\n");
}
return 0;
}

In the example above, the printf function is never called because of the “continue;”.

What is a header file? Why do you need header files in C? Give examples
Header files are files that are included in other files prior to compilation by the C preprocessor. Some, such as
stdio.h , are defined at the system level and must included by any program using the standard I/O library. Header
files are also used to contain data declarations and defines that are needed by more than one program. Header
files should be functionally organized, i.e., declarations for separate subsystems should be in separate header files.
Also, if a set of declarations is likely to change when code is ported from one machine to another, those
declarations should be in a separate header file.

Information that is needed by several different files or functions is collected into a header file. A header file
contains C-language definitions and structures. Centralizing information into a header file facilitates the creation
and update of programs. Because #include statements are used to insert header files into a C-language program,
header files are often referred to as include files.

Header files define the following functions:

· Structures of certain files and subroutines


· Type definition (typedef) synonyms for data types
· System parameters or implementation characteristics
· Constants and macros that are substituted during the C language preprocessing phase.
C- TUTORIAL
For example, to use printf() and scanf() functions we use header file stdio.h and is included with the preprocessor
directive #include<stdio.h>. The string handling functions are stored in string.h header file. All mathematical
functions are stores in math.h file.

What is a preprocessor directive? Why it is needed?


The preprocessor is a program that processes the source code before it passes through the compiler. It
operates under the control of what is known as preprocessor directive. Preprocessor directives are placed in
the source program before the main() line.

Preprocessor directives follow special syntax rules that are different from the normal syntax. They all begin
with the symbol # in column one and do not require a semicolon at the end. These preprocessor directives can
be grouped into three categories.

Ø Macro substitution directives


Ø File inclusion directives
Ø Compiler control directives
Macro substitution is a process when an identifier in a program is replaced by a predefined string composed of
one or more tokens. The preprocessor accomplishes this task under the direction of #define directives.

Syntax : #define identifier string


Ex: # define PI 3.14
# define SIZE 10
# define AND &&
# define START main(){
# define END }
# define cube(x) (x*x*x)
#define max(a,b) (((a) > (b) ? (a) : (b))
File inclusion directives are used to include a file which contains a particular useful function for the said
program. All file inclusion directives begin with the syntax #include

Ex : #include <math.h>
#include “string.h”
The filename can be specified with angle brackets or with a double quote. When the filename is included
within double quotes, the search for the file is made first in the current directory and then in the standard
directories. Alternatively, if filename is specified with angle brackets, the file is searched only in the standard
directories.

The compiler control directives are used for conditional compilation of the source program.

Differentiate between nested if –else and switch statements


When different actions are to be done depending on the value of a variable, we can use cascaded if else
statements. By the use of switch statement, same program can be achieved in a compact and user friendly way.
Both statements are used for multiway branching in a program. But by using if else conditions we can test for any
real value whereas a switch statement allows for testing of integers only. Also under each if statement, it is
possible to test complex conditions.

The following example illustrates the use of nested if else and switch statement for the same program.
C- TUTORIAL
Nested if – else Switch statement

If ( code == 1) switch ( code)

{ {

discount = 20; case 1:


price – price- (price*20/100);
discount = 20;
}
price – price- (price*20/100);
else if ( code == 2)
break;
{
case : 2
discount = 10;
discount = 10;
price – price- (price*10/100);
price – price- (price*10/100);
}
break;
else if ( code == 3)

{ case : 3

discount = 5; discount = 5;

price – price- (price*5/100); price – price- (price*5/100);

} break;

24. When do you use a switch statement? Explain the syntax of switch with examples? 04

A switch statement is used when multiple branching is required in a program. Switch is a multi way branching
statement. The switch statement tests the value of a given variable against a list of case values and when a match is
found, a block of statements associated with that case is executed. The general form of the switch statement is as
follows.

Syntax:

switch (expr)
{
case value1 :
block1;
break;
case value2:
block2;
break;
------
------
default:
default-block;
break;
} Flow chart
C- TUTORIAL

The expr is an integer expression or character. value1, value2, …. are constant or constant expressions and are
known as case labels. Each of these values should be unique within a switch statement. block1, block2, …. are
statement lists and may contain zero or more statements.

When the switch statement is executed, the value of the expression is successively compared against the values
value1, value2…. If a case is found whose matches with the value of the expression, then the block of statements
that follows the case are executed.

Ex:

switch ( num)
{
case 1:
printf”(One”);
break;
case 2:
printf”(Two”);
break;
case 3:
printf(“Three”);
break;
…..
…..
}

Explain the difference between while and do-while loop?


While loop do – while loop
1. Entry controlled loop i.e. the condition is 1. Exit controlled loop i.e. condition is
checked first and statement in the loop will checked at the end of the loop and statement
get executed if the condition is true in the loop will get executed if the condition
is true.
2. Statements in the loop will not get 2. Statements in the loop will get executed
executed if initially the condition is false at least once even if the condition is false
initially.
3. syntax: 3. Syntax:
while ( condition) do
{ {
statements; statements;
} } while (condition);
4. Example: 4 . Example:
int i=1; int i=1;
do { do {
printf(“%d”, i); printf(“%d”, i);
i++; i++;
} while (i<10); } while (i<10);
C- TUTORIAL
What is array? How do you classify arrays? Give examples
An array may be defined as a group of similar data elements that share a common name. The arrays can be profitably
used if want to handle a large number related data of similar type.
For instance, we can define an array name salary to represent a set of salaries of a group of employers. A
particular value is indicated by writing a number called index or subscript in brackets after the array name. For
example,
Salary[10] represents the salary of the 10th employee. While the complete set of values is referred to
as an array, the individual values are called elements of the array. Arrays can be of any variable type.
Arrays can be classified as one dimensional arrays and multidimensional arrays. A list of items having only one
variable name and can be accessed using only one subscript is called a single dimensional array.
For ex: salary[50]; is a one dimensional array.
The array declared with more than one subscript is called a multi dimensional array. Here more than one subscript is
required to specify each array element. Consider a case where we have to store the marks of 5 students in 4 subjects.
For this purpose, we can declare a two dimensional array which can store 20 values.
Ex: matrix[5][5]; is a two dimensional array.

What is an array? How are they declared ? What are the rules to be followed while using arrays,

Declaration of arrays:
An Array is declared as follows:
Type variable[n];
Where n is an integer indicating the maximum number of elements in the array.
Type refers to the data type of the array and variable is any valid C identifier used indicate the name of the array.
Example:
int marks[10];
float sales[50];
int purchase[10][20];
char name[20];
Rules to be followed while using arrays:
· Array subscript always starts with zero. So the first element will have the index as zero.
· The data type of all the elements of the array must be same.
· Array can be initialized at the time of declaration by specifying the value of each element within
braces. There must be an equal sign between the array name and braces and each value in the braces
must be separated by a comma.
· If all values are given in braces, the subscript in the array can be omitted.
· If an array is declared with subscript and fewer the number of values are given in the braces, the
cells are initialized from the beginning and remaining cells are left uninitialized.
· There is no way to initialize middle elements of the array.
· The compiler does not check for bounds of the array. While assigning values to the array elements,
the user has to see that the subscript value will be less than the maximum size of the array.
Distinguish between local and global variables
Local variables
These variables only exist inside the specific function that creates them. They are unknown to other functions and to
the main program. As such, they are normally implemented using a stack. Local variables cease to exist once the
function that created them is completed. They are recreated each time a function is executed or called.
Global variables
These variables can be accessed (i.e. known) by any function comprising the program. They are implemented by
associating memory locations with variable names. They do not get recreated if the function is recalled.
Example:
int x = 10; /* global variable */
main()
{
int a =5; /* local variable */
printf(“ A = %d x = %d”, a,x); /* output A = 5 x =10 */
f1();
C- TUTORIAL
printf(“ A = %d x = %d”, a,x); /* output A = 5 x =50 */
}
f1()
{
x = 50;
printf(“\n X = %d”, x); /* output X =50 */
}
Mention different categories of functions. Give examples.
Different categories of functions are as under:
A function can be defined as a subprogram which performs a particular sub task. Functions may be library
functions and user defined functions. Library functions are the built-in functions for performing certain operations
such as finding the sine of an angle, square root, printing and reading data values, etc. Example are printf(), scanf(),
sqrt(), abs(), etc. User defined function is a sub program written by the user for a particular task. They can be
codified and recalled whenever needed.
The user defined functions can be categorized as follows depending on the return type and arguments of the
function.
i) Functions with no arguments and no return type
When a function has no arguments, it does not receive any data from the calling function. Similarly, when it does not
have a return type, the calling function does not receive any data from the function. In effect, there is no data transfer
between the calling function and the called function.

function1() main()
{ {
------- printline();
------- printf(“KVGCE\n”);
function2(); printline();
} }
function2() printline()
{ {
------- printf(“--------------------“);
------ }
}

ii) Functions with arguments and no return type


If the calling function has to send some data to the called function, it may do so with the help of arguments. In this
type of function arguments will be passed to function and the called function uses those value for further processing.
But the computed result will not be returned back
function1() main()
{ {
------- int a =10;
------- f1();
function2(a); printline();
} }
function2(int a) f1(int x)
{ {
------- x = x + 10;
------ printf(“x = %d”, x);
} }

iii) Functions with arguments and with return type


If there is two way communications between the calling function and called function, then this type of function falls
under this category.
C- TUTORIAL
function1() main()
{ {
int b,a =10
------- b=f1(a);
x = function2(y); Printf(“B = %d”, b);
printf(“x = %d”, x) }
} f1(int x);
function2(int a) {
{ int z = x+5;
return(z);
return(a); }
}

What are users defined functions? Why they are required for large and complex
programs.
A function is a self contained block of code that performs a particular task. Once a function has been designed and
packed, it can be treated as a “black box” that takes some data from the main program and returns a value. The inner
details of operation are invisible to the rest of the program.
Need of functions:
In a large and complex program, if the program is written with only a main() function, it leads to a number of
problems. The program may become too large and complex and as a result the task of debugging, testing and
maintaining becomes difficult. If a program is divided into functional parts, then each part may be independently
coded and later combined into a single unit. These functions are much easier to understand, debug, and test.
There are times when some type of operation is repeated at many points throughout a program. For instance,
factorial of a number. In such situations, we may repeat the statements wherever they are needed. Another approach
is to design a function that can be called and used wherever required. This saves both time and space.
The use of functions in C serves many advantages:
· It facilitates top-down modular programming . In this programming style, the high level of the overall
problem is solved first while the details of each lower-level function are addressed later.
· The length of a source program can be reduced by using functions at a appropriate places.
· It is easy to locate and isolate a faulty function for further investigations.
· A function may be used by many other programs. This means that a C programmer can build on what others
have already done, instead of starting from scratch.

Explain any five string handling functions with examples.


strcat() Function
strcat() joins two or more strings together. It takes the following form
strcat(string1, string2);
string1 and string2 are character arrays. When the above function is executed, string2 is appended to string1. It does
so by removing the null character at the end of string1 and placing string2 from there. The string at string2 remains
unchanged.
strcat function may also append a string constant to a string variable. The following is valid
strcat(part1,"SACY");
C also permits nesting of strcat functions. For example
strcat(strcat((string1,string2),string3);
is allowed and concatenates all the three strings together. The resultant string is stored in string1.
strcmp() Function
The strcmp function compares two strings identified by the arguments and has a value 0 if they are equal. If they are
not, it has the numeric difference between the first non-matching characters in the strings. It takes the form:
strcmp(string1, string2);
string1 and string2 may be string variables or string constants. For example
strcmp(name1,name2);
strcmp(name1,"JOHN");
C- TUTORIAL
strcpy() Function
The strcpy function works almost like a string-assignment operator. It takes the form
strcpy(string1,string2);
and assigns the contents of string2 to string1. string2 may be a character array variable or a string constant. For
example
strcpy(city,"DELHI");
will assign the string "DELHI" to the string variable city. Similarly the statement
strcpy(city1, city2);
will assign the contents of the string variable city2 to the string variable city1.The size of the array city1 should be
large enough to receive the contents of city2.
strlen() Function
This function counts and returns the number of characters in a string
n = strlen(string);
Where n is an integer variable, which receives the value of the length of the string. The argument may be a string
constant. The counting ends at the first null character.
strncmp(str1, str2,n) function
Compares first n characters of the second string with first string and returns either 0, 1 or -1.
strncat(str1,str2,n) function
Concatenates first n characters of the second string to the first string
strncpy(str1,str2,n) function
Copies first n characters of the second string to the first string
strupr(str1) function
Converts the string to upper case
strlwr(str1) function
Converts the string to lower case

Explain scope and lifetime of variables


The scope of a variable is the portion of the program where the variable is valid or "known”. A variable's lifetime is
the period of time during which that variable exists during execution. Some variables exist briefly. Some are
repeatedly created and destroyed. Others exist for the entire execution of a program. In this section we will discuss
two storage classes of variables: automatic variables and static variables.
An automatic variable's memory location is created when the block in which it is declared is entered. An automatic
variable exists while the block is active, and then it is destroyed when the block is exited. Since a local variable is
created when the block in which it is declared is entered and is destroyed when the block is left, one can see that a
local variable is an automatic variable.
A static variable is a variable that exists from the point at which the program begins execution and continues to exist
during the duration of the program. Storage for a static variable is allocated and initialized once when the program
begins execution. A global variable is similar to a static variable since a global variable exists during the duration of
the program. Storage for the global variable is allocated and is initialized once when the declaration for the global
variable is encountered during execution. Thus both the global variable and the static variable have a history
preserving feature -- they continue to exist and their contents are preserved throughout the lifetime of the program.

Why do you need static variables in a program? Explain with an example


A static variable is a variable that exists from the point at which the program begins execution and continues to exist
during the duration of the program. Storage for a static variable is allocated and initialized once when the program
begins execution.
A programmer can declare a local variable to be static by using the keyword static in the variable's declaration as in
the following example:
static int num=0;
For most applications, the use of automatic variables works just fine. Sometimes, however, we want a function to
remember values between function calls. This is the purpose of a static variable. A local variable that is declared as
static causes the program to keep the variable and its latest value even when the function that declared it is through
executing. It is usually better to declare a local variable as static than to use a global variable. A static variable is
similar to a global variable in that its memory remains for the lifetime of the entire program. However, a static
variable is different from a global variable because a static variable's scope is local to the function in which it is
C- TUTORIAL
defined. Thus other functions in the program can not modify a static variable's value because only the function in
which it is declared can access the variable.
Example:
main()
{
int i;
for ( i =1; i<=3; i)
stat();
}
stat()
{
static int x =0;
x=x+1;
printf(“x = %d\n”, x);
}
output
x=1
x=2
x =3
Define auto, global, static, and register variables and give examples.
i) Automatic variables
Automatic variables are declared inside a function in which they are to be utilized. They are created when the
function is called and destroyed automatically when the function is exited. Automatic variables are therefore private
(local) to the function in which they are declared.
Syntax of declaration:
auto datatype variablename;
ex: auto int a;
One important feature of the auto variables is that their value cannot be changed accidentally by what happens in
some other function in the program. This assures that we may declare and use the same variable name in different
functions in the same program without causing any confusion to the compiler.
ii) Extern variables
Variables that are both live and active throughout the entire program are known as external variables. They are also
known as global variables. They can be accessed by any function in the program. External variables are declared
outside a function.
For ex:
int number;
main()
{
-----
----
}
function1()
{
-----
-----
}
iii) Static variables
The value of the static variable persists until the end of the program. A variable can be declared as static
using the keyword static.
Ex: static int a;
The scope of the static variable extend upto the end of the function in which they are declared. A static variable is
initialized only once, when the program is compiled. It is never initialized again.
iv) Register variables
We can tell the compiler that a variable should be kept in one of machine’s registers, instead of keeping in
memory by using the keyword register. Since a register access is much faster than a memory access, keeping the
C- TUTORIAL
frequently accessed variables ( eg. loop counters) in the registers will lead to faster access execution of programs.
Ex:
register int a;
Since only few variables can be placed in the register, it is important to carefully select the variables for this purpose.

Scope and Life time of Varibales


Storage Storage Initial value Scope Life time
class
Auto Memory Garbage Local scope i.e. only in Until end of function or
value the block they declared block
register CPU Garbage Local scope Until end of function or
Registers block
extern Memory Zero Global scope Until the end of the
program
static Memory Zero Local scope The value of the variable
persists between the call of
the function.
What is pointer? Explain how to declare a variable as a pointer.
A "normal variable" is a location in memory that can hold a value. For example, when you declare a variable i as an
integer, four bytes of memory are set aside for it. In your program, you refer to that location in memory by the name
i. At the machine level that location has a memory address. The four bytes at that address are known to you, the
programmer, as i, and the four bytes can hold one integer value.
A pointer is different. A pointer is a variable that points to another variable. This means that a pointer holds the
memory address of another variable. Put another way, the pointer does not hold a value in the traditional sense;
instead, it holds the address of another variable. A pointer "points to" that other variable by holding a copy of its
address.
Because a pointer holds an address rather than a value, it has two parts. The pointer itself holds the address. That
address points to a value. There is the pointer and the value pointed to. This fact can be a little confusing until you
get comfortable with it, but once you get comfortable it becomes extremely powerful.
The following example code shows a typical pointer:
main()
{
int i,j;
int *p; /* a pointer to an integer */
p = &i;
*p=5;
j=i;
printf("%d %d %d\n", i, j, *p);
}
The first declaration in this program declares two normal integer variables named i and j. The line int *p declares a
pointer named p. This line asks the compiler to declare a variable p that is a pointer to an integer. The * indicates
that a pointer is being declared rather than a normal variable. You can create a pointer to anything: a float, a
structure, a char, and so on. Just use a * to indicate that you want a pointer rather than a normal variable.
In C, & is called the address operator. The expression &i means, "The memory address of the variable i." Thus, the
expression p = &i; means, "Assign to p the address of i." Once you execute this statement, p "points to" i. Before
you do so, p contains a random, unknown address, and its use will likely cause a segmentation fault or similar
program crash.

ARRAY
Array by definition is a variable that hold multiple elements which has the same data type.
Declaring Arrays
We can declare an array by specify its data type, name and the number of elements the array holds between square brackets
immediately following the array name.
C- TUTORIAL
Here is the syntax:

data_type array_name[size];

For example, to declare an integer array which contains 100 elements we can do as follows:

int a[100];

There are some rules on array declaration. The data type can be any valid C data types including structure and
union. The array name has to follow the rule of variable and the size of array has to be a positive constant integer.

We can access array elements via indexes array_name[index]. Indexes of array starts from 0 not 1 so the highest
elements of an array is array_name[size-1].

Initializing Arrays
It is like a variable, an array can be initialized. To initialize an array, you provide initializing values which are
enclosed within curly braces in the declaration and placed following an equals sign after the array name. Here is an
example of initializing an integer array.

int list[5] = {2,1,3,7,8};

Mention the differences between a pointer and an array


A pointer is a special type of variable which is used for storing the memory address of another variable. So a pointer
can point the location of another variable. With help of a pointer, the value stored in another variable can be
accessed. The pointers are declared similar to a normal variable but with a * ( asterisk) preceded by the variable
name.
Ex:
int *p;

An array is a collection of similar data elements having a common name and the elements of the array are stored in
contiguous memory locations. The name of the array refers to the memory address of the first element of the array.
So with the help of name of array, all elements of the array can be accessed one after another in the memory
locations. So an array is similar to a pointer variable which holds the address of the memory location and can be used
for accessing the elements of the array.

An array cannot be used for storing address of another variable similar to a pointer and cannot be de-referenced with
* operator.

Example :
int marks[20]; is a array declaration statement used for storing marks of 20 students.

Вам также может понравиться