Saturday, September 28, 2013

Misc C programs

WRITE A PROGRAM WHICH PRINTS A TEXT OF 4 LINES CONSISTING OF CHARACTERS, INTEGER VALUES AND FLOATING POINT VALUES USING “printf” STATEMENT?

PROGRAM:

#include <stdio.h>#include <conio.h>void main(void){
clrscr();
float north = 23.30, north2 = 36.45;
int east1 = 61,float east2 = 75.30;
printf(“Pakistan is located between %f degrees and\n”, north1);
printf(“%f degrees north latitude and %d\n”, north2, east1);
printf(“Degrees and %f degrees east longitude in the\n”, east2);
printf(“northern hemisphere in south-east Asia.\n”);
getch();
}

WRITE A PROGRAM TO READ IN 3 INTEGERS AND PRINT THEIR SUM?
PROGRAM:
#include <stdio.h>
#include <conio.h>
void main(void)
{
clrscr();
int value1, value2, value3, sum;
printf(“Enter first value:”);
scanf(“%d”,&value1);
printf(“\n Enter second value:”);
scanf(“%d”,&value2);
printf(“\n Enter third value:”);
scanf(“%d”,&value3);
sum = value1 + value2 + value3;
printf(“\nSum of 3 integers = %d, sum);
getch();
}

WRITE A PROGRAM THAT READS AND PRINTS USING ESCAPE SEQUENCE, ASKING THE NAME, AGE, HEIGHT AND GENDER OF STUDENTS USING “scanf” AND “printf” STATEMENTS?
PROGRAM:
#include <stdio.h>
#include <conio.h>
void main(void)
{
clrscr();
char name[20], gender[6];
int age;float height;printf(“Enter your name:”);
scanf(“%s”,& name);
printf(“\n Enter your age:”);
scanf(“%d”,& age);
printf(“\n Enter your height:”);
scanf(“%f”,& height);
printf(“\n Enter your gender:”);
scanf(“%s”,& gender);
printf(“\n\n Your name is %s.“, name);
printf(“\n You are %d years old.“, age);
printf(“\n Your height is %f feet.“, height);
printf(“\n You are %s.“, gender);
getch();
}

WRITE A PROGRAM WHICH USES OPERATORS (CALCULATE THE AREA OF TRIANGLES, VOLUME OF SPHERE AND ARRANGE THE RESULTANT VALUES IN ASCENDING ORDER)?
PROGRAM:
#include <stdio.h>
#include <conio.h>
#include <math.h>
void main(void)
{
clrscr();
float a, b, c, s, area, d, vol;
printf(“Enter triangle side A:”);
scanf(“%f”,& a);
printf(“\n Enter triangle side B:”);
scanf(“%f”,& b);
printf(“\n Enter triangle side C:”);
scanf(“%f”,& c);
printf(\n Enter diameter of sphere:”);
scanf(“%f”,& d);
s = (a + b + c) /2;
area = sqrt (s * (s - a) * (s - b) * (s - c));
vol = (3.14 / 6) * (d * d * d);
if(vol> area)
{
 printf(“\n\n Area of triangle = %f”, area);
printf(“\n Volume of sphere = %f”, vol);
}
else
{
 printf(“\n Volume of sphere = %f”, vol);
printf(“\n Area of tringle = %f”, area);
}
getch();
}

WRITE A PROGRAM TO READ IN 5 NUMBERS AND COMPUTE THE AVERAGE, MAXIMUM AND MINIMUM VALUES?
PROGRAM:
#include <stdio.h>
#include <conio.h>
void main(void)
{
clrscr();
float in, sum = 0.0, max = 1000000.0, min = -1000000.0;
int i;
for(i = 1; i<=5; i++)
printf(“\n Enter number %d:”, i + 1);
scanf(“%f”,& in);
if(min < in)
min = in;
if(max > in)
{ 
max = in;
sum = sum + in;
}
printf(“\n Largest = %f, Smallest = %f”, min, max);
printf(“\n Average %f \n”, sum / 5);
getch();
}

WRITE A PROGRAM WHICH USES “for” LOOP STATEMENT (GENERATE THE MULTIPLICATION TABLE FROM 2 TO 20)?
PROGRAM:
#include <stdio.h>
#include <conio.h>
void main(void)
{
clrscr();
int x, y, num;
for(x = 2; x<21; x++)
{
 for(y = 1; y<=10; y++)
{
 num = x * y;
printf(%d * %d = %d \n”, x, y, num);
}
}
getch();
}

WRITE A PROGRAM WHICH USES “while” LOOP AND NESTED “while” LOOP(USE “for” LOOP AND CONTINUE THE PROCESS IN “while” LOOP SATISFYING THIS CONDITION)?PROGRAM:
#include <stdio.h>
#include <conio.h>
void main(void)
{
clrscr();
int x, loop, count;
for(x = 1; x <3; x++)
{
 loop = 1;
while(loop <= 5)
{
 count = 1;
while(count <= loop)
{
 printf(“%d”, count);count++;
}
printf(“\n”);
loop++;
}
}
getch();
}

FINDING THE FACTORIAL OF ‘N’ USING “while” LOOP, READ VALUE OF ‘N’ USING “scanf” AND “printf” FACTORIALS OF VARIOUS ‘N’?
PROGRAM:
#include <stdio.h>
#include <conio.h>
void main(void)
{
clrscr();
int n, result = 1, counter = 2;
printf(“Enter the value of N:”);
scanf(“%d”,& n);
while(counter <= n)
{
 result = counter * result;
counter += 1;
}
printf(“\n\n Factorial of N is %d”, result);
getch();
}

WRITE A PROGRAM WHICH USES A “switch” STATEMENT AND BREAKS THE PROGRAM IF CERTAIN CONDITION IS OBSERVED. REPEAT THE PROGRAM WITH CASE STAEMENT? 
PROGRAM:
#include <stdio.h>
#include <conio.h>
void main(void)
{
clrscr();
int month;
do
{
 printf(“Type the number of a month:”);
scanf(“%d”,& month);
printf(“\n\n Name of month %d is “, month);
switch (month)
{
case 1 : printf(“January”);
 break;
case2 : printf(“February”);
 break;
case3 :
 printf(“March”);
 break;
case4 : 
printf(“April”);
 break;
case5 : 
printf(“May”); 
break;
case6 :
printf(“June”);
 break;
case7 :
 printf(“July”);
 break;
case8 :
 printf(“August”); 
break;
case9 :
 printf(“September”); 
break;
case10 :
 printf(“October”);
 break;
case11 : 
printf(“November”);
 break;
case12 :
 printf(“December”);
 break;
}
}
while (month < 1 || month > 12);
getch();
}

WRITE A FUNCTION, WHICH GENERATES FACTORIAL OF ‘N’ AND CALLS THIS FUNCTION IN THE “main” PROGRAM?
PROGRAM:
#include <stdio.h>
#include <conio.h>
int factorial(int x);
void main(void)
{
clrscr();
int n, f;
printf(“Enter the value of N :”);
scanf(“%d”,& n);
f = factorial(n);
printf(“\n\n Factorial of N is %d”, f);
}
int factorial(int x)
{
int i, fact = 1;
for(i = 2; i<=x; i++)
fact = fact * i;
return fact;
}

WRITE A PROGRAM WHICH USES MULTIPLE ARGUMENTS IN A FUNCTION (DEVELOP A USER-DEFINED FUNCTION TO GENERATE A RECTANGLE). USE THE FUNCTION FOR PASSING ARGUMENTS TO DRAW DIFFERENT SIZES OF RECTANGLES AND SQUARES?
PROGRAM:
#include <stdio.h>
#include <conio.h>
void box(int length, int width);
void main(void)
{
clrscr();
box(5,5);
box(5,10);
box(7,7);
box(3,8);
}
void box(int length, int width)
{
int a, b, x;
for(a = 1; a <= width; a++)
print(“*”);
for(b = 1; b <= length; b++)
{
x = 0;
printf(“\n*”);
}
while(x <= (width – 3))
{
x = x + 1;
printf(“  ”);
 }
printf(“\n”);
for(a = 1; a <= width; a==)
printf(“*”);
printf(“\n”);
}
getch();
}

Thursday, September 26, 2013

SELECTION STRUCTURE (CHOICES AND DECISIONS)


SELECTION STRUCTURE (CHOICES AND DECISIONS)

Comparison of selection and sequential structure in C programming:
Selection Structure allows a choice among various alternatives. Selection structure is different than that of sequential structure. A program that executes the statements one by one until the defined end, this type of program is called sequential structure. The functionality of this type of program is limited since it flows in single direction. Now we will be looking at one of the most powerful programming feature - the ability to change the flow of program execution. It is achieve by establishing the truth or falsity of an expression (condition). This type of program is called selection structure.
Explanation of Selection Structure: We all make different decisions in the face of changing circumstances. For example, if my friend is at home, then I will visit him. If the weather is good tomorrow, I will go for picnic. Computer Languages are also able to perform different tasks depending on the circumstances.
Selection structure is extensively used in programming because it allows the program to decide an action based upon user's input or other processes. The application of selection structure can be seen at systems that have password checking such as ATM Machine, handphone and etc. The system allows user access only if the user input password is the same as the corresponding password stored in the system. 

C uses the following statements to implement choices and decisions in programs.
  1.      The if statement
  2.      The if-else statement
  3.      The else-if statement
  4.      The switch statement
  5.      The conditional operator
Meaning of True and False in Programming:
Before we go further into the selection structure, you need to know the meaning of True and False in programming. An expression that evaluates to non-zero (1) is considered true expression while false expression evaluates to zero (0).


THE if STATEMENT IN C PROGRAMMING LANGUAGE



Here, if is the keyword in C. 


SYNTAX:

if (condition)
{
  block of statements to be executed
}

When this statement is executed, the condition is evaluated first. If the condition is true then the block of statements within the braces will be executed.
Note: The block of statements to be executed must be enclosed in opening and closing braces. If only one statement needs to be executed then braces need not be used. Let us understand if statement using an example.
FLOW CHART:


Example # 1:
Let’s look at an example that implement if selection structure. The program asks the user to input a number. Then it message if the number is a positive number.
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int num;
printf(“Enter a number:”);
scanf(“%d”,&num);
if(num>0)
printf(“\n %d is a positive number”, num);
getch();
}
Sample output:

           Enter a number: 6
           6 is a positive number


Explanation:

int num;
printf(“Enter a number:”);
scanf(“%d”,&num);

We declare a variable called num and then we prompt the user to enter a number.The scanf statement reads the user input and store it in variable num.

            if(num>0)
printf(“\n %d is a positive number”, num);

The if statement compare the value in num with the value of 0. If num is greater than 0, the printf() will be executed which displays a message and continue with the next part of the program. If it is not greater than 0, the printf() will be skipped. 


Example #2 :
/*Demonstration of if statement*/

int marks;
printf(“Enter the marks:”);
scanf(“%d”, &marks);
if(marks>=35){
printf(“Congrats!!!”);

getch( );
}
In the above program, it will prompt you to enter the marks. If you enter marks greater than or equal to 35, it will display Congrats!!! on the screen else it will do nothing.
***************************************************************************************************************************************************************************************************************************************************

THE if -else STATEMENT IN C PROGRAMMING LANGUAGE

Here, if and else are the keywords in C. 

SYNTAX:

if (condition)
{
  block of statements to be executed
}
else
{
block of statements to be executed
}


When this statement is executed, the condition is evaluated first. The if-else statement allows one action to be executed if the condition is true and another action to be executed if the condition is false. If the condition is true then the if block of statements will be executed, if the condition is false the body of else will be executed.

Note: The block of statements to be executed must be enclosed in opening and closing braces. If only one statement needs to be executed then braces need not be used. Let us understand if statement using an example.
FLOW CHART:


Example #1:
Let’s look at an example that implements if-else selection structure.  The following will find out large number from given input:
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
        int x,y;
        printf("Enter value for x :");
        scanf("%d",&x);
        printf("Enter value for y :");
        scanf("%d",&y);
        if ( x > y ){
                printf("X is large number - %d\n",x);
        }
        else{
                printf("Y is large number - %d\n",y);
        }
getch( );
}

Example # 2:
The following program prompts the user to enter a character, if its is vowel a msg "Character is vowel" will be displayed, otherwise the message "character is consonant" will be displayed on the screen.

#include<stdio.h>
#include<conio.h>
void main()
{

clrscr( );
char ch;
printf("enter the character");
scanf("%c",&ch);
if (ch=='a'||ch=='e'||ch=='i'||ch=='o'||ch=='u')
printf("character is vowel");
else
printf("character is consonant");
getch();
}


Example # 3:
The following programs checks that either the input number is even or odd by using if-else statment.

#include<stdio.h>

#include<conio.h>
void main()
{
int n;
clrscr();
printf(“enter the number:”);
scanf(“%d”,&n);
if (n%2==0)
printf(“the number is even”);
else
printf(“the number is odd”);
getch;
}


Example # 4:
The following program read the student name, section and grade. If the grade is greater than 75,  the student ispassed otherwise the student is failed.

#include<stdio.h>
#include<conio.h>
void main()
{
int grade;
char student[25],section[25];
clrscr();
printf(“Enter the name of a student: “);
scanf(“%s”, &student);
printf(“Enter the section of a student: “);
scanf(“%s”, &section);
printf(“Enter the grade of a student: “);
scanf(“%d”, &grade);
if(grade>75)
printf(“PASSED”);
else
print(“FAILED”);

getch();
}

Example # 5:
The following program prompts the user to enter age, if the age is less than 80, it will displayed the message "can't vote" otherwise the message " Can vote" would be displayed.

#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int age;
printf(“Enter the age:”);
scanf(“%d”, &a);
if(a<18)
printf("can't vote");
else
printf("can vote");
getch();
}

Example #6:
The following program 
#include<stdio.h>
#include<conio.h>
void main()
{
int grade;
clrscr();
printf(“Enter Grade:\n”);
scanf(“%d”, &grade);
if((grade>=80)&&(grade=75)&&(grade<=79))
printf("Nice");
else
printf("Poor");
getch( );
}

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

THE else-if STATEMENT IN C PROGRAMMING LANGUAGE

 If we have long decision tree, then the else-if statement is used.
SYNTAX:
The syntax of else-if statement in C programming language is:
if(boolean_expression 1)
{
   /* Executes when the boolean expression 1 is true */
}
else if( boolean_expression 2)
{
   /* Executes when the boolean expression 2 is true */
}
else if( boolean_expression 3)
{
   /* Executes when the boolean expression 3 is true */
}
else
{
   /* executes when the none of the above condition is true */
}

FLOWCHART:

EXAMPLE:
 Cprogram by using if else statement to print smallest of given four numbers.
#include<stdio.h>
#include<conio.h>
void main()
{

clrscr( );
int a=10,b=20,c=30,d=40;
if (a<b && a<c && a< d)
printf("A is smallest");
else if (b<a &&b<c &&b<d)
printf(" b is smallest );
else if (c <a && c<b && c <d)
printf("c is smallest");
else
printf("D is smallest");
getch()
}

EXAMPLE: 
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr( );
int x;
printf(“enter any number between 1 to 12″);
scanf(“%d”,&x);
if(x==1)
{
printf(“month is jan. %d\n”,x);
}
else if(x==2)
{
printf(“month is feb%d\n”,x);
}
else if(x==3)
{
printf(“month is march .%d\n”,x);
}
else if(x==4)
{
printf(“month is april %d /n”,x);
}
else if……………….
…………………………………….
………………..
………………………
…………………………….
else(x==12)
{
printf(“month is december %d\n”);
}
getch();
}
************************************************************************************************************************************************************************************************************************************************

WHAT IS A LOOP IN C PROGRAMMING?

WHAT IS A LOOP IN C PROGRAMMING?

In every programming language, thus also in the C programming language, there are circumstances were you want to do the same thing many times. For instance you want to print the same words ten times. You could type ten printf function, but it is easier to use a loop. The only thing you have to do is to setup loops that execute the same printf function ten times.
There are three basic types of loops which are:
§  “for loop”
§  “while loop”
§  “do while loop”

A loop allows us to execute a statement or group of statements multiple times. C programming language provides the following types of loop to handle looping requirements.

Loop Type
Description
Execute a sequence of statements multiple times and abbreviates the code that manages the loop variable.
Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body.
Like a while statement, except that it tests the condition at the end of the loop body
You can use one or more loop inside any another while, for or do..while loop.

for loop

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 ( initialization ; condition; increment )
{
   statement(s);
}
Here is the flow of control in a for loop:
1.      The initialization 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.
2.      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 flow of control jumps to the next statement just after the for loop.
3.      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.
4.      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 CHART:



Example:

#include <stdio.h>
#include<conio.h>
void main ()
{
 for( int a = 10; a < 20; a = a + 1 )
   {
      printf("value of a: %d\n", a);
   }
 getch();
}
When the above code is compiled and executed, it produces the following result:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19

"While Loop"

A while loop statement in C programming language repeatedly executes a target statement as long as a given condition is true.

Syntax:
The syntax of a while loop in C programming language is:
while(condition)
{
   statement(s);
}
Here, statement(s) may be a single statement or a block of statements. The condition may be any expression, and true is any nonzero value. The loop iterates while the condition is true.
When the condition becomes false, program control passes to the line immediately following the loop.
Flow Diagram:









#include <stdio.h>

#include<conio.h>

 void main ()

{

   int a = 10;

 

    while( a < 20 )

   {

      printf("value of a: %d\n", a);

      a++;

   }

getch();

}

 

When the above code is compiled and executed, it produces the following result:

value of a: 10

value of a: 11

value of a: 12

value of a: 13

value of a: 14

value of a: 15

value of a: 16

value of a: 17

value of a: 18

value of a: 19

 

do-while Loop


Unlike for and while loops, which test the loop condition at the top of the loop, the do...while loop in C programming language checks its condition at the bottom of the loop.
A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at least one time.

Syntax:
The syntax of a do...while loop in C programming language is:
do
{
   statement(s);
 
}
while( condition );
Notice that the conditional expression appears at the end of the loop, so the statement(s) in the loop execute once before the condition is tested.
If the condition is true, the flow of control jumps back up to do, and the statement(s) in the loop execute again. This process repeats until the given condition becomes false.
Flow Diagram:



Example:

#include <stdio.h>

#include<conio.h>

 void main ()

{

  int a = 10;

   do

   {

       printf("value of a: %d\n", a);

       a = a + 1;

   }

while( a < 20 );

    getch();

}

 

When the above code is compiled and executed, it produces the following result:

value of a: 10

value of a: 11

value of a: 12

value of a: 13

value of a: 14

value of a: 15

value of a: 16

value of a: 17

value of a: 18

value of a: 19