Professional Documents
Culture Documents
1. Machine language
2. Assembly language
This language uses codes such as ADD, MOV, and SUB to represent instructions.
These codes are called mnemonics. Though these codes have to be memorized,
assembly language is much easier to use than machine language.
3. High-level languages
High-level languages such as BASIC, FORTRAN, C, C++, and JAVA are very much
easier to use than machine language or assembly language because they have
words that are similar to English.
4. Test the algorithm for correctness: Provide test data and try to work out the
problem as the computer would. This is a critical step but one that
programmers often forget.
7. Run the program: Instruct the computer to execute the program. The
process of running the program differs from language to language.
8. Debug the program: Make sure that the program runs correctly without any
errors or bugs as they are called in computer terminology. Finding the errors
and fixing them is called debugging. Don’t get depressed when bugs are
found. Think of it as a way to learn.
Structure of a C program
{ { {
} } }
Programmers are free to name C program functions (except the main() function).
The following is a simple C program that prints a message ‘Hello, world’ on the
screen.
1.#include<stdio.h>
2.main()
3.{
4. printf(“Hello, world”);
5.}
The information enclosed between ‘/* */’ is called a ‘comment’ and may appear
anywhere in a C program. Comments are optional and are used to increase the
readability of the program.
The ‘#include’ in the first line of the program is called a preprocessor directive. A
preprocessor is a program that processes the C program before the compiler. All
the lines in the C program beginning with a hash (#) sign are processed by the
preprocessor.
‘stdio.h’ refers to a file supplied along with the C compiler. It contains ordinary C
statements. These statements give information about many other functions that
perform input-output roles.
Thus, the statement ‘#include<stdio.h>’ effectively inserts the file ‘stdio.h’ into the
file hello.c making functions contained in the ‘stdio.h’ file available to the
programmer. For example, one of the statements in the file ‘stdio.h’ provides the
information that a function printf() exists, and can accept a string (a set of
characters enclosed within the double quotes).
The next statement is the main() function. As you already know, this is the place
where the execution of the C program begins. Without this function, your C
program cannot execute.
Next comes the opening brace ‘{’, which indicates the beginning of the function.
The closing brace ‘}’ indicates the end of the function.
The statement printf() enclosed within the braces‘{}’ informs the compiler to print
(on the screen) the message enclosed between the pair of double quotes. In this
case, ‘Hello, world’ is printed. As mentioned earlier, the statement printf() is a
built-in function shipped along with the C compiler. Many other built-in functions
are available that perform specific tasks. The power of C lies in these functions.
Errors/bugs are very common while developing a program. If you don't detect them
and correct them, they cause a program to produce wrong results. There are three
types of errors — syntax, logical, and run-time errors. Let us look at them:
3. Runtime errors: These errors occur during the execution of the programs
though the program is free from syntax and logical errors. Some of the most
common reasons for these errors are
Unless you run the program, there is no chance of detecting such errors.
Exercise
Table 1
*/
#include<stdio.h>
main()
inta=10;
floatb=3.1412;
charch=’A’;
printf(“%d\n%f\n%c”,a,b,ch);
When you run this program, the following output will be displayed on screen:
10
3.1412
The characters %d, %f, and %c are called format specifiers or simply format
strings. The ‘%’ symbol alerts the compiler that a variable is to be printed at that
location and the letter that follows tells it to print the value as an int, float, char,
and so on.
The character ‘\n’ is called a newline character. It is used to insert a new line so
that the values in variables mentioned after it are printed on a new line
Characters like the ‘\n’ character that start with ‘\’ are called escape sequences.
The following tables gives you a partial list of format strings and escape
sequences that you will frequently come across in C programs.
Table 2 Table 3
\n (newline)
\t (tab)
\b (backspace)
\" (double quote)
\\ (backslash)
#include <stdio.h>
int main(void)
{
printf("Audible or visual alert. \a\n");
printf("Form feed. \f\n");
printf("This escape, \r, moves the active position to the initial
position of the current line.\n");
printf("Vertical tab \v is tricky, as its behaviour is unspecified
under certain conditions.\n");
return 0;
}
#include <stdio.h>
main ( )
{
int ml,m2,m3,m4,m5;
int total;
float average;
printf("Enter the 5 marks..");
scanf("%d%d%d%d%d",&ml,&m2,&m3,&m4,&m5);
total = ml + m2 + m3 + m4 + m5;
average = total / 5.0;
printf("Total=%d average%f\n",total,average);
main( )
{
int p, n ;
float r, si ;
printf ( "Enter values of p, n, r" ) ;
scanf ( "%d %d %f", &p, &n, &r ) ;
si = p * n * r / 100 ;
printf ( "%f" , si ) ;
Exercise
1. Write a program to store 10, 12.5, and a character ‘Z’ in integer, float,
and character variables respectively and display the values on the
screen.
2. Write a program to store 15, 3,14, and ’X’ in integer, float, and character
variables respectively and display the values on separate lines on the
screen.
Input Function
You would do this by opening the program, assigning the values to variables,
and compiling the program again. However, this is a cumbersome process, as
you have to recompile the program each time that you make a change.
Moreover, when using an assignment operator, you may not know in advance
the values that you want to assign to the variables.
Almost every program should include statements used to request input from users
while the program is running. Such statements are called input statements. The C
compiler has built-in input functions for storing data (entered through a keyboard)
in variables while the program is running. These input functions facilitate
interactive programming, i.e., you can interact with a running program. One such
widely used function in C is scanf().
The syntax of scanf() and that of printf() look alike except that an ‘&’ symbol
precedes every variable in the case of scanf(). This function is used to input
different kinds of values — int, float, and char.
1. int a;
2. float b;
3. char c;
4. printf(“Enter an integer:”);
5. scanf(“%d”,&a);
6. printf(“Enter a float:”);
7. scanf(“%f”,&b);
8. printf(“Enter a character:”);
9. scanf(“%c”,&c);
Apart from the scanf() function, there are also other functions such as getchar()
and gets() to store characters and strings (set of characters). The following
program demonstrates the use of these functions.
#include<stdio.h>
main()
1. char a;
3. a=getchar();
Observe how the function getchar() is used in this program. This function
receives a character entered by the user and stores it in the variable a. The
printf() function written below the getchar() statement displays on the
screen the character that you entered from the keyboard. C, however, also
provides a function called putchar() to display the character on the screen. You
can use this function in the above program instead of printf(). The following
statement is written to use putchar() in the above program.
putchar(a);
The program that displayed a string (Hello, World) on the screen use the
printf() function. Now see how to accept a string from keyboard and display it.
#include<stdio.h>
main()
char a[25];
gets(a);
printf (“%s”,a);
In this program:
The fourth statement displays the string that you entered on the
screen.
You can also get the same result for the above program by using another kind of
output function, puts(). This function is used exclusively for handling strings. It
can’t be used for printing numeric data. The following statement would be
written to use puts() in the above program.
puts(a);
Exercise
1. Write a program to accept and store the values 15, 30.5 and ‘A’ in the
variables i, f, and c using the function scanf(), and to display them using
the printf() function.
2. Write a program to accept and store a character (say, ‘$’) in the variable
ch using the function getchar() and t display it on the screen using the
function putchar().
3. Write a program to accept and store a string (say, “Hi-Tech City”) in the
variable city and to display it on the screen using the function puts().
MORE ON I/O
The function getchar does not take any parameters. When it is called, it reads
a character from the standard input device, and returns an integer value
corresponding to the ASCII code of the input char. If no input is available
getchar returns a special value called EOF.
putchar is the twin of getchar and does the complementary job: it prints a char to the
standard output device. The char which is to be printed will have to be passed as
parameter to putchar.
#include <stdio.h>
main ( )
{
int c;
printf ("Enter an uppercase letter");
printf("Lowercase=”);
putchar(c + 32);
putchar('A') ;
putchar (65); /* int and char can be mixed in c */
Since putchar takes an int as a parameter, you can pass to it either an int
constant (like 65) or an int variable, or an integer expression, or a function that
returns an integer (for example getchar).
Mathematical operators
1. + - Addition
2. - - Subtraction
3. * - Multiplication
4. / - Division
#include<stdio.h>
main()
2. printf(“Addition\n”);
3. c=a+b;
4. printf(“Result=%f\n”,c);
5. printf(“Subtraction\n”);
6. c=a-b;
7. printf(“Result=%f\n”,c);
8. printf(“Multiplication”);
9. c=a*b;
10. printf(“Result=%f\n”,c);
11. printf(“Division\n”);
12. c=a/b;
13. printf(“Result=%f\n”,c);
Addition
Result=7.000000
Subtraction
Result=3.000000
Multiplication
Result=10.000000
Division
Result=2.000000
Observe the last output. The result of division is displayed as 2.000000 instead of
2.500000! What is the reason for this? Let us find out.
Division works differently for ints and floats. Floating-point division results in a
float, and integer division results in an int. In this example, the two variables
involved in the division calculation are of integer type, and hence the result is an
integer. In C, any fraction resulting from an integer division is ignored. This process
is called truncation. This can be avoided using a mechanism called typecasting.
Typecasting
c= (float) a/b;
A pair of parentheses with a data type written inside is known as C’s cast operator.
To print the output correctly, remember to change the format string in the printf()
statement on line 13 from %d to %f.
SPECIAL OPERATORS
count++;
So
Temperature += 5;
is actually equivalent to saying
Temperature = Temperature + 5;
What is an expression?
If you have done some basic math, you would have heard of expressions. An
expression consists of a combination of operators and operands (values on which
an operator operates on). For example
c=a+b;
or
x=a*(b/c+d*3)+5;
3rd = Assignment
If there are two operators of the same level in an expression, the operator that
comes first is considered first — ‘first come, first served’.
#include<stdio.h>
main()
1. int a=10,b=20,c=15,d=5,result;
2. result=a+b%5-c*d/2;
3. printf(“Result=%d”,result);
}
Result=-27
result=10+20%5-15*5/2
Exercise:
2. Write a program to accept basic salary, HRA, DA and PF and display the net
salary. (Hint: Net salary is computed as: Basic+HRA+DA–PF).
3. Write a program to accept the radius of a circle and display its radius and
perimeter. (Hint: area=∏*r*r; perimeter= 2*∏*r)
Relational Operators
1. Relational operators are used in Boolean conditions or expressions.
2. Boolean conditions or expressions return either true or false.
3. The relational operator returns zero values or nonzero values.
4. The zero value is taken as false while the nonzero value is taken as true.
1. The relational operators are as follows: <, <=, >, >=, ==, !=.
2. The priority of the first four operators is higher than that of the later two operators.
Boolean Operator in C
2. Both sides of the operator must evaluate to true before the entire expression become
|| Operator
1. || operator: evaluate from left to right.
2. If either side of the condition is true, the whole expression results in true.
Logic Operator OR ||
#include <stdio.h>
int main()
{
char c;
printf("Y/y?");
c=getchar();
if(c=='Y' || c=='y')
{
printf("Bye!\n");
}
else
{
printf("Okay!\n");
}
return(0);
}
Practice Questions
1. Modify the temperature conversion program to print a heading above the table.
#include <stdio.h>
int main(void)
{
float fahr, celsius;
int lower, upper, step;
lower = 0;
upper = 300;
step = 20;
printf("F C\n\n");
fahr = lower;
while(fahr <= upper)
{
celsius = (5.0 / 9.0) * (fahr - 32.0);
printf("%3.0f %6.1f\n", fahr, celsius);
fahr = fahr + step;
}
return 0;
}
int main(void)
{
float fahr, celsius;
int lower, upper, step;
lower = 0;
upper = 300;
step = 20;
printf("C F\n\n");
celsius = lower;
while(celsius <= upper)
{
fahr = (9.0/5.0) * celsius + 32.0;
printf("%3.0f %6.1f\n", celsius, fahr);
celsius = celsius + step;
}
return 0;
}
int main(void)
{
printf("Press a key. ENTER would be nice :-)\n\n");
printf("The expression getchar() != EOF evaluates to %d\n",
getchar() != EOF);
return 0;
}
#include <stdio.h>
int main(void)
{
printf("The value of EOF is %d\n\n", EOF);
return 0;
}
#include <stdio.h>
int main(void)
{
int blanks, tabs, newlines;
int c;
int done = 0;
int lastchar = 0;
blanks = 0;
tabs = 0;
newlines = 0;
while(done == 0)
{
c = getchar();
if(c == '\t')
++tabs;
if(c == '\n')
++newlines;
if(c == EOF)
{
if(lastchar != '\n')
{
++newlines; /* this is a bit of a semantic stretch, but it
copes
* with implementations where a text file might
not
* end with a newline. Thanks to Jim Stad for
pointing
* this out.
*/
}
done = 1;
}
lastchar = c;
}
Write a program to copy its input to its output, replacing each string
of one or more blanks by a single blank.
#include <stdio.h>
int main(void)
{
int c;
int inspace;
inspace = 0;
while((c = getchar()) != EOF)
{
if(c == ' ')
{
if(inspace == 0)
{
inspace = 1;
putchar(c);
}
}
return 0;
}
Write a program that prints its input one word per line.
#include <stdio.h>
int main(void)
{
int c;
int inspace;
inspace = 0;
while((c = getchar()) != EOF)
{
if(c == ' ' || c == '\t' || c == '\n')
{
if(inspace == 0)
{
inspace = 1;
putchar('\n');
}
/* else, don't print anything */
}
else
{
inspace = 0;
putchar(c);
}
}
return 0;
}
#include <stdio.h>
#include <limits.h>
int
main ()
{
printf("Size of Char %d\n", CHAR_BIT);
printf("Size of Char Max %d\n", CHAR_MAX);
printf("Size of Char Min %d\n", CHAR_MIN);
printf("Size of int min %d\n", INT_MIN);
printf("Size of int max %d\n", INT_MAX);
printf("Size of long min %ld\n", LONG_MIN); /* RB */
printf("Size of long max %ld\n", LONG_MAX); /* RB */
printf("Size of short min %d\n", SHRT_MIN);
printf("Size of short max %d\n", SHRT_MAX);
printf("Size of unsigned char %u\n", UCHAR_MAX); /* SF */
printf("Size of unsigned long %lu\n", ULONG_MAX); /* RB */
printf("Size of unsigned int %u\n", UINT_MAX); /* RB */
printf("Size of unsigned short %u\n", USHRT_MAX); /* SF */
return 0;
}