|
|
Variables and TypesCan you show me an example of a simple program involving a calculation? I learn best using examples also. /*Project: First Program */ /*File: type.c */ /*Aim: Learn Basic Types*/ #include
What does the program does? This program takes two numbers called num1, num2 from the user and calculates their sum or adds them up and displays the result onto the screen. What does int mean? int is a key word in C. It stands for integer. From you math you should know that there are positive integers and negative integers, and zero is also considered an integer. The instruction int sum1, sum2; specifies the type, and name of the two variables that you will be need in the program. What do you mean by variable? The variables in the above program are sum1 and sum2. We are familiar with variables in mathematics. They stand for something. In programming, we can declare variables by type. Declaring variables in effect creates a space in memory to store a value. Also, declaring variables help clarify the data type used in the program. You can initialize the variable or assign its value later on the program. What other type of data are used in C?
Other types are Const, Void, Volatile. How are integer types different, and why do we use different types? Note that integer types differ in terms of the size and the range. Different types are used according to needs of the programs. One will not long double integer if it is sufficient to just integer, because that will save you more memory. How do you represent a word or string in C? And, how does a string differ from the above types? I don't know. Could you explain the other instructions also please? int sum; Another integer variable declaration. printf("Enter Two Numbers: \n"); A printf statement. scanf("%d %d \n", &num1, &num2); scanf is an input function, which takes in input data from the console. You have to follow the conventions required by the function in order to use the function. You have to specify the type of data that you are going to get it from the user. Here %d represents signed decimal integer. In other words, d specifies that the expected input is of type integer, in decimal notation, and signed means that negative integers are also to be expected. The & is a required convention, and what ever value entered is assigned to the declared variables of num1 and num2. sum=num1 + num2; The input numbers are added and the value is stored in the variable sum. printf("The sum is %d \n", sum); The result is output to the console or screen. |