C Question

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 17

13.(a) Explain For statement with example?

A for loop is a repetition control structure that allows you to efficiently


write a loop that needs to execute a specific number of times.

Syntax

The syntax of a for loop in C programming language is −


for ( init; condition; increment ) {
statement(s);
}
Here is the flow of control in a 'for' loop −
 The init step is executed first, and only once. This step allows you to
declare and initialize any loop control variables. You are not required to put
a statement here, as long as a semicolon appears.
 Next, the condition is evaluated. If it is true, the body of the loop is
executed. If it is false, the body of the loop does not execute and the flow of
control jumps to the next statement just after the 'for' loop.
 After the body of the 'for' loop executes, the flow of control jumps back up
to the increment statement. This statement allows you to update any loop
control variables. This statement can be left blank, as long as a semicolon
appears after the condition.
 The condition is now evaluated again. If it is true, the loop executes and the
process repeats itself (body of loop, then increment step, and then again
condition). After the condition becomes false, the 'for' loop terminates.

Flow Diagram
Example

Live Demo
#include <stdio.h>

int main () {

int a;

/* for loop execution */


for( a = 10; a < 20; a = a + 1 ){
printf("value of a: %d\n", a);
}

return 0;
}

14.(a) Explain How will you initialize a string variable? in c

Strings in C
Strings are defined as an array of characters. The difference between a character
array and a string is the string is terminated with a special character ‘\0’.

Declaration of strings:

Declaring a string is as simple as declaring a one-dimensional array. Below is the


basic syntax for declaring a string.
char str_name[size];
In the above syntax str_name is any name given to the string variable and
size is used to define the length of the string, i.e the number of characters strings
will store. Please keep in mind that there is an extra terminating character which is
the Null character (‘\0’) used to indicate the termination of string which differs
strings from normal character arrays.

Initializing a String: A string can be initialized in different ways. We will


explain this with the help of an example. Below is an example to declare a string
with name as str and initialize it with “GeeksforGeeks”.

1. char str[] = "GeeksforGeeks";

2. char str[50] = "GeeksforGeeks";

3. char str[] = {'G','e','e','k','s','f','o','r','G','e','e','k','s','\0'};

4. char str[14] = {'G','e','e','k','s','f','o','r','G','e','e','k','s','\0'};

15.(b) Write a C program to find the biggest of three numbers using


function.

#include<stdio.h>

// function to find largest among three number


float large(float a, float b, float c)
{
if(a>=b && a>=c) return a;
else if(b>=a && b>=c) return b;
else return c;
}

int main()
{
float num1, num2, num3, largest;

printf("Enter three numbers: ");


scanf("%f %f %f", &num1, &num2, &num3);

largest = large(num1, num2, num3);


printf("Largest number = %.2f",largest);
return 0;
}

Output for the different test-cases:-

Enter three numbers: 12.5 8 6.9


Largest number = 12.50
Enter three numbers: 3 5.9 6.0
Largest number = 6.00

18.(a)Explain while and do-while statement in C.

In programming, loops are used to repeat a block of code until a specified


condition is met.

C programming has three types of loops.

1. for loop

2. while loop

3. do...while loop

while loop

The syntax of the while loop is:


while (testExpression) {
// the body of the loop
}

How while loop works?

 The while loop evaluates the testExpression inside the parentheses ().


 If testExpression is true, statements inside the body of while loop are
executed. Then, testExpression is evaluated again.
 The process goes on until testExpression is evaluated to false.
 If testExpression is false, the loop terminates (ends).
To learn more about test expressions (when testExpression is evaluated
to true and false), check out relational and logical operators.

Flowchart of while loop


Working of while loop

Example 1: while loop

// Print numbers from 1 to 5

#include <stdio.h>
int main() {
int i = 1;

while (i <= 5) {
printf("%d\n", i);
++i;
}

return 0;
}

Output
1
2
3
4
5

Here, we have initialized i to 1.


1. When i = 1, the test expression i <= 5 is true. Hence, the body of
the while loop is executed. This prints 1 on the screen and the value of i is
increased to 2.
2. Now, i = 2, the test expression i <= 5 is again true. The body of
the while loop is executed again. This prints 2 on the screen and the value of i is
increased to 3.
3. This process goes on until i becomes 6. Then, the test expression i <= 5 will
be false and the loop terminates.

do...while loop

The do..while loop is similar to the while loop with one important difference. The


body of do...while loop is executed at least once. Only then, the test expression is
evaluated.
The syntax of the do...while loop is:

do {
// the body of the loop
}
while (testExpression);
How do...while loop works?

 The body of do...while loop is executed once. Only then,


the testExpression is evaluated.
 If testExpression is true, the body of the loop is executed
again and testExpression is evaluated once more.
 This process goes on until testExpression becomes false.
 If testExpression is false, the loop ends.

Flowchart of do...while Loop

Working of do...while loop


Example 2: do...while loop

// Program to add numbers until the user enters zero

#include <stdio.h>
int main() {
double number, sum = 0;

// the body of the loop is executed at least once


do {
printf("Enter a number: ");
scanf("%lf", &number);
sum += number;
}
while(number != 0.0);

printf("Sum = %.2lf",sum);

return 0;
}

Output

Enter a number: 1.5


Enter a number: 2.4
Enter a number: -3.4
Enter a number: 4.2
Enter a number: 0
Sum = 4.70

Here, we have used a do...while loop to prompt the user to enter a number. The
loop works as long as the input number is not 0.
The do...while loop executes at least once i.e. the first iteration runs without
checking the condition. The condition is checked only after the first iteration has
been executed.

do {
printf("Enter a number: ");
scanf("%lf", &number);
sum += number;
}
while(number != 0.0);

So, if the first input is a non-zero number, that number is added to the sum variable
and the loop continues to the next iteration. This process is repeated until the user
enters 0.
But if the first input is 0, there will be no second iteration of the loop
and sum becomes 0.0.
Outside the loop, we print the value of sum.

20.(b) Write a program to sort an array of integers using function.

Using Function
1. The main() calls the sort() to sort the array elements in ascending
order by passing array a[], array size as arguments.
2) The sort() function compare the  a[j] and a[j+1] with the condition
a[j]>a[j+1],if a[j] is the highest value than a[j+1] then swap the both
elements.
3)To sort the array in ascending order
 a) Repeat the step b  from i=0 to i<n-1
b) for loop iterates from j=0 to j<n-i-1
find the highest element by comparing a[j] and a[j+1] and swap both
elements. Repeat until all iterations of j.
4) After all iterations of i, the sorted array will be generated in which the
elements are in ascending order.
5) To print the sorted array, the main() function calls the print() function
by passing the array, size of the array as arguments.

#include <conio.h>
int sort(int *a,int n)
{
    int i,j,temp;
     for(i=0; i<n-1; i++)
    {
          
        for(j=0; j<n-i-1; j++)
        {
           if(a[j]>a[j+1])
           {
           temp=a[j];
           a[j]=a[j+1];
           a[j+1]=temp;
  
}         }      }
              
}
print(int *a,int n)
{
  
    int i;
    for(i=0; i<n; i++)
    {
       printf("%d ",a[i]);
    }
    
      
}
 
  
int main()
{
    int a[10000],i,n,key;
  
    printf("Enter size of the  array : ");
    scanf("%d", &n);
    printf("Enter elements in array : ");
    for(i=0; i<n; i++)
    {
        scanf("%d",&a[i]);
    }
    
   sort(a,n);
      print(a,n);
 
    
    
}
Output:
Output
C
1 Enter size of the  array: 5
2 Enter elements in array : 5 4 3 2 1
31 2 3 4 5

8-5
8-4
4-1
19.(a)

i)strcat( ) Function :
  strcat( ) function in C language concatenates two given strings. It
concatenates source string at the end of destination string. Syntax
for strcat( ) function is given below.

Syntax :  char * strcat ( char * destination, const char * source );

Example :
strcat ( str2, str1 ); - str1 is concatenated at the end of str2.
strcat ( str1, str2 ); - str2 is concatenated at the end of str1.

• As you know, each string in C is ended up with null character (‘\0′). 
• In strcat( ) operation, null character of destination string is overwritten
by source string’s first character and null character is added at the end of
new destination string which is created after strcat( ) operation.

  Program : The following program is an example of strcat() function


#include <stdio.h>
#include <string.h>
int main( )
{
char source[ ] = “ ftl” ;
char target[ ]= “ welcome to” ;

printf (“\n Source string = %s”, source ) ;


printf ( “\n Target string = %s”, target ) ;

strcat ( target, source ) ;

printf ( “\n Target string after strcat( ) = %s”, target ) ;


}
Output :
Source string = ftl
Target string = welcome to
Target string after strcat() = welcome to ftl

ii) strrev() function :


strrev() function reverses a given string in C language.
Syntax : char *strrev(char *string);
strrev() function is non standard function which may not available in
standard library in C.
Example :
char name[20]=”ftl”; then
strrev(name)= ltf
  Program : In below program, string “Hello” is reversed using strrev( )
function and output is displayed as “olleH”.
#include<stdio.h>
#include<string.h>

int main()
{
char name[30] = “Hello”;

printf(“String before strrev( ) : %s\n”, name);

printf(“String after strrev( ) : %s”, strrev(name));

return 0;
}
Output :
String before strrev( ) : Hello
String after strrev( ) : olleH

iii) strcmp( ) Function :


strcmp( ) function in C compares two given strings and returns zero if
they are same. If length of string1 < string2, it returns < 0 value. If
length of string1 > string2, it returns > 0 value.
Syntax : int strcmp ( const char * str1, const char * str2 );
strcmp( ) function is case sensitive. i.e., “A” and “a” are treated as
different characters.

You might also like