Thread: Trying to understand why this happens

  1. #1
    Registered User
    Join Date
    Sep 2018
    Posts
    9

    Trying to understand why this happens

    Code:
    #include <stdio.h>
    
    void calculateTriangularNumber (int n)
    {                                       
        int i, triangularNumber = 0;
    
        for (i = 1; i <= n; ++i)
            
            triangularNumber += i;
        
        printf ("Triangular number %i is %i\n", n, triangularNumber);
    }
    
    int main (void)
    {
        int n;
        
        printf ("What triangular number do you want to calculate?\n");
        scanf ("%i", &n);
        
        calculateTriangularNumber (n);
        
        return 0;
    }
    Hi, this is my first post here and im starting to learn C. So this code is for calculate the nth triangular number. Everything works fine but my question is why, when I must put what triangular number I want to calculate, but I write a char or string like the letter a or any word the program return "Triangular number 32764 is 536756230? I want to know why this happens. Cause I declare n to be an int. And how can this be fixed. Thank you

  2. #2
    Registered User
    Join Date
    Apr 2017
    Location
    Quetzaltenango
    Posts
    82
    Everything stored in the computer is just a bunch of bits turned on or off. Whether it is a letter or number is just a matter of interpretation. You have told scanf to see the bits as an int, and it has obeyed.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. ome one can help me to understand
    By alon4963 in forum C Programming
    Replies: 5
    Last Post: 10-29-2013, 03:59 PM
  2. Don't understand (int *a, a) etc etc
    By phil128 in forum C Programming
    Replies: 21
    Last Post: 07-02-2008, 04:10 AM
  3. NOT, AND, OR- I do not understand at all.
    By Phanntom in forum C++ Programming
    Replies: 7
    Last Post: 08-21-2006, 06:28 PM
  4. Help me understand why
    By byteme101 in forum C Programming
    Replies: 7
    Last Post: 12-08-2004, 09:39 AM
  5. I don't understand K&R example
    By rllovera in forum C Programming
    Replies: 8
    Last Post: 10-25-2004, 10:45 AM

Tags for this Thread