If you run my code, what is your output?

This is mine:

My code:

// Created by Paul A. Gureghian in May 2020. //
//This C program takes two integers and calculates the sum. //

// Start of program. //

// Import libraries. //
#include <stdio.h>

// Define the main(). //
int main()
{
    int i, j, sum;
    scanf("Enter 1'st integer: %d", &i);
    scanf("Enter 2'nd integer: %d", &j);

    sum = i + j;

    printf("Sum is: %d\n", sum);
    return 0;
}

// End of program. //

@paulgureghian,
The reason your program isn’t running as you expect it to is because you are using scanf() where you should be using a combination of printf() and scanf(). On a very basic level, just making that change would allow your program to “work”:

// Start of program. //

// Import libraries. //
#include <stdio.h>

// Define the main(). //
int main()
{
    int i, j, sum;
    printf("Enter 1st integer: ");
    scanf("%d", &i);
    printf("Enter 2nd integer: ");
    scanf("%d", &j);


    sum = i + j;

    printf("Sum is: %d\n", sum);
    return 0;
}

// End of program. //

That being said, you probably don’t need to be using scanf() to get an integer input in C++. Is there any reason you would be opposed to using cout and cin? A nearly identical program can be written using cout and cin:

#include<iostream>

int main()
{
  int i, j, sum;
  std::cout << "Enter 1st integer: ";
  std::cin >> i;
  std::cout << "Enter 2nd integer: ";
  std::cin >> j;

  sum = i + j;

  std::cout << "Sum is: " << sum << "\n";
  return 0;
}

You will still need to guard against inputs that are not integers, but you will have fewer problems overall.

If you really want and/or need to use scanf(), I would highly recommend reading through this post first, as it breaks down several ways that scanf() may have unexpected results.

1 Like

It is a ‘C’ program, if that makes any difference. anyways, I used a combo of ‘printf’ and ‘scanf’ and it works. thanks.