Declaration and Initialisation of Strings

Strings in C are group of characters ,digits and symbols enclosed in quotation marks .The end of the string is marked with a special character,the'\0'(null),which has the decimal value 0.There is a difference between a character stored in memory and a single character string stored in a memory.The character requires only one byte whereas the single character string requires two bytes (one byte for the character aand other byte for the delimiter).

Declaration of Strings

To declare a string,specify the data type as char and place the  number of characters in an array in square brackets after the string name.Syntax is as follows:

Char string-name[size];
for example -
char city[24];
char studname[50];

Initialization of strings

String can be initialized as follows:

String can be initialized as follows:
char name[8]={'P','R','O','G','R','A','M','\0'};

Each character of strings occupies 1 byte of memory(on 16 bit computing) .The size of character is machine dependent,and varies from 16 bit computers to 64 bit computers .The character of strings are stored in the contiguous(adjacent) memory location.

1 Byte 1 Byte 1 Byte 1 Byte 1 Byte 1 Byte 1 Byte 1 Byte
P R O G R A M \0
2001 2002 2003 2004 2005 2006 2007 \2008

The C compiler inserts the null (\0) character automatically at the end of the string.So initialization of the Null character is not essential.

You can set the initial value of a character array when you declare it by specifying a string literal .If the array is too small for the literal ,the literal will be truncated .If the literal  is smaller than the array ,then the final characters in the array will be undefined .If you don't specify the size of  the array,but do specify a literal,then C will set the array to the size of the literal ,including the null terminator.

char str[4]={'u','n','i','x'};
char str[5]={'u','n','i','x','\0'};
char str[3];
char str[]="UNIX";
char str[4]="unix";
char str[9]="unix";

All of the above declarations are legal.The first is valid declaration but it will cause major major problem because null is not-terminated.The fifth example suffers the size problem and fourth example is legal because the compiler will determine the length of string automatically and initialize the  last character to null-terminator .

String Constants

String constants have double quote marks around him them,and can be assigned to char pointers.Alternatively,you can assign a string constant to char array -either with no size specified ,or you can specify a size ,but don't forget to leave a for the null character !Suppose you create the following two code fragments and  run them:
/*fragment 1*/
 {
char *s;
s="hello" ;
printf("%s\n",s);
 }

/*fragment 2*/
{
 char s[100];
strcpy(s,"hello");
printf("%s\n",s);
}

These two fragments produce the same output ,but their internal behavior is different.In fragment 2 you can say s="hello"; . To understand the differences,you have to understand how the string constant table work in C.When your program is compiled ,the compiler forms the object code file ,which contain your machine code and a table of ll the string constant declared in a program.In fragment 1 ,the statement s="hello"; causes s to  point to the address of the string hello in the string constant table .Since this string is in the string constant table ,and therefore technically a part of executable code,you cannot modify it .You can only point to it and use it in a read-only manner.In fragment 2,the string hello also exists in the constant table ,so you can copy it into the array of characters  named s .Since s is not an address,the statement s="hello"; will not work n fragment 2.It will not compile.


EXAMPLE

Write  a program to read a name from the keyboard and display message Hello onto the monitor.


#include<stdio.h>
main()
{
char name[10];
printf("\n Enter your name:");
Scanf("%s",name);
printf("Hello %s\n",name);
}

OUTPUT
Enter your name : Pankaj
Hello Pankaj

MULTI-DIMENSIONAL ARRAYS

Multi dimensional array is an array in which more than one row and one column is present.Chess board is an example to two dimensional array.Two dimensional array use to indices to pinpoint an individual element of the array.This is very similar to what is called "algebraic notation ",commonly used in chess circles to record games and chess problems. '

Multi-Dimension Array Declaration

The syntax is as follows:

datatype array_name[Size1][SIZE2];

in the above statement,datatype is the name of some type of data,such as int,char.Size1 and Size2 are the size of an array's first(row) and second(column) dimension,respectively.8-by-8 array of integers is similar to a chessboard.Remember,because C arrays are zero-based,the indices on each side of the chessboard array run 0 through 7,rather than 1 to 8.

int chessboard[8][8];

Initialization of Two-dimensional arrays

If you have an m x n array then it will have  m*n  elements and will require m*n*elements size bytes of storage.To allocate storage for an array you must reserve this amount of memory.The element of two-dimensional array are stored row wise .
int tab[3][3]={1,2,3,4,5,6,7,8,9};
It means that elements
table[0][0] =1;
table[0][1] =2;
table[0][2] =3;
table[1][0] =4;
table[1][2] =5;
table[1][3] =6;
table[2][0] =7;
table[2][1] =8;
table[2][2] =9;

ARRAY INITIALIZATION

Array can be initialized at the time of declaration.The initial values must appear in the order in which they will be assigned to the individual array elements,enclosed within the braces and separated by commas.

Syntax of array initialization :

data type array-name[size]={value 1,value 2......value n};

Value 1 is the  value for the  first array element,value 2 is the value for second element,value n is the value for n array element.When you are initializing the values at the time of declaration,then there is no need to specify size.

int[10]={1,2,3,4,5,6,7,8,910};

int[]={1,2,3,4,5,6,7,8,9,10};


Character Array Initialization

The array of characters is implemented as in C.Strings are handled differently as far as initialization is concerned.A special character called null character '\0', implicitly suffixes every string.When the external or static string character array is assigned a string constant,the size specification is usually omitted and is automatically assigned;it will include the '\0' character ,added at the end.For example,consider the following two assignment statements:

char thing[3]="TIN";
char thing[]="TIN";

In the above statements the assignments are done differently .The first statement is not a string but simply an array storing three characters 'T','I','N' and is same as writing:

char thing[4]={'T','I','N'};
whereas ,the second one is four character string TIN\0.The change in the first assignment,as given below,can make it a string.

Example

Write a program to illustrate how the marks of 10 students are read in an array and then used to find the maximum marks obtained by a student in the class.

#include<stdio.h>
#define SIZE 10 

main()
{
int i=0;
int max=0;
int stud_marks[SIZE];
for(i=0;i<SIZE;i++)
 {
printf("Student no.=%d",i++);
printf("Enter the marks out of 50: ");
scanf("%d",&stud_marks[i]);
}
for(i=0;i<SIZE;i++)
{
 if(stud_marks[i]>max)
max=stud_marks[i];
}

printf("\n\n The maximum of the marks obtained among all the 10 students: %d",max);
} 
OUTPUT
Student no.=1 Enter the marks out of 50:10
Student no.=2 Enter the marks out of 50:17
Student no.=3 Enter the marks out of 50:23
Student no.=4 Enter the marks out of 50:40
Student no.=5 Enter the marks out of 50:49
Student no.=6 Enter the marks out of 50:34
Student no.=7 Enter the marks out of 50:37
Student no.=8 Enter the marks out of 50:16
Student no.=9 Enter the marks out of 50:08
Student no.=10 Enter the marks out of 50:37

Array

  • Array is a data structure storing a group of elements , all of which are of same data type.
  • All the elements of an array share the same name,and they are distinguished from one another with the help of an index.
  • Random access to every element using a numeric index.
  • A simple data structure,used for decades,which is extremely  useful.
  • Abstract Data type list is frequently associated with the array data structure.




The declaration of an array is just like any variable declaration with additional size or dimension.In the following section we will see how an array is declared.

Syntax of declaration is as follows :

data-type array_name[constant-size];
 
          Data-type refers to the type of elements you want to store
          Constant-size is the number of elements

The following are  some declaration for arrays:
int char[80];
float farr[500];
static int iarr[80];
char charray[40];


There are two restrictions for using arrays in C :

  • The amount of storage for a declared array had to be specified at compile time before execution.This means that an array has a fixed size.
  • The data  type of an array  applies uniformly to all the elements ;for this reason,an array is called a homogeneous data structure.
Size Specification

The size of an array should be declared using symbolic constant rather a fixed integer quantity .The use of a symbolic constant makes it easier to modify a program that uses an array .All reference to maximize the array size can be altered simply by changing the  value of the symbolic constant. 

Example

Write a program to declare and read values in an array and display them.

#include<stdio.h>
#define SIZE 5

main()
{
int i=0;

int stud_marks[SIZE];
for(i=0;i<SIZE;i++)
{
printf("Element no.=%d",i+1);
printf("Enter the value of element");
scanf("%d",&stud_marks[i]);
 }
printf("\n Following are the values stored in the corresponding array elements:\n\n ")
 for(i=0;i<SIZE;i++)
{
printf("value stored in a [%d] is %d\n"i,stud_marks[i]);
}
}

OUTPUT
 Element no.=1 Enter the Value of the element=11
 Element no.=2 Enter the Value of the element=12
 Element no.=3 Enter the Value of the element=13
 Element no.=4 Enter the Value of the element=14
 Element no.=5 Enter the Value of the element=15

Values stored in a corresponding array elements:

Value stored in a[0] is 11
Value stored in a[1] is 12
Value stored in a[2] is 13
Value stored in a[3] is 14
Value stored in a[4] is 15

The Continue statement

Unlike break statement,which is used to jump the control out of the loop,it is sometimes required to skip some part of the loop and to continue the execution
with next loop iteration.Continue statement used inside the loop helps to bypass the section of a loop and passes the control to the beginning of the loop to continue the execution with the next loop iteration.The syntax is follows :

continue;  





Example

Write a program to print the first 20 natural numbers skipping the  number  divisible by 5.

#include<stdio.h>

main()
{
int i;
for(i=1;i<=20;i++)
{
if((i%5)==0)
 continue;
 printf("%d",i);
}
}

OUTPUT
 1 2 3 4 6 7 8 9 11 12 13 14 16 17 18 19

The break statement

Sometimes,it is required to jump a loop irrespective of the conditional test value.Break statement is used inside any loop to allow the control jump to the immediate statement following the loop.The syntax is as follows:

break;

When nested loops are used,then the break jumps the control from the loop where it has been used.Break  statement can be used inside any loop.
   Example 

Write a program to calculate the first smallest divisor o a number.

#include<stdio.h>

main()
{
int div,num,i;
printf("Enter any number: \n");
scanf("%d",&num);
for(i=0;i<=num;i++)
{
if((num%i)==0)
{
 printf("Smallest divisor for number %d"",num,i);
break;
}
}
}

OUTPUT
Enter any number:
9
Smallest divisor of 9 is 3

THE goto STATEMENT

The goto statement is used to alter the normal sequence of program instructions by transferring the control to some other portion of the program .The syntax is as follows:

goto label;

Here,label is an identifier that is used to label the statement to which control will be transferred.The targeted statement  must be preceded by the unique label followed by colon.

label : statement ;

Although goto statement is used to alter the normal sequence of program  execution but its usage in the program should be avoided.The most common application are:

1)To branch  around statements under certain conditions in place of use of if-else statement .

2)To jump to the end of the loop under certain  conditions by passing the rest of the statements inside the loop in place of continue statement.

3)To jump out of the loop avoiding the use of break statement.

goto can never be used to jump into the loop from outside and it should be preferably used for forward jump.

Situations may arise,however,in which the goto statement can be useful.To the possible extent,the use of the goto statement should generally be avoided.




EXAMPLE

Write a program to print first 10 even numbers.

#include<stdio.h>
main(){
int i=2;
while(i)
 {
printf("%d",i);
i=i+2;
if(i>=20)
goto outside;
}
outside:printf("over")
}

OUTPUT
2 4 6 8 10 12 14 16 18 20 over

Loop Control Statements

Loop Control Statements are used when a section of code may either be executed a fixed number of times,or while  same condition is true.C gives you a choice of three types of loop statements,while,do-while and for.

1) The while loop keeps repeating an action until an associated condition returns false.This is useful where are programmer does not know in  advance how many times the loop will be traversed.

2)The do while loop is similar,but the condition is checked after the loop body is executed.This ensures that the loop body is run at least once.

3)The for loop is frequently used,usually where the loop will be traversed a fixed number of times.


The While Loop 

When in a program a single statement or certain group of statements are to be executed repeatedly depending  upon certain test condition,the while statement is used.

The syntax is as follows:

while (test condition)
{
body_of_the_loop;
}

Here,test condition is an expression that controls how long the loop keeps running.Body of the loop is a statement  or group of statements enclosed in braces and are repeatedly executed till the value of test condition evaluates to true.As soon as the condition evaluates to false,the control jumps to the first statement following the while statement.If condition initially itself is false,the body of the loop will never be executed.While loop is sometimes called as entry-control loop,as it controls the execution of the body of the loop depending upon the value of test condition.


Example 

Write a program to calculate the factorial of a given input natural number.

#include<stdio.h>
#include<math.h>

main()
{
int x;
long int fact=1;
printf("Enter any number to find factorial:\n");
scanf("%d",&x);
while(x>0)
{
fact=fact*x;
x=x-1;
}
 printf("Factorial is %d",fact);
}

OUTPUT

Enter any number to find factorial;
4
Factorial is 24

The do...while Loop 

There is another loop control structure which is very similar to the while statement called as the do....while statement.The only difference is that the expression which determines whether to carry on looping is evaluated at the end of  each loop.The syntax is as follows:

do{
statements(s);
}while(test condition);

In do-while loop,the body of loop is executed at least once before the condition is evaluated.Then the loop repeats body as long as condition is true.However,in while loop,the statement doesn't execute the body of the loop even once,if condition is false.That is why do-while loop is also called exit-control loop.


Example 

Write a program to print first ten  even natural numbers.

#include<stdio.h>
main()
{
int i=0;
int j=2;
do{
print("%d",j);
j=j+2;
i=i+1;
}
while(i<0);
}

OUTPUT
2 4 6 8 10 12 14 16 18 20


The for Loop

for statement makes it more convenient to count iterations of a loop and works well where the number of iterations of the loop is known before the loop is entered .The syntax is as follows:

for(initialization;test condition;increment or decrement)
{

statement(s);
}
The main purpose is to repeat statement while condition remains true,like the while loop.But in addition,for provides places to specify an initialization instruction and an increment or decrement of the control variable instruction.So this loop is specially designed to perform a repetitive action with a counter .



Example 

Write a program to print first n natural numbers.


#include<stdio.h>
main()
{
int i,n;
printf("Enter the value of n \n");
scanf("%d",&n);
printf("\n The first %d natural numbers are : \n",n);
for(i=1;i<=n;i++)
{
printf("%d",i);
}
}


OUTPUT

Enter value of n
6
The first 6 natural numbers are :
1 2 3 4 5 6

Decision Control Statement

In a C program ,a decision causes a one-time jump to a different part of a program , depending on the value of an expression.Decisions in C can be made in several ways.The most important is with the if..else statement,which chooses between two alternatives.This Statement can be used without the else ,as a simple if statement.Another decision control statement ,switch ,creates branches for multiple alternative sections of code, depending on the value of a single variable .


Types of Decision Control Statement :-

1) if statement

2)if...else statement

3)Nested if ... else statement

4)Else if statement

5)Switch statement


Simple if statement

It is used to execute an instruction or block of instructions only if a condition is fulfilled

The syntax is as follows:

if(condition)

{

 block of statements;

}



Example :

Write a program to calculate the net salary of an employee,if a tax of 15% is levied on his gross-salary if it exceeds Rs. 10,000 /- per month .

 #include<stdio.h>
 OUtput  main()
{
float gross_salary,net_salary;

printf("Enter gross salary of an employee\n");
scanf("%f",&gross_salary);

if(gross_salary<10000)
  net_salary=gross_salary;

if(gross_salary>=10000)
 net_salary=gross_salary-0.15*gross_salary;

printf("\n Net salary is Rs. %.2f\n",net_salary);
}

OUTPUT

Enter gross salary of an employee
9000
Net salary is Rs.9000.00

Enter gross salary of any employee
10000

Net Salary is Rs.8500.00

 
 If...else statement

if...else statement is used when a different sequence of instructions is to be executed  depending on the logical value (True/False) the condition evaluated.


The syntax is as follows:

if(condition)
{
statement_1_block ;
}
 else{

statement_2_block ;

}
Statement_3_block;



Example

Write a program to print whether the given  number is even or odd.

#include<stdio.h>

main()
{
int x;
 printf ("Enter a number :\n");
 scanf("%d",&x);
if(x%2==0)
printf("\n Given number is even\n");
else
printf("\n Given number is odd \n");
}

 OUTPUT
 Enter a number :
6
Given number is even
Enter a number:
7
Given number is odd

Nested if..else Statement

in nested if..else statement,an entire if..else construct is written within either the body of the if statement or the body of an else statement.the syntax is as follows:

The syntax is as follows:

if(condition1)
{
 if(condition2)
{
 Statement_1_block;
}
else{
Statement_2_block;
}
}
else
{
Statement_3_block;
}
Statement_4_block;


Example

Write a program to calculate an Air ticket fare after discount,given the following conditions:
1)If passenger is below 14 years then there is 50 %  discount on fare .
2)if passenger is above 50 years then there is 20 % discount on fare .
3)if passenger is above 14 and below 50 then there is 10 % discount on fare.


#include<stdio.h>
main()
{
int age;
float fare;
printf("\n Enter the age of passenger :\n");
scanf("%d",&age);
printf("\n Enter air ticket fare \n");
scanf("%f",&fare) ;
if(age<14)
fare=fare-0.5*fare;
else
if(age<=50)
{
fare=fare-0.1*fare;
}
else
{
fare=fare-0.2*fare;
}
printf("\n Air ticket fare to be charged after discount is %0.2f",fare);
}
 
OUTPUT

Enter the age of passengert
12
Enter the Air ticket fare
2000.00
Air ticket fare to be charged after discount is 1000.00

Else if statement 

To show a multi-way decision based on several conditions,we use the else if statement.This works by cascading of several comparisons.As soon as one of the conditions is true,the statement or block of statement following them is executed and no further comparisons are performed.The syntax is as follows:

if(condition_1)
{
Statement_1_block;
 }
else if
{
Statement_2_block;
}  

 
 .......
else if (Condition_n)
{

Statement_n_block;
}
 else
Statement_x;



Example

Write a program to award grades to students depending upon the criteria mentioned below:
1) Marks less than or equal to 50 are given "D" grade.
2)Marks above 50 but below 60 are given "C" grade.
3)Marks above 60 to 75 are given "B" grade.
4)Marks above 75 are given "A" grade.


#include<stdio.h>
main()
{
int result;
printf("Enter total marks of a student:\n") ;
scanf("%d",&result);
if(result<=50)
printf("Grade D \n");
else if (result<=60)
printf("Grade C \n");
else if (result<=75)
printf("Grade B\n");
else
printf("Grade A"\n);
}

OUTPUT 
Enter the total marks of a student:
80
Grade A

 
Switch statement

Its objective is to check several possible constant values for an expression,something similar to what we had studied in the earlier sections,with the linking of several if and else if statements.When the actions to be taken depending on the  value of control variable ,are large in number,then the use of control structure Nested ....if else makes the program complex .There switch statement can be used.

Syntex is as follows:

switch(expression){
case expression 1 :
block of instructions 1
break;
case expression 2:
bock of instructions 2
break;
..
case expression n:
block of instruction n
break;

default:
default block of instructions 

}


Example

Write a  program that performs the following ,depending upon the choice selected by the user .
1)calculate the square of number if choice is 1.
2)calculate the square rooot of number if choice is 2 and 4 .
3)calculate the cube of given number if the choice is 3.
4)otherwise print the number as it is .


main()
{

int choice,n;
printf("\n nter any number :\n");
scanf("%d",&n) ;
printf("choice is as follows:\n\n");
printf("1.To find the square of a number\n");
printf("2.To find the square-root of a number\n");
printf("3.To find the cube of a number\n");
printf("4.To find the square-root of a number\n\n");;

printf("Enter your choice\n");
scanf("%d",&choice) ;
switch(choice)
{
case 1 :  printf("The square of a given  number is %d\n" ,n*n);
break;
case 2:printf("The square-root of a given number is %f \n" ,sqrt(n));
break;
case  3 : printf("The cube of a given number is %d\n" ,n*n*n);
 break;
case 4 :printf("The square-root of a given number is %f \n" ,sqrt(n));
break;
default: printf("The given number is %d\n" ,n);
break;


}
}

OUTPUT

Enter any number :
4
Choice as follows :
1.To find the square of a number .
2.To find the square root of a number .
3.To find cube of a number .
4.To find the square-root of a number
Enter your choice :
2
The square-root of  given number is 2

Algorithm to check whether the given number is prime or not.

Write an algorithm to check whether the given number is prime or not.


1.Start

2.Read the number num

3.[Initialize]

    i=2 , flag=1

4. repeat steps 4 through 6 until i < num or flag=0

5.rem=num mod i

6.if rem=0 then

flag=0

 else

    i=i+1

7.if flag=0 then
   
              Print number is not Prime

     else
              Print number is prime

8. Stop

How to Change Mac Address of a device

 Mac address is a address  is a address which is assigned by a manufacturer .
Firstly you have to type ifconfig command in your terminal ,then it will show all the devices connect to your computer and their ip and Mac address.

Step 1: Type ifconfig



Step 2 : Type ifconfig wlan0(Device Name) down


Step 3 : Type ifconfig wlan0 hw ether (00:22:44:33:66:44) give the mac address which you want to give

Step 4 :Type Ifconfig wlan0 up
 Step 5 : Type ifconfig to check