You are on page 1of 21

C Programming- Day 1

Programming: The next step after developing an algorithm

Once we develop the algorithm, we need to convert it into a computer program


using a programming language (a language used to develop computer programs).
A programming language is entirely different from the language we speak or write.
However, it also has a fixed set of words and rules (syntax or grammar) that are
used to write instructions for a computer to follow.

Programming languages can be divided into three types. They are:

1. Machine language

This is the basic language understood by a computer. This language is made up of


0’s and 1’s. A combination of these two digits represents characters, numbers,
and/or instructions. Machine language is also referred to as binary 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.

A quick comparison of programming languages


Machine Assembly High-level
Language Language Languages
Time to execute Since it is the basic A program called an A program called a
language of the ‘assembler’ is compiler or
computer, it does required to convert interpreter is
not require any the program into required to convert
translation, and machine language. the program into
hence ensures Thus, it takes machine language.
better machine longer to execute Thus, it takes more
efficiency. This than a machine time for a computer
means the language program. to execute.
programs run
faster.
Time to develop Needs a lot of skill, Simpler to use than Easiest to use.
as instructions are machine language, Takes less time to
very lengthy and though instruction develop programs
complex. Thus, it codes must be and, hence, ensures
takes more time to memorized. It takes better program
program. less time to develop efficiency.
programs as
compared to
machine language.
Developing a computer program

Follow the steps given below to become a successful programmer:

1. Define the problem: Examine the problem until you understand it


thoroughly.

2. Outline the solution: Analyze the problem.

3. Expand the outline of the solution into an algorithm: Write a step-by-step


procedure that leads to the solution.

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.

5. Convert the algorithm into a program: Translate the instructions in the


algorithm into a computer program using any programming language.

6. Document the program clearly: Describe each line of instruction or at least


some important portions in the program. This will make the program easy to
follow when accessed later for corrections or changes.

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

Every C program consists of one or more functions. A function is nothing but a


group or sequence of C statements that are executed together. Each C program
function performs a specific task. The ‘main()’ function is the most important
function and must be present in every C program. The execution of a C program
begins in the main() function.

The figure below shows the structure of a C program.

main() function1() function2()

{ { {

statement1; statement1; statement1;

statement2; statement2; statement2;

……; ……..; ……;


……; ……..; ……;

} } }

Programmers are free to name C program functions (except the main() function).

Writing your first C program

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.}

1. Save the program as hello.c by pressing F2 or Alt + ‘S’.


2. Press Alt + ‘C’ or Alt + F9 to compile the program.
3. Press Alt + ‘R’ or Ctrl + F9 to execute the program.
4. Press Alt + F5 to see the output.

Understanding the program

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.

Be cautious about errors!

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:

1. Syntax errors: These errors occur because of wrongly typed statements,


which are not according to the syntax or grammatical rules of the language.
For example, in C, if you don’t place a semi-colon after the statement (as
shown below), it results in a syntax error.

printf(“Hello,world”) – error in syntax (semicolon missing)

printf("Hello,world"); - This statement is syntactically correct.

2. Logical errors: These errors occur because of logically incorrect instructions


in the program. Let us assume that in a 1000 line program, if there should
be an instruction, which multiplies two numbers and is wrongly written to
perform addition. This logically incorrect instruction may produce wrong
results. Detecting such errors are difficult.

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

a. when you instruct your computer to divide a number by zero.


b. when you instruct your computer to find logarithm of a negative
number.
c. when you instruct your computer to find the square root of a
negative integer.

Unless you run the program, there is no chance of detecting such errors.

Exercise

1. Write a C program to print your name on the screen.

2. Write a C program to print the name of your favorite cricketer.


Data Type

Table 1

Data Memory size Range


type (in bytes)
int 2 or 4 -32,768 to +32767 (2-bytes)
(depends on
whether you -2,147,483,648 to +2,147,483,648 (4-
are using 16- bytes)
bit processor
or 32-bit
processor)
short 2 -32768 to +32767
long 4 -2,147,483,648 to +2,147,483,648
float 4 ±10 e-37 to ±10e+37
double 8 ±10 e-307 to ±10e+307
char 1 -128 to +127

Declaring variables in a C program

Writing a program to print values in variables

*/

#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

Sl. No Data type Format Sl. Escape Purpose


Specifier No sequence
1. Int d 1. \n Newline
2. float f 2. \t Tab
3. char c 3. \a Beep
4. unsigned int u 4. \b Backspace
5. string s 5. \r Return
6. long int ld
7. double lf Experiment to find out what happens
when printf 's argument string
contains \c, where c is some character not listed in:

\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;
}

3. Calculate Average of marks for five subjects.

#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);

4. Calculate Simple Interest

/* Calculation of simple interest */

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 ) ;

5. Print the ASCII Code

#include <stdio.h> main ( )


{
int i; float f; char c; i = 65;
f = i; /* f now contains 65.0 */
C.= f; /* c contains 65 */
printf("%c ",C);/* prints 'A': the ascii code of 'A' is 65 I */
f = f + 0.99;
i = f; /* i contains 65 and not 66 I */ /* c becomes 66 */
c = c+ 1;
printf("%d\n", c+l) ; /* prints 67 */

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

Suppose you develop a piece of software to be used for computerizing a bank’s


operations. In the code for this software, you would write a program to store
details of the bank’s customers. In this program let us assume that you have
used the assignment operator (refer to the previous article) for storing customer
details such as name, age and telephone number in the respective variables.
How would you enter the details of a new customer?

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.

Data and input functions

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 scanf() function

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.

Use of the scanf() function


main()

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);

10. printf(“You entered %d %f %c”, a, b, c);

Other input functions

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;

2. printf (“Enter any character:”);

3. a=getchar();

4. printf(“The character you entered is:%c”,a);

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);

Accepting strings using gets() function

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];

printf (“Enter a string:”);

gets(a);

printf (“%s”,a);

In this program:

The first statement — char a[25]; — informs the compiler to set


aside 25 locations to store 25 characters.

The second statement prompts the user by displaying the message


“Enter a string” on the screen.

The third statement accepts the string from the keyboard.

The fourth statement displays the string that you entered on the
screen.

%s stands for ‘format string’ to print strings.

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

character I/O – getchar() and putchar()

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.

use of getchar and putchar

#include <stdio.h>
main ( )
{
int c;
printf ("Enter an uppercase letter");

c = getchar();/* parenthesis needed even if no parameter I */

printf("Lowercase=”);
putchar(c + 32);

putchar('A') ;
putchar (65); /* int and char can be mixed in c */

putchar('A' + 5); /* prints 'F' : char can take part in arithmetic ! */

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).

Writing programs to process data

Mathematical operators

In C, arithmetic operations (addition, subtraction, multiplication, division, and


modulo division) are performed using five arithmetic operators:.

1. + - Addition

2. - - Subtraction

3. * - Multiplication

4. / - Division

5. % - Modulo Division (remainder after integer division)

#include<stdio.h>

main()

1. int a=5,b=2; float c;

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);

When you run this program, you will see this:

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

Typecasting allows you to convert the value of an expression to a particular data


type. If you want the result of 5/2 in the above example as 2.5, you must type the
code in line 12 as follows:

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

C provides a number of operators which perform various operations.

+ + serves as the increment operator in C and -- serves as the decrement


operator.

The increment and decrement operators are available in two forms:


1. The prefix form and 2. the postfix form. That is, if you have an int variable by
name count, and you want to increment it, you can achieve this either by saying
++count
or by saying

count++;

Difference between the two forms

int a = 50, b = 100;


a = ++b /* now both a and b contain 101 I*/
b = a++; /* now b contains 101 whereas a's value is 102 I*/
printf("%d\n", ++a) /* printf is going to print 103 now */

printf("%d\n", a++) /* prints 103 again I; but a has become 104 */

C provides a number of operators which can be expressed in the general form


op=
Where op is an operator like +,., *, I, % etc.
So you have operators like + = , - = , * = ,
= and so on. In general, an expression likes
var op= value;
is interpreted as

var = var op value;

So
Temperature += 5;
is actually equivalent to saying

Temperature = Temperature + 5;

Total *= i; /* Total = Total * i ; */


Count 1; /* Equivalent to Count */

These operators serve a number of purposes:


1. They provide a short hand notation, which once clearly understood and
mastered, reduce the number of key strokes.
2. They reduce the possibility of spelling errors (since you do not have to specify
the variable name on both sides of the assignment operator).
3. Last but definitely not the least: They often result in better object code.

Expressions and operator precedence

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;

operands can be constants, variables, or combinations of the two.

In C, arithmetic expressions are evaluated according to a strict hierarchy of


operators. Given below is the hierarchy of arithmetic operators in C:

Priority Operators Description

1st */% multiplication, division, modulo division

2nd +- addition, subtraction

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’.

/* Demo of operator precedence */

#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);
}

When you run this program you will see this:

Result=-27

Let us see how you got this result.

The expression result= a+b%5-c*d/2 is evaluated as follows:

result=10+20%5-15*5/2

1. result=10+0-15*5/2 % is evaluated first. The remainder is 0 when


5 divides 20.

2. result=10+0-75/2 Multiplication is performed. 15*5=75.

3. result=10+0-37 Division is performed. (75/2 results in 37 instead of 37.5


because both 75 and 2 are integers.

4. result=10-37 Addition is performed because it comes before


minus.

5. result=-27 Finally subtraction is performed and –27 is


stored in the variable result.

Exercise:

1. Write a program to accept the marks of a student in three subjects, and


display the total marks and the average.

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

Character Set Boolean Operator


&& and
|| or
&& Operator
1. && operator: evaluate a Boolean expression from left to right.

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);
}

logic operator and (&&)


#include <stdio.h>
int main(void)
{
char letter =0;

printf("Enter an upper case letter:");


scanf(" %c", &letter);

if ((letter >= 'A') && (letter <= 'Z'))


{
letter += 'a'-'A';
printf("You entered an uppercase %c.\n", letter);
}
else
printf("You did not enter an uppercase letter.\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;
}

2. Write a program to print the corresponding Celsius to Fahrenheit table.


#include <stdio.h>

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;
}

Verify that the expression getchar() != EOF is 0 or 1


#include <stdio.h>

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;
}

Write a program to print the value of EOF.

#include <stdio.h>

int main(void)
{
printf("The value of EOF is %d\n\n", EOF);

return 0;
}

Write a program to count blanks, tabs, and newlines.

#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 == ' ')


++blanks;

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;
}

printf("Blanks: %d\nTabs: %d\nLines: %d\n", blanks, tabs, newlines);


return 0;
}

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);
}
}

/* We haven't met 'else' yet, so we have to be a little clumsy */


if(c != ' ')
{
inspace = 0;
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;
}

Write a program to determine the ranges of char , short , int , and


long variables, both signed and unsigned , by printing appropriate
values from standard headers and by direct computation. Harder if you
compute them: determine the ranges of the various floating-point
types.

#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;
}

You might also like