SRL Archive - C/C++ Help and Tutorials

First C Lecture, Insanity remade


Recursive

2012-06-29 22:23:06

This is the first program we wrote today and I need help understanding some stuff cause I am used to c++

#include <cstdio>
#include <cstdlib>
#include <time.h>
using namespace std;

int main(void)
{
int deja;
int num1, num2;

printf("This program gets 2 numbers from the user and randomly adds or subtracts them \n");
printf("Enter 2 numbers and hit the ENTER key after each one \n");

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

printf("%s, %i, %i \n", "The 2 numbers are : ", num1, num2);
srand(time(NULL));
deja = rand()%2;

if (deja == 1)
{
printf("%s, %i \n","The sum is", num1 + num2);
}
else
{
printf("%s, %i \n", "The difference is" ,num1 - num2);
}

return EXIT_SUCCESS;
}

Everytime I run it, it does not print these first 2 lines
printf("This program  gets 2 numbers from the user and randomly adds or subtracts them \n");
printf("Enter 2 numbers and hit the ENTER key after each one \n");

Instead goes to the scanf and eventually waits for the user to enter both numbers before displaying the first 2 printf functions.

Also is there a different way to do the rand function that is easier to understand to someone who has never used it before?

When it runs, it shows this:
This program  gets 2 numbers from the user and randomly adds or subtracts them 
Enter 2 numbers and hit the ENTER key after each one
The 2 numbers are : , 6, 5
The difference is, 1

Is there a way to prevent it from showing the comma before the numbers?

Brandon

2012-06-29 22:42:09

One.. You're still writing C++ code.

Two.. You're includes are C++ includes. All C includes end in .h. Any include prepended with C is a C++ version of the C include.

Three.. To remove the comma, don't prepend the value with it:


#include <stdio.h> //C++ : CSTDIO
#include <stdlib.h> //C++: CSTDLIB
#include <time.h> //C++ : CTIME

//using namespace std;

int main(void)
{
int deja;
int num1, num2;

printf("This program gets 2 numbers from the user and randomly adds or subtracts them \n");
printf("Enter 2 numbers and hit the ENTER key after each one \n");

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

printf("%s %i, %i \n", "The 2 numbers are:", num1, num2);
srand(time(NULL));
deja = rand()%2;

if (deja == 1)
{
printf("%s %i \n","The sum is:", num1 + num2);
}
else
{
printf("%s %i \n", "The difference is:" ,num1 - num2);
}

return EXIT_SUCCESS;
}