Earn Online

Chapter - 1

 Why use C?
C (and its object oriented version, C++) is one of the most widely used third generation
programming languages. Its power and flexibility ensure it is still the leading choice for
almost all areas of application, especially in the software development environment.
=========================================
An Example C Program
/* This program prints a one-line message */
#include <stdio.h>
int main()
{
printf("Hello World\n");
return 0;
}
==========================================
/* This program ... */   The symbols /* and */ delimit a comment.Comments are ignored by the compiler 1, and are used to provide useful information for humans that will read the program.
main()-C programs consist of one or more functions. One and only one of these functions must be called main. The brackets following the word main indicate that it is a function and not a variable.
{ }braces surround the body of the function, which consists of one or more instructions (statements).
printf()-is a library function that is used to print on the standard output stream (usually the screen).
"Hello World\n" is a string constant.
\n -is the newline character.
; -a semicolon terminates a statement.
return 0;-return the value zero to the operating system. C is case sensitive, so the names of the functions
( main and printf ) must be typed in lower case as above.

====================================
#include<stdio.h>
int main (void)
{
int number1;
int number2;
int result;
number1=23;
number2=12;
result=number1+number2;
printf("%d\n",result);
return 0;
}
=====================================

_____________________
Data Types:
                            \There are three min data types

Data Type
Range of value

Int
-32768 to +32767
1,2,3,n
Char
-128 to 127
A,a—B,b—C,c....Z,z
Float
3.4 e-38 to 3.4e+38
1.100 , 1.298 , 3.598
______________________
Variable Declaration:
Int i;             int number;             int max;          
Here int is variable type and (i, number, max) are the variable names, you can write any variable name that can be easy to remember and write the whole program.
float i;          float number;          float max;       
char m;        char city;                 char name;     
if you want to declare more than one variables of same data type, you can write like this
int      a,number, flight;    
char   m,name,city;          
float   i,num,max;             
you can also initialize the value of these variables during the declaration of variable.
int     a=12,number=2,flight=865;    
Scanf Command: 
                              \Scanf commend is used for getting input by the user. We write the scanf commend in different ways according to the data type.
Int a;
Scanf("%d",&a);
                                Char ali;
                                Scanf("%c",&ali);
                                                              Float number;
                                                              Scanf("%f",&number)
Example:
====================================
#include<stdio.h>
int main (void)
{
int number1;
int number2;
int result;
Scanf ("%d"&number1);
Scanf ("%d"&number1);
result=number1+number2;
printf("%d\n",result);
return 0;
}
=====================================

Relational and Logical Operators:

The following relational operators produce a true or false value. True and false, when
generated by such an expression, are represented by the int values 1 and 0
respectively. Thus the expression
1 < 10
has the int value 1. Note, however, that C treats any non-zero value as being true!

Operators with higher precedence number get evaluated first (a complete list of C
operators and their relative precedence is given in section 19).
The following logical operators are used to combine logical values.
____________________________________________


> 
Grater than
< 
Less than
>=
Grater than or equal to
<=
Less than or equal to
==
Equal to
!=
Not equal to
||
Or operator
&&
And operator
!
Not operator


If Else statement:
This statement is completely based on conditions. There can me two or more conditions at the same time to proceed by this if else statement. 


if (expression)                          /* if expression is true */
statement1;                              /* do statement1 */
else                                           /* otherwise */
statement2;                              /* do statement2 *
if  there is only one statement after the if condition or else condition then there is no need to write the braces{} around the statement. but if there are more than one statement then you must have to write the braces {}.
else if {}  if there are more than two conditions then for the first one you will just write the if (condition). but for the second one else if (condition), and so on. but for the last one you will write just else condition.
Example:
====================================
#include<stdio.h>
int main (void)
{
int number1;
int number2;
int result;
Scanf ("%d"&number1);
Scanf ("%d"&number1);
if(number1>number2)
            {
               result=number1/number2;
               printf("%d\n",result);
            }
else 
            printf("It could not be divide\n");

return 0;
}
=====================================
Do while Loop:

Do while loop allow you to execute code in loop body at least one time. All the statements those are inside the braces{ }, will execute continually until the condition that you apply in the while statement will not false. You can use any condition inside the while.(a<b) or (a>b) 
or (a==b) or (a != b) or (a<=b) and (a>=b)
do {  
      statement;   /* this expression will be execute until while statement will not false*/ 
     }while (expression)
Examples:
=================================================
#include<stdio.h>
int main (void)
{
int x=5;
int i=0;                 /*its counter*/
int number;
do
{
Scanf ("%d"&number);
Printf ("%d"&number*2);
i=i+1;
}while(i<x)
return 0;
}
=================================================
//do while example
#include<stdio.h>
int main(void)
{

int SECRET_CODE = 15;
int code;

do{
printf("Type the secret code number to enter.\n");
scanf("%d", &code);
}while(code!=SECRET_CODE);
printf("Well done , you can now enter\n");
return 0;
}
=================================================

While Loop:-
A repetition statement allow you to specify that an action is to be repeated while some condition remains true. In this loop the two things are most important. One is condition that you will write inside the loop and second is counter.
= = = = = = = = = = = = = = = = = = = = = = = = = = = = 
#include <stdio.h>
void main()
{
int a, b, d ;
int c = 0 ;
while(c < 10)
{
scanf(“%d”,&a);             
scanf(“%d”,&b);             
d = a * b ;                        
printf(“%d”,d) ;               
c = c+1;                          
}
}
= = = = = = = = = = = = = = = = = = = = = = = = = = = = 
This Program will take the value of a and b at 10 times. from 0 to 9. and every time multiply a and b and then print the result. C is a counter variable while loop compare the value c with 10. and (c = c+1) will increment 1 in c. so when the value c will be 10 the while condition will false. And loop will stop.
================================================
#include <stdio.h>
int main()
{
int counter; /* counter variable that will count the loop*/
int grade;
int total;
int average;
total = 0;
counter = 1;
while ( counter <= 10 ) {            /* loop 10 times */
printf( "Enter grade: " );          /* prompt for input */
scanf( "%d", &grade );           /* read grade from user */
total = total + grade;                 /* add grade to total */
counter = counter + 1;              /* increment counter */
}                                                 /* end while */
average = total / 10;                 /* integer division */
printf( "Class average is %d\n", average );      /* display result */
return 0;
}
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
Increment and decrement operator:-
C also provides some increment and decrement operator.
Assignment Operator
Simple Expression
Expression we were using Before
Assume: int c = 3 , d = 5 , e = 4 , f = 6 , g = 12.
+=
C += 7
C = C+7
- =
D - = 4
D = D-4
*=
E *= 5
E = E * 5
/=
F /= 6
F = F/6
%=
G %= 9
G = G%9


Assignment Operator
Simple Expression
Expression we were using Before
++
++a
Increment a by 1 and then use the new value of (a) in loop or where it resides.
++
a++
Use the current value of (a) in expression or loop where it resides and then after increment by 1. and at next loop cycle it will use the new value of (a) and then once again increment by 1.
- -
- - b
decrement b by 1 and then use the new value of (b) in expression or loop where it resides.
- -
b- -
Use the current value of (b) in expression or loop where it resides and then after decrement by 1.and at next loop cycle it will use the new value of (b)and then once again decrement by 1.
For Repetition Statement: For loop:-
For repetition statement is also a loop statement as while loop. We can use any one of both. The main advantage of this statement is that all the elements of loop like initialization of counter variable, condition and increment in counter variable can handle in just one statements. And secondly its very useful for nested loop. Nested loop we will study later.
For ( a = 0; a<max ; a++ )
If we already have declared counter variable then we can initialized it in the for loop like a = 0;
this is a condition that should be true for the proceeding the statements the we will write inside the loop braces { } after the for statement. MAX can be any number.
A++ is increment in counter variable the will be increment with one after every cycle.
And when the counter variable a will equal to the max the condition will be false and loop will stop.
For (a=0;a<max;a++) {
     Expression
     Expression
     Expression   
}
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
#include <stdio.h>
int main()
{
int sum = 0;
int number;
for ( number = 2; number <= 100; number += 2 )
{
sum += number;
}
printf( "Sum is %d\n", sum );
return 0;
}
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
Write a c program that print the table of any integer:
#include<stdio.h>
void main( )
{
int a , b , c , d ;
scanf ( “%d” , &a ) ;
for ( b=1 ; b<=10 ; b ++ )
{
c = a * b ;
printf (“%d*%d = %d”, a , b , c) ;
}
}
= = = = = = = = = = = = = = = = = = = = = = = = = = = = 
Switch Statement:-
If else statement is good for choosing between two alternatives. But when several alternatives are needed then if else statement takes much time. The solution of this problem is switch statement.


Int a ;
Scanf (“%d”, &a) ;
Switch (a)
{
Case 1:
- - - - - - - - -
Break;
Case 2:
- - - - - - - - - 
Break;
Case 3:
- - - - - - - - - -
Break ;
Default :
- - - - - - - -- -
Break ;
}

Simply for the switch statement first we declare any variable (int a ;) and then after we take the value of this variable by user by using scanf( ) command. First we write the switch statement likes this switch(a) and the after braces {}. And inside the braces we write we can write cases, case: and after each case must write break; to stop the switch loop.
Switch statement will take the compiler on that case for perform the function who’s value will match with the value of a inside the switch(a).
Default: statement is performed when no match are found.

#include <stdio.h>

main()
{
     Char  Grade ;
     scanf ( "%c" , & grade ) ;

     switch( Grade )
     {
        case 'A' : printf( "Excellent\n" );
                   break;
        case 'B' : printf( "Good\n" );
                   break;
        case 'C' : printf( "OK\n" );
                   break;
        case 'D' : printf( "Mmmmm....\n" );
                   break;
        case 'F' : printf( "You must do better than this\n" );
                   break;
        default  : printf( "What is your grade anyway?\n" );
                   break;
     }
}
= = = = = = = = = = = = = = = = = = = = = = = = = = = = 
#include <stdio.h> 
main()
{

    
int i,n = 5;

   

   

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

        
switch(i%2)

        
{

            
  case 
  printf("the number %d is even \n",i);

                     
  break;

            
  case : printf("the number %d is odd \n",i);

                     
  break;

        
}
}
}
= = = = = = = = = = = = = = = = = = = = = = = = = = = =
Calculate the temperature: Convert centigrade to farenhight and farenhight to centgrade.
#include<stdio.h>
#include<conio.h>
main()
{
clrscr();
float a,b;
char f,c;
printf("Enter c for centigrade and f for farenhight");
scanf("%c",&c);
if(c=='c')
{
printf("enter the temp in centigrade")
scanf("%f",&a);
b=(((a-32)*5)/9);
clrscr();
printf("The required temp in farenhight is : %f",b);
}
else
{
scanf("%c",&f);
if(f=='f')
{
printf("enter the temp in farenhight")
scanf("%f",&a);
b=(32+(9*a)/5);
clrscr();
printf("The required temp in centigrade is : %f",b);
}
else
printf(" please enter as per instructed")
}


/* This program reads from keyboard a sequence
of integers terminted by a 0 and computes the
minimum, maximum, and arithmetic mean of the
sequence
*/
#include <stdio.h>
main() {
  int min, max, sum;   /* minimum, maximum and sum of integers */
  float mean; /* mean */
  int x; /* variable used to read integers */
  int i; /* array index */
  printf("Enter a sequence of integers terminated by a 0: ");
  /* read first integer x and initialize max and min to x and sum to 0 */
  scanf("%d", &x);
  sum = 0;
  max = x;
  min = x;
  /* repeat update max, min and sum and read new number until a 0 is read */
  for (i=1; x!=0 ; i++) {
if (x>max)
max=x;
if (x<min)
min=x;
sum = sum + x;
scanf("%d",&x);
  }
  i-- ; /* we don't count the final zero */


/* Compute mean and print results */
  if (i==0)
printf("Null sequence\n");
  else {
mean = (float)sum/i;
printf("maximum : %d\n",max);
printf("minimum : %d\n",min);
printf("mean : %f\n",mean);
  }
}
= = = = = = = = = = = = =  = = = = = = = = = = = = = = = = = = = =
/*
This program computes (and prints) the first N Fibonacci numbers;
The series is defined as:
 x(1)=1
 x(2)=1
 x(i)=x(i-1)+x(i-2), for each i>2
*/

#include <stdio.h>
main()
{

int x1,x2,y;   /* it is enough to remember the last two numbers */
int i,n;
x1=1;
x2=1;
printf("Enter how many numbers should be computed: ");
scanf("%d",&n);
       if (n<=0)
 printf("Error: the number must be positive\n");
else {
 printf("here is the series:\n");
           /* print the first two numbers */
 if (n>=1)
 printf("%d\n", x1);
 if (n>=2)
 printf("%d\n", x1);
     /* print the remaining numbers */
 for(i=3; i<=n; i++) {
 y=x1+x2;
 printf("%d\n",y);
 x1=x2;
 x2=y;
 }
}
}
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = 
/* This program computes (and prints) the factorial of a positive (integer) number;
The factorial is defined as:
 n! = n(n-1)(n-2)...(2)(1)    */

#include <stdio.h>
main()
{
        int i , n , fact ;
printf("Enter n: ");
scanf("%d",&n);
        if (n<=0)
 printf("Error: the number must be positive\n");
else {
 fact = 1;
 for (i=2; i<=n; i++)
fact = fact * i ;
 printf("The factorial is: %ld", fact);
}
}
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =

/* A possible solution for the 1st exercise of Lab 2
   This program reads from keyboard a sequence of real
   numbers terminated by a 0, counts how many of them
   are positive and how many of them are negative, and
   prints separately the arithmetic mean of positive
   numbers and the arithmetic mean of negative numbers.*/
#include <stdio.h>

main() {
  float n;
  float sumpos=0,sumneg=0; /* sum of positive and negative numbers */
  int numneg=0,numpos=0;   /* counters for positive and negative numbers */


/* Read numbers and compute sumpos, sumneg, numpos, numneg */
printf("Enter numbers and terminate with 0\n");
do {
scanf("%f",&n);

/* if the number entered is positive 
  add it to the sum of positive numbers and
  increment the count of positive numbers */

if(n>0) {
sumpos=sumpos+n;
numpos++;
}
/* if the number entered is negative 
  add it to the sum of negative numbers and
   increment the count of negative numbers */
else if(n<0) {  
sumneg=sumneg+n;
numneg++;
}
}
while(n!=0);
       /* Compute and print arithmetic means
  Note the two choices, used to avoid a division by 0..*/
if(numpos!=0)
printf("\nthe average of positive numbers is %f\n",sumpos/numpos);
else
printf("\nno positive number in the sequence\n");
       if(numneg!=0)
printf("\nthe average of negative numbers is %f\n",sumneg/numneg);
else
printf("\nno negative number in the sequence\n");
}
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =

/* A possible solution for the 2nd exercise of Lab 2
   This program simulates the behaviour of a changing money machine
   The machine is initially filled with 20 1 euro coins and 20 0.50 coins
   The machine continuously reads inputs from the keyboard according to the following menu:
M 1 means that a 1 euro coin is entered in the machine.
M 2 means that a 2 euro coin is entered in the machine.
S means that the machine is switched off (the program terminates).*/


#include <stdio.h>
main() {
  int coin1  = 20; /* number of 1 euro coins */
  int coin50 = 20; /* number of 50 cents coins */
  char selection; /* first selection character */
  int coin; /* value of coin 1=1europ, 2=2euros */
  char finished=0; /* boolean variable: true when machine switched off */
  printf("\nChange money simulation:\n\n");
  do {
/* print menu and prompt*/
printf("\nM 1 (Enter 1 Euro)\nM 2 (Enter 2 Euro)\nS (Switch off the machine)\n\n");
printf("> ");
/* read first selection character and perform corresponding action */
scanf("%c",&selection);
switch (selection) {
case 'M': coin=0;
 scanf("%d", &coin);
 switch(coin) {
case 1: if(coin50>=2) {
coin50=coin50-2;
printf("\nReturned two 50 cent coins. Change completed.\n");
coin1++;
} else
         printf("Returned one 1 euro coin. Coins for change unavailable\n");
break;
case 2: if(coin1>=2) {
coin1=coin1-2;
printf("\nReturned two 1 euro coins. Change completed.\n");
}
                              else if (coin50>=2 && coin1==1)
                                       {
               coin50=coin50-2;
        coin1=0;
printf("\nReturned one euro coin and two 50 cent coins. Change completed.\n");
}
                               else if(coin50>=4)
                                       {
coin50 = coin50-4;
printf("\nReturned four 50 cent coins. Change completed.\n");
}
                               else
printf("Returned one 2 euro coin. Coins for change unavailable\n");
break;
default:
                                        printf("Wrong value for input coin\n");
break;
 }
 break;
case 'S': finished=1;
 break;
default:  printf("Wrong command\n");
 break;
}
/* empty input line buffer */
while (selection != '\n')
scanf("%c", &selection);
/* print residual of coins */
printf("\n1 Euro coins: %d\n50 cent coins: %d\n",coin1,coin50);
  } while(!finished);
}

= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
/* A possible solution to the 3rd exercise of Lab 2
   This program reads from keyboard two positive integer numbers,
   and computes their greatest common divisor using the Euclidian
   algorithm*/

#include <stdio.h>
main() {
  int a,b,r;
  printf("\nEnter two positive integers:\n");
  scanf("%d %d",&a,&b);
  if (a<=0 || b<=0)
printf("The numbers are not positive\n");
  else {
while (b != 0) {
r = a % b;
a = b;
b = r;
}
printf("\nThe GCD is %d\n",a);
  }
}
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
/* A possible solution for the 4th exercise of Lab 2
   This program reads from keyboard a sequence of integer numbers
   terminated by a 0 and counts how many strictly increasing
   sub-sequences (of length 2 or more) are included in the sequence.*/
#include <stdio.h>
main() {
  int num,prev; /* the last and previous numbers read */
  int count=0; /* counts the number of strictly increasing sub-sequences */
  int len; /* sequence length */
  printf("Enter a sequence of integer numbers terminated by a 0:\n");
  scanf("%d", &num);
  if (num != 0) {
len=1;
prev=num;
do {
scanf("%d",&num);
if(num>prev)
len++; 
else {
if (len>=2)
count++;
len=1;
}
prev = num;
} while(num!=0);
  }
  printf("\n\nNumber of strictly increasing sequences (of length 2 or more): %d\n",count);
}
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
/* A possible solution to the 5th exercise of Lab 2
   reads from keyboard a sequence of 10 integers followed by another integer x
   and then computes and prints the list of integers in the sequence that are
   divisible by x*/
#include <stdio.h>

main() {
  int vect[10],i;
  int x;
  printf("Enter 10 integers:\n");
  for(i=0;i<10;i++)
scanf("%d",&vect[i]);

  printf("\n\nEnter now another integer number:\n");
  scanf("%d",&x);

  printf("\nThe integers divisible by x are:\n");

  for(i=0;i<10;i++)
if((vect[i]%x)==0) 
printf("%d\n",vect[i]);
}
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =