Friday, July 21, 2017

Input Output in C

Input and Output in C

Declaration and Initialization of Variables:

Any variable in C programming language must be declared before using it. Variables are declared using the following rules-

Integer type variables are declared using the “int” keyword before the variable name. More than one variable can be declared in a single statement. Syntax for declaring integer type variables is given below-

int <list_of_variable_names>;

For example:

int n;
int basic, hra;

Real or floating type variables are declared using the keyword “float” before the variable name. Syntax for declaring floating type variables is given below-

float <list_of_variable_names>;

For example:

float a;
float rate, gross_salary, weight;

Character type variables are declared using the keyword “char” before the variable name. Syntax for declaring character type variables is given below-

char <list_of_variable_names>;

For example:

char c;
char x, y, symbol;

Variables can be initialized or given values at the time of declaration.

For example:

int n=12, a=5;
float x=1.5, y=3.7;
char a=’t’, b=’#’;

In C programming language variables should be declared in the beginning of any function.

For example:

int main()
{
      int n1, n2=25;
      float length=45.8;
      statement;
      …;
      …;
}

Input and Output:

There should be a way for interacting with the outside world. There are so many readymade library functions for input and output in C. Two of them are explained here. Others will be explained, whenever and wherever they are used.

For outputting messages, values of variables, results of expressions, etc. function printf() is used. The format of this function is given below-

printf(“<format_string”, <list_of_variables>);

In the format string, “%d” is used for printing integer values, “%f” for floating point values, and “%c” for character values. These are called format specifiers. You can give any other characters too in the format string. These characters will be printed as they are. The number and order of format specifiers should be same as that of the variables to be printed. To use the function printf(), include the instruction #include<stdio.h> at the beginning of the program. This instruction is preprocessor directive and will be explained later. A few examples of this function are given below-

printf(“Number of students : %d”, num);
printf(“%d %f”, num, weight);
printf(“%c”, a);
printf(“Basic salary is %d\nGross salary is %f”, basic, gross);

Please note that in the last statement, “\n” has been used in the format string. This is the newline character, and it takes the cursor to the new line, wherever it is used. That’s why; output of this statement will be shown in two lines like this-

Basic salary is 5000
Gross salary is 8500.50

If you want a program to receive input from keyboard during execution, here is a library function, function scanf(). It is the counterpart of function printf(). The format of this function is given below-

scanf(“<format_string>”, &variable1, &variable2,…);

The explanation of format string is same as in the function printf(). You should give the format specifiers in the same number and order you want to receive the values of variables from the keyboard. The ampersand (&) before the variable name is the “address of” operator. It gives the location number or address of variable in the memory. When we say &variable_name, it tells to the function scanf() at which memory location, value, supplied by the user through the keyboard, should be stored.

For example:

scanf(“%d %d %d”, &n1, &n2, &n3);
scanf(“%f”, &weight);
scanf(“%c”, &ch);

If you want to receive more than one value at a time from the keyboard using only one scanf() statement, supply these values using either <space>, or <tab>, or <enter> keys during program execution.

Now, whatever you have learnt till now, apply in a C program. Please type this program in your editor.

/* Program to add three numbers */
#include<stdio.h>
#include<conio.h>
int main()
{
       int n1, n2, n3, sum;
       clrscr(); /* clears the screen */
       printf("Enter 3 numbers: ");
       scanf("%d %d %d", &n1, &n2, &n3);
       sum=n1+n2+n3;
       printf("Sum of 3 numbers is %d", sum);
       getch();  /* gets a character from
                          keyboard, but does not
                          echo it */
       return 0;
}

Compile and execute this program. Output of this program would be like this-

Enter 3 numbers: 12
25
33
Sum of 3 numbers is 70

In this program, whatever written between /* */ is comment entry, and will not be executed.

/* Program to add three numbers */

Next two lines are preprocessor directives, which you will learn in later posts. These lines simply asks to compiler to add two files (stdio.h and conio.h) in the program. File “stdio.h” is needed for printf() and scanf() functions, and file “conio.h”, for clrscr() and getch() functions.

#include<stdio.h>
#include<conio.h>

In this program, there is only one function, called main(). A C program can contain more than one function. Function main() is necessary for execution and execution starts from function main(). Return type of this function is “int”, which means, it returns an integer value to the operating system. You will learn more about return type of a function in the later posts.

int main()
{
       …;
       …;
       …;
return 0;
}

The first thing we do in a function is to declare all the necessary variables. In this program, we have declared four integer type variables.

int n1, n2, n3, sum;

Next statement clears the screen and positions the cursor at the top-left corner of the screen. We do this, because it may be that the screen is showing something from the previous program. Function clrscr() is a library function.

clrscr();

Next statement prompts the user to enter three numbers.

printf("Enter 3 numbers: ");

Now, function scanf() waits for the numbers to be entered. You can enter three numbers separating them either by pressing <space>, or <tab>, or <enter> key.

scanf("%d %d %d", &n1, &n2, &n3);

The next statement adds the numbers and assigns the result in the variable “sum”.

sum=n1+n2+n3;

+” is the arithmetic operator for addition. “=” is the assignment operator. It is different from “equal to” operator in mathematics. It assigns the value of right-hand-side expression to the left-hand-side variable. There are 45 operators in the C computer language. You will learn more about operators in the later posts.

Next statement prints the result on the screen.

printf("Sum of 3 numbers is %d", sum);

Now, the function getch() waits a key-press. If we don’t use this function, output screen would not show up. That’s why, to hold the screen we have used this function.

getch();

Last statement returns the value ‘0’ to the operating system. ‘0’ indicates success.

return 0;

Now, this simple program is well explained. I hope you have a good foundation at your disposal. I recommend you to read all my posts from the very beginning.


If you are interested in how to create simple graphics in C, please read my blog Graphics in C.

Tuesday, July 11, 2017

C Keywords, Variables, Constants

Getting Ready to Learn C

Like any natural language, C computer language too has its own character set, grammar, and rules. Before start writing programs, you should first learn these basics of C language.

C Character Set:

C computer language allows following valid alphabets, numbers and special symbols-
A, B, ……., Z
a, b, …….., z
0, 1, …….., 9
~  `  !  @  #  %  ^  & *  (  )  _  +  -  =  |  \  {  }  [  ]  :  ;   “  ‘  <  > , .  ?  /  $ 

C Keywords:

Keywords are the reserved words or terms which have a special meaning. This meaning has been described to compiler. These keywords can only be used for the purpose they are designed to. They cannot be used for anything else. There are 32 keywords provided in the C computer language as given below:

auto
break
case
char
const
continue
default
do
double
else
enum
extern
float
for
goto
if
int
long
register
return
short
signed
sizeof
static
struct
switch
typedef
union
unsigned
void
volatile
while
 
Meaning of these keywords will be explained later wherever and whenever they are used.

Variables and Constants:

As the name suggests variable refers to the entity that may change, and constant refers to the entity that doesn’t change. During execution, the program resides in computer’s memory (RAM). A program can have many data values and it does lots of calculations during program execution. The results too are stored in this memory. Computer memory consists of millions of cells. The data values are stored in these memory cells. To retrieve or store these data values easily, these memory cells or locations are given some meaningful names. These names are called variable names. Since, one can change the values of these memory locations; hence the name given to these locations is variable-name or variable simply. The data values itself are called constants. For example, you refer to a memory location by the name ‘x’, and give the value to it 5. During program execution, you give another value 7 to ‘x’. In this example, ‘x’ is a variable, because its value is changing and you can give different values to it at different times. 5 and 7 are constants, because these are fixed values. Variable can be called ‘identifiers’ and constants can be called ‘literals’.

Types of Variables and Constants:

Variables and constants can be organised in two broad categories-
  • Primary
  • Secondary
In primary type, there are three main categories-
  • Integer type
  • Real or floating point type
  • Character type
In secondary type, there come complex data types and user-defined data types. Some of these are given below-
  • Array
  • Structure
  • Union
  • Enum
A specific type of variable can contain the same type of constant. For example, an integer type of variable can hold only integer type of constant.

Variable Naming Conventions:

  • A variable name can be a combination of alphabets, digits, and an underscore ( _ ) and its size can be of one character to 31 characters.
  • A variable name must start with an alphabet or underscore ( _ ).
  • No blanks are permitted in the variable name.
  • No special character except underscore ( _ ) can be used.
  • Variable names should be meaningful.

Rules for Creating Constants:

Rules for creating primary constants are given below-

Integer Constant:

  • There should be at least one digit in the integer constant.
  • There should be no decimal point.
  • An integer constant can be positive or negative.
  • Default sign of integer constant is positive. If you don’t specify the sign, it is assumed to be positive.
  • There should be no commas or blanks in the constant.
  • The range of integer constant is from -32768 to +32767.
  • For some compiler, range is from -2147483648 to +2147483647.
  • Ex: 3, 56, -657, etc.
Real or Floating Point Constant:
  • A real constant must have a decimal point.
  • There should be at least one digit before or after decimal point.
  • No commas or blanks are permitted in the constant.
  • By default, floating point constants are positive, but it can be either positive or negative.
  • Ex: 0.5, 238.48, -65754.433, etc.
  • Floating point constants can be written in exponential form too. If the number is either too small or too large, exponential form is suitable to use.
  • In exponential form, the real constant is written in two parts. The first part is called mantissa, whereas second part is called exponent. These two parts are separated by the letter ‘e’ or ‘E’.
  • The first part mantissa can be positive or negative. Default sign is positive.
  • Thus, the number 0.000003827 can be written in exponential form as 3.827e-6. In normal mathematics it can be written as 3.827x10-6.
  • The range of real constant is -3.4e38 to 3.4e38.
Character Constants:
A character constant is any single alphabet, or a digit, or any special symbol enclosed within single quotation marks or apostrophes.
Ex: ‘a’, ‘6’, ‘&’, etc.




C Operator Precedence and Associativity

C Operator Precedence and Associativity Precedence of Operators in C: Operator precedence tells the order, in which operations are per...