IT Solution Menu

N O T I C E

Project on Computer topics, Programs for practicals for BCA Students, and Mobile Android app requirements. Please pay less and get more immediate delivery for school and higher level. Thank You. Contact me - at +91-8800304018(w)

Saturday, July 13, 2024

C's Control Flow by Md. Farrukh Asif

 



C Flow Control:

·         C’s Controls

·         if...else

·         for Loop

·         while Loop

·           break and continue

·           switch...case

·           Programming goto

·         Control Flow Examples

 

Don't know how to learn C Programming, the right way? Enroll in our Interactive C Course for FREE.(farrukhasif16@gmail.com) or Whatsapp : 8800304018

C Language:

C for the beginner 's by Md Farrukh Asif

Operators in C by Md. Farrukh Asif

C's Control Flow by Md. Farrukh Asif

String handling in C by Md Farrukh Asif

The Function of C Language by Md. Farrukh Asif

C for beginner's programming with output. Course Code – 106 [‘C’]) TMBU,BGP

BCA SOLVED EXAMINATION QUESTIONS WITH ANSWERS Course Code – 106 [‘C’]) TMBU,BGP  

C’s  if...else:

The syntax of the if statement is:

if (test expression)

{

   // code

}

 

How if statement works?

The if statement evaluates the test expression inside the parenthesis ().

·         If the test expression is true, statements inside the body of if are executed.

·         If the test expression is false, statements inside the body of if are not executed.

Working of if Statement:

Example 1: if statement

// Program to display a number if it is negative

// Otherwise it will not be displayed

/* Author: Md Farrukh Asif */

#include <stdio.h>

int main() {

    int num;

    printf("Enter any integer: ");

    scanf("%d", &num);

    // true if number is less than 0

    if (number < 0) {

        printf("You entered %d.\n", number);    }

    printf("https://teachallinone2020.blogspot.com");

    return 0;

}

***********

The if … else statement may have an optional else block.

The syntax of the if..else statement is:

if (test expression) {

    // run code if test expression goes true

}

else {

    // run code if test expression goes false

}

-------------------

How if...else statement works?

If the test expression is true,

·         statements inside the body of if are executed.

·         statements inside the body of else are skipped from execution.

If the test expression is false,

·         statements inside the body of else are executed

·         statements inside the body of if are skipped from execution.

Syntax of if...else (Ladder)

 

if (test expression1 true) {

   // statement(s)

}

else if(test expression2 true) {

   // statement(s)

}

else if (test expression3 true) {

   // statement(s)

}

.

.

// if test expression falls

else {

   // statement(s)

}

 

Example 4: Nested if...else

The following program relates two integers using either <, > and = similar to the if...else ladder's example. However, we will use a nested if...else statement to solve this problem.

 

#include <stdio.h>

/* AuthorL Md Farrukh Asif */

int main() {

    int num1, num2;

    printf("Enter two integers: ");

    scanf("%d %d", &num1, &num2);

 

    if (num1 >= num2) {

      if (num1 == num2) {

        printf("Result: %d = %d",num1,num2);

      }

      else {

        printf("Result: %d > %d", num1, num2);

      }

    }

    else {

        printf("Result: %d < %d",num1, num2);

    }

 

    return 0;

}

--------------------------

C’s  for Loop:

In any programming, a loop is used to repeat a block of code according to the expression/condition.

C programming has three types of loops:

·         for loop

·         while loop

·         do...while loop

for Loop:

The syntax of the for loop is:

for (initialization; testExpression; increment/decrement)

{

    // statements inside the body of loop

}

How for loop works?

The initialization statement is executed only once.

Then, the expression is evaluated. If the test expression is evaluated to false, the for loop is terminated.

However, if the test expression is evaluated to true, statements inside the body of the for loop are executed, and the increment/decrement  expression is updated.

Again the test expression is evaluated.

This process goes on until the test expression is false. When the test expression is false, the loop terminates.

Example 1: for loop

// Print numbers from 1 to 10

/* Author: Md Farrukh Asif */

#include <stdio.h>

int main() {

  int i;

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

  {

    printf("%d ", i);

  }

  return 0;

}

-------------------------

Run the above Code

-------------------------

Output:

-------------------------

1 2 3 4 5 6 7 8 9 10

-------------------------

while loop:

The syntax of the while loop is:

while (Expression) {

  // the body of the loop

}

How while loop works?

The while loop evaluates the Expression inside the parentheses ().

·         If Expression is true, statements inside the body of while loop are executed. Then, Expression is evaluated again.

·         The process goes on until testExpression is evaluated to false.

·         If testExpression is false, the loop terminates (ends).

Example 1: while loop

// Print numbers from 10 to 50

/* Author Md Farrukh Asif */

#include <stdio.h>

int main() {

  int i = 10;

     while (i <= 50) {

    printf("%d\n", i);

    i=i+10;

  }

  return 0;

}

Output

10

20

30

40

50

 

C’s 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  Expression is evaluated.

·         If  Expression is true, the body of the loop is executed again and  Expression is evaluated once more.

·         This process goes on until  Expression becomes false.

·         If  Expression is false, the loop ends.

Example 2: do...while loop

// Program to add numbers until the user enters zero

 #include <stdio.h>

int main() {

  double num, sum = 0;

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

  do {

    printf("Enter a number: ");

    scanf("%lf", &num);

    sum += num;

  }

  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

C break and continue:

C break

The break statement ends the loop immediately when it is encountered.

Its syntax is:

break;

The break statement is always used with if...else statement inside the loop.

Example 1: break statement

// Program to calculate the sum of numbers (10 numbers max)

// If the user enters a negative number, the loop terminates

/* Author: Farrukh */

#include <stdio.h>

int main() {

   int i;

   double num, sum = 0.0;

   for (i = 1; i <= 10; ++i) {

      printf("Enter n%d: ", i);

      scanf("%lf", &num);

      // if the user enters a negative number, break the loop

      if (num < 0.0) {

         break;

      }

      sum += num; // sum = sum + num;

   }

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

   return 0; }

---------------

Output

---------------

Enter  n1: 2.4

Enter n2: 4.5

Enter n3: 3.4

Enter n4: -3

Sum = 10.30

-----------------

C’s switch Statement:

The switch statement allows user to execute one code block from many alternatives.

You can do the same thing with the if...else..if  ladder. However, the syntax of the switch statement is much easier to read and write.

Syntax of switch...case

switch (expression)

​{

    case option1:

      // statements

      break;

     case option2:

      // statements

      break;

    .default:

      // default statements

}

How does the switch statement work?

 The expression is executed once and compared with the values of each case label.

If there is a match, the corresponding statements after the matching label are executed.

For example, if the value of the expression is equal to option2, statements after case option2: are executed until break is encountered.

If there is no match, the default statements are executed.

Notes:

·         If we do not use the break statement, all statements after the matching label are also executed.

·         The default clause inside the switch statement is optional.

 Example: Simple Calculator

// Program to create a simple calculator

/* Author: Farrukh Asif */

#include <stdio.h>

int main() {

    char op;

    double n1, n2;

    printf("Enter an operator (+, -, *, /): ");

    scanf("%c", &operation);

    printf("Enter two operands: ");

    scanf("%lf %lf",&n1, &n2);

    switch(op)

    {

        case '+':

            printf("%.1lf + %.1lf = %.1lf",n1, n2, n1+n2);

            break;

        case '-':

            printf("%.1lf - %.1lf = %.1lf",n1, n2, n1-n2);

            break;

        case '*':

            printf("%.1lf * %.1lf = %.1lf",n1, n2, n1*n2);

            break;

        case '/':

            printf("%.1lf / %.1lf = %.1lf",n1, n2, n1/n2);

            break;

        // operator doesn't match any case constant +, -, *, /

        default:

            printf("Error! operator is not correct");

    }

    return 0;

}

------------

Output:

------------

Enter an operator (+, -, *, /):   -

Enter two operands:    32.5

12.4

32.5 - 12.4 = 20.1

---------------------------

C’s goto Statement:

The goto statement allows us to transfer control of the program to the specified mentioned label.

Syntax of goto Statement

goto label;

label:

statement;

The label is an identifier. When the goto statement is encountered, the control of the program jumps to label: and starts executing the code.

How goto statement works?

 Example: goto Statement

// Program to calculate the sum and average of positive numbers

// If the user enters a negative number, the sum and average are displayed.

/* Author: Farrukh Asif  */

#include <stdio.h>

int main() {

   const int maxiInput = 100;

   int i;

   double num, avg, sum = 0.0;

   for (i = 1; i <= maxiInput; ++i) {

      printf("%d. Enter a number: ", i);

      scanf("%lf", &num);

            // go to jump if the user enters a negative number

      if (num < 0.0) {

         goto jump;

      }

      sum += num;         // sum=sum+num;

   }

jump:

   avg = sum / (i - 1);

   printf("Sum = %.2f\n", sum);

   printf("Average = %.2f", avg);

   return 0;

}

--------------

Output:

--------------

1. Enter a number: 3

2. Enter a number: 4.3

3. Enter a number: 9.3

4. Enter a number: -2.9

Sum = 16.60

Average = 5.53

--------------------------

1. C Program to Check Whether a Number is Even or Odd

·         C Programming Operators

·         C if...else Statement

Program to Check Even or Odd

#include <stdio.h>

int main() {

    int num;

    printf("Enter an integer: ");

    scanf("%d", &num);

    // true if num is perfectly divisible by 2

    if(num % 2 == 0)

        printf("%d is even.", num);

    else

        printf("%d is odd.", num);

        return 0;

}

-----------------

Output

-----------------

Enter an integer: -7

-7 is odd.

-------------------------

2. C Program to Check Whether a Character is a Vowel or Consonant

 C Programming Operators

C if...else Statement

C while and do...while Loop

The five letters A, E, I, O and U are called vowels.

All other alphabets except these 5 vowels are called consonants.

This program assumes that the user will always enter an alphabet character.

Program to Check Vowel or consonant

#include <stdio.h>

int main() {

    char c;

    int lowercase_vowel, uppercase_vowel;

    printf("Enter an alphabet: ");

    scanf("%c", &c);

    // checks to 1 if variable c is a lowercase vowel

    lowercase_vowel = (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u');

    // checks to 1 if variable c is a uppercase vowel

    uppercase_vowel = (c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U');

 

    // checks to 1 (on being true) if c is a vowel

    if (lowercase_vowel || uppercase_vowel)

        printf("%c is a vowel.", c);

    else

        printf("%c is a consonant.", c);

    return 0;

}

-------------

Output

-------------

Enter an alphabet: G

G is a consonant.

---------------------

3. C Program to Find the Roots of a Quadratic Equation

C Programming Operators

C if...else Statement

The standard form of a quadratic equation is:

ax2 + bx + c = 0, where

a, b and c are real numbers and

a != 0

The term  b2 - 4ac  is known as the discriminant of a quadratic equation. It tells the nature of the roots.

If the discriminant is greater than 0, the roots are real and different.

If the discriminant is equal to 0, the roots are real and equal.

If the discriminant is less than 0, the roots are complex and different.

3. Program to Find Roots of a Quadratic Equation

#include <math.h>

#include <stdio.h>

int main() {

    double a, b, c, discriminant, root1, root2, realPart, imagPart;

    printf("Enter coefficients a, b and c: ");

    scanf("%lf %lf %lf", &a, &b, &c);

    discriminant = b * b - 4 * a * c;

    // condition for real and different roots

    if (discriminant > 0)

{

        root1 = (-b + sqrt(discriminant)) / (2 * a);

        root2 = (-b - sqrt(discriminant)) / (2 * a);

        printf("root1 = %.2lf and root2 = %.2lf", root1, root2);

    }

    // condition for real and equal roots

    else if (discriminant == 0) {

        root1 = root2 = -b / (2 * a);

        printf("root1 = root2 = %.2lf;", root1);

    }

    // if roots are not real

    else {

        realPart = -b / (2 * a);

        imagPart = sqrt(-discriminant) / (2 * a);

        printf("root1 = %.2lf+%.2lfi and root2 = %.2f-%.2fi", realPart, imagPart, realPart, imagPart);

    }

    return 0;

}

----------------

Output

----------------

Enter coefficients a, b and c: 2.3

4

5.6

root1 = -0.87+1.30i and root2 = -0.87-1.30i

-----------------------------------------------------

4. C Program to Check Whether a Character is an Alphabet or not

·         C Programming Operators

·         C if...else Statement

In C programming, a character variable holds an ASCII value (an integer number between 0 and 127) rather than that character itself.

The ASCII value of the lowercase alphabet is from 97 to 122. And, the ASCII value of the uppercase alphabet is from 65 to 90.

If the ASCII value of the character entered by the user lies in the range of 97 to 122 or from 65 to 90, that number is an alphabet.

5. Program to Check Alphabet

#include <stdio.h>

int main() {

    char c;

    printf("Enter a character: ");

    scanf("%c", &c);

    if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))

        printf("%c is an alphabet.", c);

    else

        printf("%c is not an alphabet.", c);

    return 0;

}

-------------

Output

-------------

Enter a character: *

* is not an alphabet

--------------------------

6. C Program to Generate Multiplication Table

·         C Programming Operators

·         C for Loop

The program below takes an integer input from the user and generates the multiplication tables up to 10.

//Multiplication Table Up to 10

// Author = Farrukh Asif

#include <stdio.h>

int main() {

  int n;

  printf("Enter an integer: ");

  scanf("%d", &n);

  for (int i = 1; i <= 10; ++i) {

    printf("%d * %d = %d \n", n, i, n * i);

  }

  return 0;

}

-------------

Output

-------------

Enter an integer: 9

9 * 1 = 9

9 * 2 = 18

9 * 3 = 27

9 * 4 = 36

9 * 5 = 45

9 * 6 = 54

9 * 7 = 63

9 * 8 = 72

9 * 9 = 81

9 * 10 = 90

------------------

Here, the user input is stored in the int variable n. Then, we use a for loop to print the multiplication table up to 10.

7. C Program to Find GCD of two Numbers

To understand to find the GCD, you should have the knowledge of the following C programming topics:

·         C Programming Operators

·         C for Loop

·         C if...else Statement

·         C while and do...while Loop

The HCF or GCD of two integers is the largest integer that can exactly divide both numbers (without a remainder).

There are many ways to find the greatest common divisor in C programming.

Example #1: GCD Using for loop and if Statement

#include <stdio.h>

int main()

{

    int n1, n2, i, gcd;

 

    printf("Enter two integers: ");

    scanf("%d %d", &n1, &n2);

    for(i=1; i <= n1 && i <= n2; ++i)

    {

        // Checks if i is factor of both integers

        if(n1%i==0 && n2%i==0)

            gcd = i;

    }

    printf("G.C.D of %d and %d is %d", n1, n2, gcd);

    return 0;

}

------------------

Output

------------------

Enter two integers: 81

153

GCD = 9

-----------------

Example #2: GCD Using while loop and if...else  

#include <stdio.h>

int main()

{

    int n1, n2;

   

    printf("Enter two positive integers: ");

    scanf("%d %d",&n1,&n2);

    while(n1!=n2)

    {

        if(n1 > n2)

            n1 -= n2;

        else

            n2 -= n1;

    }

    printf("GCD = %d",n1);

    return 0;

}

------------------

Output

------------------

Enter two positive integers: 81

153

GCD = 9

-----------------

8. C Program to Find LCM of two Numbers

To better understand this example, you must have the knowledge of:

·         C Programming Operators

·         C if...else Statement

·         C while and do...while Loop

The LCM of two integers n1 and n2 is the smallest positive integer that is perfectly divisible by both n1 and n2 (without a remainder). For example, the LCM of 72 and 120 is 360.

LCM using while and if

#include <stdio.h>

int main() {

    int n1, n2, max;

    printf("Enter two positive integers: ");

    scanf("%d %d", &n1, &n2);

    // maximum number between n1 and n2 is stored in max

    max = (n1 > n2) ? n1 : n2;

    while (1) {

        if ((max % n1 == 0) && (max % n2 == 0)) {

            printf("The LCM of %d and %d is %d.", n1, n2, max);

            break;

        }

        ++max;

    }

    return 0;

}

----------------

Output

----------------

Enter two positive integers: 72

120

The LCM of 72 and 120 is 360.

--------------------------------------

9. C Program to Check Whether a Number is Palindrome or Not

An integer is considered a palindrome when its reverse is identical to the original number.

Program to Check Palindrome

#include <stdio.h>

int main() {

  int n, reversed = 0, remainder, original;

    printf("Enter an integer: ");

    scanf("%d", &n);

    original = n;

    // reversed integer is stored in reversed variable

    while (n != 0) {

        remainder = n % 10;

        reversed = reversed * 10 + remainder;

        n /= 10;

    }

    // palindrome if orignal and reversed are equal

    if (original == reversed)

        printf("%d is a palindrome.", original);

    else

        printf("%d is not a palindrome.", original);

    return 0;

}

-------------------

Output

-------------------

Enter an integer: 1001

1001 is a palindrome.

----------------------------

10. C Program to Convert Binary Number to Decimal and vice-versa

·         C Functions

·         C User-defined functions

Example 1: C Program to Convert Binary Number to Decimal

// convert binary to decimal

#include <stdio.h>

#include <math.h>

// function prototype

int convert(long long);

int main() {

  long long n;

  printf("Enter a binary number: ");

  scanf("%lld", &n);

  printf("%lld in binary = %d in decimal", n, convert(n));

  return 0;

}

// function definition

int convert(long long n) {

  int dec = 0, i = 0, rem;

  while (n != 0) {

    // get remainder of n divided by 10

    rem = n % 10;

    // divide n by 10

    n /= 10;

    // multiply rem by (2 ^ i)

    // add the product to dec

    dec += rem * pow(2, i);

    // increment i

    ++i;

  }

  return dec;

}

--------------------------------------

Output

--------------------------------------

Enter a binary number: 1101

1101 in binary = 13 in decimal

--------------------------------------

*** See You Again ***

************************

Share and Subscribe with Like

************************


No comments:

Post a Comment

Top Popular Post