Anasayfa » C / C++

C / C++ Courses ? 3 (Variables)

23 Temmuz 2010 2.065 views 1 Yorum

Let’s talk about variables and usage of conversion specifiers now.

What is a variable?

  • It’s a location in memory
  • It’s used to store input and results. (Results can be output as well)
  • It has a name and a data type

Variable Names:

Rules for variable names:

~It can consist of characters, letters, digits

~It can not start with a digit

int 2a;–> invalid

float 123; –>invalid

~It can not contain spaces

char my name; –> invalid

~It can not be a C reserved word

int return;–> invalid

char float;–> invalid

~We can not use arithmetic operations as variables

int x+y; –> invalid

Some Variable Data Types:

int -> for integers (4 bytes=32bits)

float -> for floating point numbers (4 bytes=32bits)

double -> for floating point numbers (8 bytes=64bits)

char -> for characters (1 byte=8bits)


  • We specify the location in memory by declaring

Three things that we can do with variables are declaration, initialization and using it.If you use a variable without declaring it, it will give you an error “undeclared identifiers”.

int num; // this is a declaration statement

num=5;  // this statement is called initializing variable


*Don’t forget! C is case sensitive. So they are different from each other:

int A1,a1;

int val, Val, VAL, VaL;


Initializing a variable can be done in three ways:

  1. Using an assignment statement
  2. stnum=07010800;

  3. Using scanf function 

  4. we didn’t learn this. In previous lectures, you will understand this very easily.

  5. Using an arithmetic operator
  6. int y=x+5;


Conversion Specifiers:

When you put a percentage “%” , it means sth different is going to happen depends on what there is.They are used to be able to print sth in variable in printf or scanf functions.

data type conversion spesifiers

int                                  %d

float                                 %f

double                             %lf

char                                  %c

for example:

int num=07010800;

printf( ” My uni number is %d” , num );

Output will be like that:

My uni number is 07010800


Let’s write a simple program which covers our knowledge about variables and finish this part:

? Question:Write a program that declares 2 integer variables and initializes them to 65 and 34 respectively.Find and print sum and product of these integers on the screen.

int main(){
int num1, num2;
int sum, product;
num1= 65;
num2= 34;
sum= num1 + num2 ;
product= num1 * num2;
printf( " The sum is %d , the product is %d ." ,  sum , product );
return 0;

Output on the screen is:

The sum is 99 , the product is 2210.




»Extra: What happens if we write a printf statement without any variable to specify %d ??

like this:  printf( "The number is %d" );

Answer is in  the following lesson😉



Have a nice day 🙂

1 Yorum »

Etiketler: , , , , , , , , , ,