c_cpp3

 Paper DSC 203:PROGRAMMING WITH C & C++

UNIT-IINTRODUCTION TO C LANGUAGE, VARIABLES, DATA TYPES AND OPERATORS INTRODUCTION: TYPES OF LANGUAGES- HISTORY OF C LANGUAGE – BASIC  TRUCTURE –PROGRAMMING RULES – FLOW CHARTS-ALGORITHMS–COMMONLY USED LIBRARY FUNCTIONS - EXECUTING THE C PROGRAM - PRE-PROCESSORS IN “C”- KEYWORDS & IDENTIFIERS – CONSTANTS – VARIABLES: RULES FOR DEFINING VARIABLES - SCOPE AND LIFE OF A VARIABLE–- DATA TYPES - TYPE CONVERSION - FORMATTED INPUT AND OUTPUT OPERATIONS. OPERATORS: INTRODUCTION – ARITHMETIC – RELATIONAL – LOGICAL – ASSIGNMENT - CONDITIONAL - SPECIAL - BITWISE - INCREMENT / DECREMENT OPERATOR.

UNIT-II: WORKING WITH CONTROL STATEMENTS, LOOPS CONDITIONAL STATEMENTS: INTRODUCTION - IF STATEMENTS - IF-ELSE STATEMENTS – NESTED IF-ELSE – BREAKSTATEMENT-CONTINUE STATEMENT-GO TO STATEMENT-SWITCH STATEMENTS. LOOPING STATEMENTS: INTRODUCTION-WHILE STATEMENTS – DO-WHILE STATEMENTS - FOR STATEMENTS-NESTED LOOP STATEMENTS.

UNIT-III: FUNCTIONS, ARRAYS AND STRINGS FUNCTIONS: DEFINITION AND DECLARATION OF FUNCTIONS- FUNCTION PROTO TYPE-RETURN STATEMENT- TYPES OF FUNCTIONS-FORMATTED AND UNFORMATTED FUNCTIONS. BUILT IN FUNCTIONS: MATHEMATICAL FUNCTIONS - STRING FUNCTIONS - CHARACTER FUNCTIONS - DATE FUNCTIONS.USER DEFINED FUNCTIONS: INTRODUCTION - NEED FOR USER DEFINED FUNCTIONS - ELEMENTS OF FUNCTIONS – FUNCTION CALL – CALL BY VALUE AND CALL BY REFERENCE - RECURSIVE FUNCTIONS.ARRAYS: INTRODUCTION - DEFINING AN ARRAY - INITIALIZING AN ARRAY –CHARACTERISTICS OF AN ARRAY- ONE DIMENSIONAL ARRAY – TWO DIMENSIONAL ARRAY – MULTI DIMENSIONAL ARRAY. STRINGS: INTRODUCTION - DECLARING AND INITIALIZING STRING - READING AND WRITING STRINGS - STRING STANDARD FUNCTIONS.

UNIT-IV: POINTERS, STRUCTURES AND UNIONS POINTERS: FEATURES OF POINTERS- DECLARATION OF POINTERS-ARITHMETIC OPERATIONS WITH POINTERS STRUCTURES: FEATURES OF STRUCTURES - DECLARING AND INITIALIZATION OF STRUCTURES –STRUCTURE WITHIN STRUCTURE- ARRAY OF STRUCTURES- ENUMERATED DATA TYPE-UNIONS-DEFINITION AND ADVANTAGES OF UNIONS COMPARISON BETWEEN STRUCTURE & UNIONS.

UNIT-V: OBJECT ORIENTED CONCEPTS USING C++ OBJECT ORIENTED PROGRAMMING: INTRODUCTION TO OBJECT ORIENTED PROGRAMMING - STRUCTURE OF C++ – SIMPLE PROGRAMOF C++– STORAGE CLASSES-SIMILARITIES AND DIFFERENCES BETWEEN C & C++ - DATA MEMBERS-MEMBER FUNCTIONS - OBJECT ORIENTED CONCEPTS-CLASS-OBJECT-INHERITANCE- OLYMORPHISM- ENCAPSULATION-ABSTRACTION.  

UNIT-III:

FUNCTIONS, ARRAYS AND STRINGS

Functions:

A function is a self-contained block of program statements that performs a particular task.

Every C program can be thought of as a collection of these functions.

C provide a way of breaking up a program into segments or modules. These segments are called functions.

Why are functions needed?

Functions provides the following  benefits:

  •   Functions makes a program more manageable and easy to understand.
  •   Writing functions avoids rewriting the same code over and over.
  •  A function may be called as many times as needed.
  •  The main program can consist of a series of function calls. They can be executed as many times as needed.
  • Functions may be reused in multiple programs. This enables code sharing.
  • Functions can be used to protect data. The data defined with in a function is called the local data. It is available only within that function.
  • By using functions many programmers can work on a project by dividing it into different functions.

Types of functions

There are basically two types of functions:

  •   Library functions (or) Built in functions
  •   User-defined functions (or) Programmer-defined functions

Library functions:

1.Explain Various Library functions in C?


Ans:

library functions are nothing but commonly required functions grouped together and stored in Library. This library of functions is present on the disk and is written for us by people who write compilers for us. Always a compiler comes with a library of standard functions. The procedure of calling both types of functions is exactly same.

Ex. printf( ), scanf( ) etc.

The functions have been classified into broad categories.

Mathematical functions

These Functions available in math.h header file

#include<stdio.h>

#include<conio.h>

#include<math.h>

main()

{

int a,b;

clrscr();

printf(“Enter the value of a”);

scanf(“%d”,n);

b=sqrt(a);

printf(“square root of%d is %d”,a,b);

getch();

return();

}


Output:

Enter the value of a :25

Square root of 25 of 5

String Functions


These String functions available in string.h header file

Write a C program to illustrate String functions in C.

#include <stdio.h>

#include <string.h>

int main()

{

char s1[20] = "Sri";

char s2[20] = " kranthi";

char s3[40];

printf("Initially Length of string1 is : %d",strlen(s1));

printf("Length of string2 is : %d", strlen(s2));

if (strcmp(s1, s2) ==0)

{

printf("string 1 and string 2 are equal");

}else

{

printf("string 1 and 2 are different");

}

strcat(s1,s2);

strcpy(s3,s1);

printf("Modified String s1 is: %s", s1);

printf("String s2 is: %s", s2);

printf("String s3 is: %s", s3);

getche();

retrn 0;

}

I/O:

Initially Length of string1 is: 3

Length of string2 is: 7

String1 nd String2 are different

Modified String1 is : Sri kranthi

String2 is : Sri

String3 is : Sri kranthi

Character Functions :

These Character functions are available in <type.h> header file.


#include<stdio.h>

#include<conio.h>

void main()

{

char s='a';

if(isalpha(s))

{

printf( "It is a character");

}

getch();

}

Output:

It is a character

 Date and Time Function

C provides a large collection of date and time functions. They are used to perform the operations such as , retrieval of current date and time ,manipulation of time, conversion of date formats, etc. The prototype of these functions are declared in <time.h> header file.

The date and time functions are as bellow

a)setdate() The setdate() function adjusts the date of the system.

(b)getdate() The getdate() function provides the current date of the operating system.

(c)Clock() clock() function provides the current time of the system

(d)time() The time() function provides the current time of the system in the structured form

(e)difftime() The difftime() function takes two times as arguments and returns the difference between them

(f)strftime() The strftime() function changes the current fromat of the time.

(g)ctime() The ctime() function returns the date and time in the form of a string

(h)gmtime() The gmtime() function provides the universal time

#include<stdio.h>

#include<conio.h>

void main()

{

time_t tim;

time(&tim);

printf("Today's date and time :%s",ctime(&tim));

getch();

}

Output:  Todays date and time Thu jun 30 10:05:15 2019

                                                                                    --O--

I/O Functions

2.Explain I/O Functions in C language?

Ans:

C has a number of standard functions to perform input and output operations.

In C, The input/output (I/O) functions are of two types:

1. Un-formatted input/output functions

2. Formatted input/output functions.

Formatted input/output functions

The I/O statements that use specific format codes for their I/O are known as Formatted I/O functions.

These functions can handle different data types.There are two important formatted I/O functions in C:

1. scanf()

2. printf()

printf():  printf() is a formatted output statement. It can print the specified contents on the screen. It has the following format:

Formatting codes for printf(),scanf()

printf(“control_string”, variable1, variable2,variable3,...);

Here, The control string is also known as “Format String”. The format string may contain three types of objects:

1. Ordinary characters : These are copied to output.

2. Format specifier field: It is denoted by % and the code.

3. Control code: It includes control characters such as \n, \b, and \t.

printf() uses format codes as shown in table.

scanf():

scanf() is a formatted input statement. It can read the given input from the keyboard. It has the following format:

scanf(“control_string”,variable1_address,variable2_ address,...);

Here, The control string is also known as “Format String”.

Example: Write a C Program to add two integer numbers and find their Sum

Solution

#include <stdio.h>

main()

{

int a,b,c;

printf(“\nEnter the first number: ”);

scanf(“%d”,&a);

printf(“\nEnter the second number: ”);

scanf(“%d”,&b);

c=a+b;

printf(“Sum = %d \n”,c);


return 0;

}

Output

Enter the first number : 5

Enter the second number: 10

Sum= 15

Escape sequences

Escape sequences are the control codes that can be used to control the output as required. C has the following escape sequence characters:

Non-formatted input/output functions

The I/O statements that does not use format codes are known as Non-Formatted I/O functions.

These functions can handle one character at a time. There are two important non-formatted I/O functions in C:

1. getchar()

2. putchar()

getchar(): -

It can read a single character at a time. It has the following format:

char_variable = getchar();

Example:                   int ch;

ch = getchar();

The getchar()function reads a character and places it in the memory location “ch”

putchar():-

It can displays a single character at a time on the monitor screen. It has the following format:

putchar(char_variable);

Example:       int ch = ‘x’;

puchar(ch)’

The putchar() function displays the character stored in the memory location “ch”.           

1. Write a C program to display a keyed in character.

Solution

#include<stdio.h>

main()

{

int ch;

ch=getchar();

putchar(ch);

return 0;

}

I/O

Input A

Output A

User-defined functions:

3.Explain the concept of user defined function in C?

Ans:


The functions which are developed by user at the time of writing a program are called user-defined functions. So, user-defined functions are functions created and developed by user.

The need for user-defined functions

Every program in a C language needs a main function where it as to begin its execution. In some cases ,using a single “main function to code a complete program may result in the development of very large program, with complications. Such programs are difficult to debug ,test and maintain .

For this reason , a program in “C” is divided into a number of functions which are combined in a later stage into a single unit. Such functions are known as “sub programs” or “user defined functions”.

User defined functions are also very helpful in program where certain operations or calculations are repeated. A function can be designed for required operation and can be called at the points where it is required .This the process saves both time and space.

Advantages:

1. The length of source program can be reduced by using the function only at appropriate places.

2. A function can be located easily for the investigation which has to be done in future

3. A sub function can also be reused by a number of other individual programs.

                                                                        --O--

Elements of User-defined functions:

4.Explain Various Elements in User-defined function?

Ans

1.function declaration or function prototype

2. function definition

3. function call

1. Function Declaration or Function prototype :

In C, a user defined function should be declared before using it in the program. A declaration that contains the function’s return type, function name and a list of parameters is known as the Function Prototype. The compiler uses function prototypes to validate function calls. A function prototype has the following format:

return_data_type function_name (data_type_list);

 The function declaration consists of four parts. They are,

function_name: This is the name given to the function.

return_data_type: This specifies the type of data given back to the calling function.

data_type_list : This list specifies the data type of the variables. These are also known as the formal parameters.

terminating semi colon: States end of the line

Examples:

1.      double power(double, int);

2.      int isPrime(int);

3.      void printMessage(void);

4.      void fibo_series(int);

2. Function Definition:

A list of statements in the program that describes the specific task done by the function is called a function definition. It consists of the function header and the function body.

The function definition has the following form:

return_data_type functionname(data_type_list)

{

/* Function Body */

}

Function Header:

The function header consists of three parts:

return_data_type: A return_data_type specifies the type of value (like float or double) that the function is expected to return to the calling program. If the return type is not explicitly specified, c will assume that it is an integer type.

Function name: The name should be appropriate to the task performed by the function.

data_type_list : This list specifies the data type of the variables.

Function Body: The function body is enclosed in braces, contains three parts in the order given below

(i) Local variable declaration: Local variable declarations are statements that specify the variables needed by the function.

(ii) Function statements: Function statements are statements that perform the task of the function.

(iii) Return Statements:

The return statement returns the value of result to the calling function.

The return statement has the following form:

return expression;

or

return(expression);

A void function does not return any value. It only returns the control from called function to calling function.

Example

int sum(int x, int y)

{

int s;

s = x+y;

return(s);

}

void multiply(int a, int b)

{

int p;

p = a*b;

printf(“\n Product = %d”,p);

}

3. Function call:

A function must be called (invoked) in order to execute it. A function call statement has the following form:

function_name(List of formal parameters);

or

variable_name = function_name(List of formal parameters);

A function can be called by simply using the function name followed by a list of actual parameters.

A function which calls another function is known as a Calling Function. A function which responds to a function call is known as a Called function.

Ex: Here in the main ( ) program the mul(10,5) Function has been called.

main ( )

{

int y;

y=mul(10,5);                                                      //function call//

printf(“%d”,y);

}

Write a C program that uses a function to convert temperature from Fahrenheit scale to Celsius scale.

#include <stdio.h>

float ftoc(float);                                                             // Function prototype

int main(void)

{

float tf;

float tc;

printf(“\n Enter the Temperature in Fahrenheit: ”);

scanf(“%f”, &tf);

tc = ftoc(tf);                                                                 //Function calling

printf(“%f Fahrenheit equals %f Celsius \n”, tf,tc);

return 0;

}

                                                                        /* FUNCTION DEFINITION */

float ftoc(float f)                                                         //Function header

{

float factor = 5.0/9.0;

float freezing = 32.0;

float celsius;

celsius = factor (f - freezing);

return celsius;

}

                                                                        --O--

Types of functions based on return values

All C functions can be called either with arguments or without arguments in a C program. These functions may or may not return values to the calling function. Now, we will see simple example C programs for each one of the below.

  1.   C function with arguments (parameters) and with return value.
  2.   C function with arguments (parameters) and without return value.
  3.   C function without arguments (parameters) and without return value.
  4.   C function without arguments (parameters) and with return value.

1. Functions With arguments and with return values

These are the functions in which parameters are passed from calling function to the called function and values are returned from called function to the calling function.

Syntax

int function( int a )

{

statements;

return a;

}

Example:

#include<stdio.h>

#include<conio.h>

void main()

{

int i=0,j =5,x;

int demo(int x,int y);

x=demo(i,j );                                      /* accepts return values* /

printf("sum =%d",x);                           /* it has arguments* /

getch();

}

int demo(int x,int y)

{

printf("This is a demo program");

return(x+y);                               /* returns value of(x+y)* /

}

output:

This is demo program sum =15

2.Functions With arguments and without return values

These are the functions in which arguments are passed from calling function to the called function but no values are returned from called function to the calling function.

Syntax:

void function(int a)

{

statements;

}

3.Functions Without arguments and without return values

These are the functions in which no parameters are passed from calling function to the called function and no values are returned from called function to the calling function

Syntax:

void function()

{

statements;

}

4.Functions Without arguments and with return values

These are the functions in which no arguments are passed from calling function to the called function but values are returned from called function to the calling function

Syntax:

int function( )

{

statements;

return a;

}

Data Passing techniques to a function

5.Explain the concepts of Call by value and call by reference with example?

Ans: Data can be passed to a function by using two techniques:

1. Pass by value or Call by value

2. Pass by reference or Call by reference.

Call by value mechanism

Calling a function by passing values as arguments is known as call by value.

In call by value, a copy of the data is sent to the formal parameters of the called function. So that the function cannot directly modify the values of the arguments.

Example:

#include <stdio.h>

int mul(int num);                     /* function prototype */

main(void)

{

int result,num = 3;

printf(“\n Before function call: num = %d ”, num);

result = mul(num);

printf(“\n After return from function: result = %d”,

result);

printf(“\n After return from function: num = %d”,

num);

return 0;

}

int mul(int num)                /* function definition */

{

num *= 10;

return num;

}

I/O:

Before function call.: num = 3,

After return from function: result = 30

After return from function: num = 3

Call by Reference  Call by reference is possible with the help of pointers.

Calling a function by passing addresses as arguments is known as Call by Reference. By using call by reference, you can change the values at calling  function.

For example,

swap(&x, &y);

Example:

#include <stdio.h>

int swap(int*, int*);

int main()

{

int x=5,y=10;

printf(“%d %d\n”,x,y);

swap(&x, &y);

printf(“%d %d\n”,x,y);

return 0;

}

void swap(int *a, int *b)

{

int temp;

temp = *a;

*a = *b;

*b = temp;

}

Output

5    10

10   5

                                                                                    --O--

Recursion

6.What is recursion? Explain with example?

Ans: Calling a function by itself is known as Recursion.  A function that calls itself is known as a Recursive function.

The recursion continues until some condition is met to stop it. if...else statement can be used to stop a recursive call.

main()

{

………

……....

recursive();

…………

………….

}

int recursive()

{

………..

recursive()

………..

}

Example: Write a C Program to generate Fibonacci Series by using Recursion.

#include <stdio.h>

#include <stdlib.h>

int fib(int);                                                 /* function prototype */

int main()

{

int i,j;

printf(“\n Enter the number of terms: ”);

scanf(“%d”,&i);

printf(“\n Fibonacci sequence for %d terms is:”,i);

for( j=1; j<=i; j++)

printf(“ %d”,fib(j));

getche();

return 0;

}

int fib(int val)                                             // Recursive Function

{

if(val <= 2)

return 1;

else

return(fib(val - 1) + fib(val - 2));                 // Recursive call

}

Output

(a) Enter the number of terms: 6

Fibonacci sequence for 6 terms is: 1 1 2 3 5 8

(b) Enter the number of terms: 4

Fibonacci sequence for 4 terms is: 1 1 2 3

                                                                        --O—

Example Write a C Program to find the factorial of the given number by using recursion

#include<stdio.h>

#include<conio.h>

int factorial(int n);

main()

{

int n,f;

clrscr();

printf("Enter a Number:");

scanf("%d",&n);

f=factorial(n);

printf("\n Factorial of %d is = %d ",n,f);

getche();

return 0;

}

int factorial(int n)

{

int fact;

if(n = =1)

return(1);

else

fact=n*factorial(n-1);

return(fact);

}

output

===========

Enter a Number : 4

Factorial of 4 is = 24


Arrays

Introduction:

Generally, A variable can store only one value at a time.

7.What is an array ?Explain 1D Array with example?

Ans:

Definition:

An array is a collection of data elements that are ordered, fixed in size, and homogeneous.

An array is a derived data type. It can store huge quantities of data.

In C, arrays are of two types:

  1.   one-dimensional arrays
  2.   Multidimensional arrays

One-dimensional Array:

An array that can have single subscript (index) is known as a one-dimensional array. Its index starts at 0 and ends at size-1.

Declaration of a One-dimensional Array

An array declaration has 3 attributes:

  •       The type of data i.e., int, char, double, float, etc.
  •        The number of values i.e., the maximum number of elements
  •      A name

A one-dimensional array can be declared by using the following syntax:

data_type    array_name [SIZE];

Example: int ar[10];

This can declare a one dimensional array with 10 elements of integer type.

Initializing Integer Arrays

Arrays can be initialized by using the following format:

datatype   array_name[size] = {Elements};

Example: int arr[5] = { 1,2,3,4,5}

or

int array[ ]={1,2,3,4,5}

This can create and initialize a one dimensional array, as shown in fig:


Accessing array elements:

An array element can be referenced as:    < array name>[<index>]

Here, <index> is an integer constant or variable ranging from 0 to <size>– 1.

Example:       arr [0] = 98;

arr [1] = 75;

arr[2] = 80;

arr [3] = 95;

arr[4] = 98;

total = arr[0] + arr[1] + arr[2] + arr[3] + arr[4];

Example: Write a c program to illustrate one dimensional arrays?

#include <stdio.h>

main()

{

int i, a[10];

for(i = 0; i< 10; i++)

{

a[i] = i;

printf(“a[%d] = %d\n”, i, a[i]);

}

printf(“\n”);

return 0;

}

I/O

a[0] = 0

a[1] = 1

a[2] = 2

a[3] = 3

a[4] = 4

a[5] = 5

a[6] = 6

a[7] = 7

a[8] = 8

a[9] = 9

                                                                        --O--

2. Write a C program to calculate Fibonacci series by using arrays concept.

/* Fibonacci series is a series in which any element is the sum of the previous two elements.*/

#include <stdio.h>

main()

{

int fib[15],i;

fib[0] = 0;

fib[1] = 1;

for(i = 2; i < 15; i++)

fib[i] = fib[i-1] + fib[i-2];

for(i = 0; i < 15; i++)

printf(“ %3d ”, fib[i]);

getche();

return 0;

}

Output:

0 1 1 2 3 5 8 13 21 34 55 89 144

Write a C program to search for an element in the array.

#include <stdio.h>

#include<conio.h>

#include <stdlib.h>

main()

{

int a[30],n,i,key, FOUND=0;

clrscr();

printf(“\n How many numbers”);

scanf(“%d”, &n);

printf(“\n Enter the array elements \n”);

for(i=0 ; i<n; i++)

scanf(“%d”, &a[i]);

printf(“\n Enter the key to be searched \n”);

scanf(“%d”,&key);

for(i=0 ; i<n; i++)

if(a[i] == key)

{

printf(“\n Found at %d”,i);

FOUND=1;

}

if(FOUND = = 0)

printf(“\n NOT FOUND...”);

getche();

return 0;

}

I/O: How many numbers:5

Enter array elements: 3 6 9 12 16

Enter the key to be searched: 9

Found at 2

Two dimensional array – Multi dimensional array

8.What is 2D array ?Explain with example?

Ans:

Arrays with more than one dimension are called multidimensional arrays.

Declaring a Two-dimensional Array:

An array of two dimensions can be declared as follows:

data_type array_name[size1][size2];

Here, data_type is any valid data type. Size1 is the number of rows and Size2 are the number of columns.


Initialization of a Multidimensional Array:

Arrays can be initialized by using the following format:

datatype array_name[size1] [size2] = {Elements};

Example:

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

Accessing array elements:

An 2D-array elements can be referenced as:  <array name>[<RowIndex>][<Column Index>]

Here, <index> is an integer constant or variable ranging from 0 to <size>– 1.

Example:

arr [0][0] = 1;

arr [0][1] = 2;

arr [0][2] = 3;

arr [1][0] =4;

arr [1][1] = 5;

arr[1][2] = 6;

arr [2][0] = 7;

arr [2][1] = 8;

arr[2][2] = 9;

total = arr[0][0] + arr[0][1] + arr[0][2] + arr[1][0]+arr[1][1]+ arr[1][2] + arr[2][0] + arr[2][1] + arr[2][2] ;

Working with Two-dimensional Arrays:

The most important application of the two dimensional array is with a matrix. A matrix is defined as an ordered rectangular array of numbers.

Example: Write a C Program to perform Matrix Addition.

#include<stdio.h>

#include<conio.h>

main()

{

int r,c,i,j, a[10][10],b[10][10],c[10][10];

clrscr();

printf("Enter the Order of matrix:");

scanf("%d %d",&r,&c);

printf("\nEnter the first matrix:");

for(i=0;i<r;i++)

for(j=0;j<c;j++)

scanf("%d",&a[i][j]);

printf("\nEnter the second matrix:");

for(i=0;i<r;i++)

for(j=0;j<c;j++)

scanf("%d",&b[i][j]);

c[i][j]=0;

for(i=0;i<r;i++)

for(j=0;j<c;j++)

c[i][j]=a[i][j]+b[i][j];

printf("\nThe result matrix is:\n");

for(i=0;i<r;i++)

{

for(j=0;j<c;j++)

{

printf(" %d ",c[i][j]);

}

printf("\n");

}

getche();

return 0;

}

Output:

Enter the Order of matrix: 2 2

Enter the first matrix:

1 2

3 4

Enter the second matrix:

4 3

2 1

The result matrix is:

5 5

5 5

                                                                                    --O--

Characteristics of Arrays

1) An array holds elements that have the same data type.

2) Array elements are stored in subsequent memory locations.

3) Two-dimensional array elements are stored row by row in subsequent memory locations.

4) Array name represents the address of the starting element.

5) Array size should be mentioned in the declaration. Array size must be a constant expression and not a variable.

Strings(One-dimensional Character Arrays)

9.What is String ? Explain with example?

Ans:

A String is an arrays of characters. In C, a String can be terminated by a null character(\0).

Declaring a String   Strings can be declared like one-dimensional arrays.

For example:                         char name[30];

char address[80];

String Initialization            Strings allow a shorthand initialization, for example,

char str[9] = “I like C”;

char msg[] = “Hello”;

Reading a String     The format code %s can be used to read a string with scanf().

For example:                         scanf("%s', &name);

Printing Strings       The format code ‘%s’ can be used to print strings by using printf().

For example, printf(“%s”,name);

Write a C Program to illustrate Strings:

#include<stdio.h>

main()

{

char str[50];

printf(“Enter a string”);

scanf(“%s”,str);

printf(“The string was :%s\n”,str);

return 0;

}

I/O:

(a) Enter a string: Ritchie

The string was :Ritchie

                                                                        --O---

String standard functions(String Manipulation)

10.Explain various String Handling Function in C language?

Ans:

C provides many functions to manipulate strings. All the string functions are available with <string.h>. Some of the functions in <string.h> are:

Table: string manipulation functions available in string.h

Counting number of characters in a string

strlen() function can be used to find the length of a string. It has the following format:

strlen(str);

Example:                   int l;

char s1[9]="Mahathma";

l=strlen(s1);

it reurns 9 to the variable l.

Copying a string into another

In C, strcpy() function can be used to copy one string to another. It has the following format:

strcpy(s1,s2);

Comparing strings  strcmp() function can be used to compare two strings.

It returns the value zero if the strings are equal. It returns a positive value if the first string is greater than the second string. It returns a negative value if the first string is lesser than the second string.

It has the following format:

strcmp(s1,s2)

Putting strings together  strcat() function can concatenate two strings together.

It has the following format:

strcat(s1,s2)

Write a C program to illustrate String functions in C.

#include <stdio.h>

#include <string.h>

int main()

{

char s1[20] = "Sai";

char s2[20] = " Vikrant";

char s3[40];

printf("Initially Length of string1 is : %d",

strlen(s1);

printf("Length of string2 is : %d", strlen(s2);

if (strcmp(s1, s2) ==0)

{

printf("string 1 and string 2 are equal");

}

else

{

printf("string 1 and 2 are different");

}

strcat(s1,s2);

strcpy(s3,s1);

printf("Modified String s1 is: %s", s1);

printf("String s2 is: %s", s2);

printf("String s3 is: %s", s3);

getche();

retrn 0;

}

I/O:

Initially Length of string1 is: 3

Length of string1 is: 7

String1 nd String2 are different

Modified String1 is : Sai Vikrant

String2 is : Sai

String3 is : Sai Vikrant

No comments:

Post a Comment