Monday, November 19, 2012

Programming Session 4

salamo3alikom Everyone :) 

Last Session Practice 

we knew last session how to create a variable and this was our session practice.
write a program that add three numbers and print their sum and Multiplication.

The answer:
#include<stdio.h>
int main()
{

      int N1=3 , N2= 4 , N3 =6;
       printf("the result of %d + %d + %d is %d\n the result of %d * %d * %d    is %d\n",N1,N2,N3,N1+N2+N3,N1,N2,N3, N1*N2*N3);

return 0;
);

}

Session Agenda:
  1. Scanf statement 
  2. practice on scanf 
okay did you notice something about the program is it dynamic or fixed ?
the program won't change the printed result unless you change the data inside variables so it is a fixed program how can we make it dynamic.

i need to make the user enter the numbers and i should print the result.

Hmmm something missing right? 
yeah actually very important thing is missing which is a user request command 
as we said we need to ask the user to enter values for the numbers.

Scanf Statement
a function used when you need to take some data from the user such as numbers in our case.

how can i tell the computer here we are going to receive two numbers from user?
scanf("%d%d");  // two %d means you are going to receive two numbers.

and how to say store the first one in N1 and the second one in N2 ?

modify the previous statement to be scanf("%d%d",&N1,&N2);

what does & sign mean?
this means go to the address of the N1 and store this inside it as each variable has an address.

our program should look like this :
#include<stdio.h>
int main()
{
   int N1, N2;
   
   printf("Enter Two Numbers\n");
   scanf("%d%d",&N1,&N2);
   printf("the result of %d + %d is %d\n",N1, N2, N1+N2);
   
   return 0;

}

this would add any two numbers and print the result.

Practice 1:
write a program that take two numbers from user and print their sum and multiplication and subtraction each in a separated line.

No comments:

Post a Comment