Coding for DUMMIES 02 : Understanding the basics of C programming language

 


    Lets talk about more in C programming in this post. In here also, we are hope to use the same strategy that we use in our previous posts. So lets start our journey today. To start that lets do a simple type of program to revise what we did in our previous posts. But I would like to make it more challenging by asking you to perform some mathematical equation, rather than just using printf function to generate results.

Question 1 - Write a program that subtracts the value 15 from 87 and displays the result, together with an appropriate message, at the terminal.

Answer –

#include <stdio.h>

int main ()

{

int sub;

sub = 87-15;   /* COMPUTE RESULT */

printf (“The answer of subtracting 15 from 87 is %i\n” , sub);   /* DISPLAY RESULTS */

return 0;

}

 

#include <stdio.h>

By calling this command we call the standard input-output header file (stdio.h), which contains essential functions like printf() , scanf() , and many others. These functions are used to perform input and output operations in a C program. Header file is a text file that contains pieces of code written in C programming language. As an example printf is included in the stdio.h header file.We use printf function to display output or values that we want to display. When using the header files you don’t have to write the code for every single thing. It helps to reduce the complexity and number of lines of the code. It also gives you the benefit of reusing the functions that are declared in header files. So you can also reduce the time waste.

int main()

The main function In C programming is a special type of function that serves as the entry point of the program where the execution begins. In here by default, the return type of the main function is int. We declare main as int because the main function returns type integer. Int main represents that the function returns some integer even ‘0’ at the end of the program execution. ‘0’ represents the successful execution of a program. int main(void) represents that the function takes NO argument. Suppose, if we don’t keep void in the parentheses, the function will take any number of arguments.

int sub;

This is a declaration of a variable. int represents the data type of variable(integer) sub represents the name of the variable. Declaring the name of the variable we assign a name to the memory address of the variable. Memory address of a variable is the location which store data in memory.

/*COMPUTE RESULT*/

This is a multiline comment. Multiline comments can be used to explain code, and to make it more readable. So the comments can be declared in any language. We can use any user friendly language to write comments. So the comments are not executed when we are running the code. Because of that the comments are not visible when we are running the program. So there are two types of comments. They are single lined comments and multiline comments. Single line comments can be used when we want to write a comment in a single line. We can start a single line comment by using // symbol. So at the end of the line we should not present // symbol. But if you want to use comments more than one line you can use multiline comments. When we use multiline comments we should start with  /* symbol and the end of the comment we should also present */ symbol.

sub=87-15;

We can assign a value to a variable using = symbol. In above expression we have assigned the answer of substracting 15 from 87 to the sub variable. So when we assign values to the variables we can only input the values in same data type which we have initially entered before the variable name. As an example we have specified the data type of above sub variable as int. Therefore the value of the sub variable should be represent in integer values. Otherwise It will generate an error.

printf();

printf is a standard function and it is included in the stdio.h header file. Its purpose is to print formatted texts. Inside the paranteses, between double quotes we can declare any formatted text.

 

%i

C programming language, %i is a format specifier. %i specifies the type as integer. Format specifiers in C are used to take inputs and print the output of a variable. The symbol we use in every format specifier is %. Format specifiers tell the compiler about the type of the variable  that must be printed on the screen. So after specifies the format specifier we should use the name of the related variable by separating the formatted text with a comma.

return 0;

A return statement ends the execution of a function, and returns control to the calling function. A return statement can return a value to the calling function. The return 0; statement is typically used at the end of the main function to indicate that the program executed successfully.

I think that now you have better understand of how these types of codes are working. Now to do something different lets try out some debugging exercises.

Question 2 - Identify the syntactic errors in the following program. Then type in and run the corrected program to ensure you have correctly identified all the mistakes.

#include <stdio.h>

int main (Void)

(

INT sum;

 

/* COMPUTE RESULT

sum = 25 + 37 – 19

 

/* DISPLAY RESULTS //

printf ("The answer is %i\n" sum);

return 0;

}

 

To identify the syntactic errors in this program lets check statement by statement from the beginning of the code. In the first statement we can see #include <stdio.h> statement. In this statement there is no error. It is written in the form that can include stdio.h library to our program. Now lets move into the second statement.

In here we can see that in the void is written with a capital V letter. This is the first error that we found in this program. In C language void is a keyword. We must write “void” in all simple. void simply indicates that the function takes no arguments. If we write void as “Void” the compiler will not recognize it as a valid keyword. We cannot change the appearance the way we using the keywords as our wish. So in here that second statement must be int main (void).

After that we can see that there is a open bracket character. This is also an error. It must be a opening curly brace. Also we must remember that to use closing brace character. It will not be really a problem in this program since there is already that closing brace is available.

Lets move into the next statement. In here we can see there is already a error in the starting of the statement. “INT” must be “int” in here. int is  data type in C . Since it must be wriiten in the lowercase. These are predefined terms provided by the language.So it should be int sum; . The next error we found in this program is the comment. In the comment it opened the correct statement correctly. But it fails to close it. So that must be /* COMPUTE RESULT*/. Usually we  did not use /* */ to indicate single line comments. We use // mark. But in Quincy, it does not support // mark. So its okay to use this /* */ mark to indicate comment. The next error we found in this program is that the programmer forgot to add “ ; ” mark after the expression. So that must be corrected by adding a semicolon after the expression. So it will be, sum = 25 + 37-19; . The next error is also something related to comments. In “/* DISPLAY RESULTS //” statement the programmer opened the comment in the correct way, closed it with a error. So it must be /* DISPLAY RESULTS */ .I’m not going to explain it again because I have already discussed about this. In the next statement the programmer forgot to put a comma before the word sum. Otherwise the compiler cannot compile the program correctly. When looking at the next statements we cannot see any other syntactic error.

Now lets rewrite the previous program with the corrected changes.

 

#include <stdio.h>

int main (void)

{

int sum;

 

/* COMPUTE RESULT*/

sum = 25 + 37 – 19;

 

/* DISPLAY RESULTS */

printf ("The answer is %i\n", sum);

return 0;

}

 

Hope you all understood.

 

Now lets do some different type of exercises.

 

Question 3 – What output might you expect from the following program?

 

#include <stdio.h>

int main (void)

{

            int answer, result;

            answer = 100;

            result = answer-10;

            printf (“The result is %i\n”, result +5 );

            return 0;

}

 

In this example I am not going to explain about the #include <stdio.h> statement and the int main (void) statement, since we have already have discussed in this same post. Lets directly move into the first statement what we find immediately after the opening braces. In here int answer,result; is a variable declaration. Not just one declaration. There are two variable declarations in this same statement. We can simply unfold this statement into ,

int answer;

int result;

This first statement declares answer variable as an integer, and the second statement declares result variable as an integer. The next statement which is answer = 100; is a variable assigning. In here the answer variable is assigned with the value 100. In the next statement the result is assigned to the value that comes when subtracting 10 by the answer variable. In the next statement, it displays the result, together with an appropriate message. But in here you can see rather than just printing result, there is an operation has been performed. It displays not just the value in the result variable, it displays the value after adding 5 to the current result value. That part has been done by the expression that have been written in the last in the statement, which is result+5. Now we can take an idea about what will be the output of this program . Lets run it on and get the output , so you can check that with your answers.



After that lets understand what is a variable and what are the valid types. Variables are like symbolic address that helps us to deal with the memory. When choosing a variable name it is better if choose a meaningful name that represents the kind of data it has stored. By that way the reader can get a direct idea about what data this is carrying, without reading the whole program just by looking at it. These variables can store integers, floating point numbers, double values, characters, strings and pointers. But there are some strict rules that we have to follow when we are choosing a variable name. A variable can begin with any letter, whether it is in lowercase or uppercase it doesn’t matter. Or with underscore character. How ever you are not permitted to start a variable name with a number or any other character. You can use numbers in the middle of the variable name, but you use any other character other than underscore, even the middle of the variable.

Now lets do some exercise to check about your understanding about the variables.

Question 4 – Which of the following are invalid variable names? Why?

Int – Valid
char – Invalid. char is a reserved word.
6_05 – Invalid. A variable cannot start with a number.
Calloc – Valid.
Xx – Valid.
alpha_beta_routine – Valid.
floating – Valid.
_1312 – Valid.
z – Valid.
ReInitialize – Valid.
_ -  Valid.
A$ - Invalid. $ is not a valid character.

 

Lets do another exercise to take the idea about constants.

Question 5 – Which of the following are invalid constants? Why?

123.456

0x10.5

0X0G1

0001

0xFFFF

123L

0Xab05

0L

-597.25

123.5e2

.0001

+12

98.6F

98.7U

17777s

0996

-12E-12

07777

1234uL

1.2Fe-7

15,000

1.234L

197u

100U

0XABCDEFL

0xabcu

+123

Answers –

0x10.5 – Hexadecimal constant cannot have decimal points.

0X0G1 – Hexadecimal constant cannot have letter G.

0996 – Octal constant only can have numbers from 0 upto 7.

17777s – s is not a valid numeric suffix.

1.2Fe-7 – Fe is not a valid floating point suffix.

To understand about the behavior of characters and to understand how they can assign, lets do another exercise. In here I am going to help you understand the execution of each program statement by explaining each statement.

 

Question 6 – What output would you expect from the following program?


#include<stdio.h> 
int main (void)
{

    char c, d;
    c = 'd';
    d = c;
    printf ("d = %c\n", d);
    return 0;

}

 

The first statement connects the stdio.h header file to our program. int main (void) is the main function and this is the starting of the execution of our program. Opening braces and the closing braces represents the scope of the main function. The first statement which is edited immediately after the braces, which is char c, d; is a variable declaration. It states that c and d both are character variables. Meaning that they store only a single character. The next statement, which is c=‘d’; is a variable initializing. In here we assign the character d into the variable c. The next statement is also a variable initialization and in here we initializing the value in c into the variable d. In the printf statement we display the value stored in the variable d and finally the return statement, return 0 by telling that the program executed successfully.


so the answer to question 6 is d

 

Hope you have understand every single thing that we discussed so far. So from now I’m going to discuss some programs with mathematical operations by Q&A form with you.

 

Question 7 – Convert given value in Meter to centimeter.

 

Answer –


#include <stdio.h>
int main()
{
         float meter_value = 0.0f;
         float centimeter_value = 0.0f;
         
         printf("Enter a value in Meter : ");
         scanf("%f", &meter_value);
         
         centimeter_value = 100*meter_value;
         printf("%.2f m is equal to %.2f cm\n",
         meter_value,centimeter_value);
         
         return 0;
}

 

In here, you can see that I have inserted the stdio.h header file and the main function at the beginning of the program. Now you know what they actually do in our program. In here I have declared the variable meter_value to store the value in meters and the variable centimeter_value to store the value that given after the operation. In here I declared them as floating point values, because the inputs and outputs may contain decimal point numbers. As we know that when we declared some value as a floating point value, it automatically allocates double space. To avoid that we can put a “f” after initializing. In printf(“Enter a value in Meter : ”);  statement we simply asking for a user input. In the scanf(“%f”, &meter_value); statement the program store the user inputs into that particular variables, in here meter_value. The & symbols directs the control to the memory address of the variable. In the next statement we can see an expression. It is 100*meter_value . This is a variable expression. Because it has an variable in the middle of the expression. In this statement we calculate the value in centimeters by multiplying the value in meters by 100 and assign that value into the variable which is centimeter_value. Tn the printf statement, we displaying the values that we stored in the both meter_value and the centimeter_value. Finally the return 0 statement which return the value 0, after executing the program successfully. The output can be show as below.



Question 8 – Calculate the volume of a cylinder. (volume of cylinder =  PI*r2h)

 

#include <stdio.h>

int main()

{
          float radius = 0.0f;
          float height = 0.0f;
          float volume = 0.0f;
         
          printf("Enter the radius of the cylinder : ");
          scanf("%f", &radius);
          printf("Enter the height of the cylinder : ");
          scanf("%f", &height);
         
          volume = 3.1459*radius*radius*height;
         
          printf("The volume of the cylinder is %.4f\n", volume);
         
          return 0;
}

In here also, you can see that I have inserted the stdio.h header file and the main function at the beginning of the program. This is essential for every program that we are going to execute. In this program our goal is to create a program that can calculate the volume of a cylinder when we give the radius value and height of the cylinder. After main function I have declared 3 variables, the variable radius to store the radius of the cylinder and the variable height to store the height of the cylinder and the volume variable to store the calculated volume of the cylinder. In here I declared them as floating point values, because the inputs and outputs may contain decimal point values. In here we put a “f” after initializing the variable to avoid allocating double space. In printf(“Enter the radius of the cylinder: ”);  statement we simply asking for a user input. In the scanf(“%f”, &radius); statement the program store the user inputs into that particular variables, in here radius. The & symbol directs the control to the memory address of the variable (This was discussed in the previous question also). In the next statement we can see that we are asking user to input the height of the cylinder. This process is same as the previous two statements. After that there is a statement with an expression which uses to calculate the volume of the cylinder. In the printf statement it prints the calculated volume. In this statement I think you may notice that there is .4f at the end of the statement. This means and tells the computer to display the value of the volume variable by 4 decimal numbers. In the return statement in returns the value zero after, executing the program successfully. The output of the program can be show as below.



Question 9 – Calculate average marks of 4 subjects which, entered separately.

Answer –

 
#include <stdio.h>
int main()
{
    float mark1 = 0.0f;
    float mark2 = 0.0f;
    float mark3 = 0.0f;
    float mark4 = 0.0f;
    float average = 0.0f;
 
    printf("Enter the marks for first subject : ");
    scanf("%f", &mark1);
    printf("Enter the marks for second subject : ");
    scanf("%f", &mark2);
    printf("Enter the marks for third subject : ");
    scanf("%f", &mark3);
    printf("Enter the marks for fourth subject : ");
    scanf("%f",&mark4);
 
    average = (mark1+mark2+mark3+mark4)/4;
 
    printf("Average of the 4 subjects = %.2f\n", average);
 
    return 0;
}

In this example there is nothing new. All the things that we can see in this program have discussed earlier in previous statements. So I will show you the output. All you have to do is understand which function do what and their output.


Question 10 - Convert the given temperature in Celsius to Fahrenheit. T(°F) = T(°C) × 1.8 + 32

Answer –

#include <stdio.h>
int main()
{
          float celcius_value = 0.0f, fahrenheit_value = 0.0f;
          printf("Enter the temperature value in Celcius : ");
          scanf("%f", &celcius_value); 
          fahrenheit_value = (celcius_value*1.8)+32;
         printf("%.2f Celcius is equal to %.2f Fahrenheit\n", celcius_value,                  fahrenheit_value);
          return 0;
}

In here we have taken two variables, which are celcius_value to store the temperature value in Celcius and Fahrenheit_value to store the calculated Fahrenheit value. Both integers are declared as floating point values, because the values like temperatures can contain decimal values. After declaring variables the printf program statement and the scanf program statements is wriiten to take the user input for the variable celcius_value. After that we can see there is a statement written to convert the Celcius value into the Fahrenheit value. In the last printf statement which we use to display values you can see there is %.2f marks. That means we are asking computer to display the results with two decimal points. These kinds of tricks can use to make our program more visual. Because when there is a lot of decimal points, it is hard to focus directly. The output of the program is shown below.


Now try doing these questions . All you need to understand and design the program to do the following questions are now covered. If it needs something more than this, I will explain them in particular places


Question 11 - Find the value of y using y = 3.5x+5 at x = 5.23.
Answer –

#include <stdio.h>
int main()
{
            float y=0.0f, x=5.23f;
            y=3.5*x + 5;
           printf("The value of y is              %.3f\n", y);
            return 0;
}

 

This is not much harder. All the things in here have already discussed. The output can shown as below.


Question 12 - Find the cost of 5 items if the unit price is 10.50 Rupees.

Answer -

 #include <stdio.h>
int main()
{
              int items=0;
              float unit_price=0.0f, cost=0.0f;
             
              printf("Enter the number of items : ");
              scanf("%i", &items);
              printf("Enter the unit price : ");
              scanf("%f", &unit_price);
             
              cost=items*unit_price;
             
              printf("cost = %.4f\n",cost);
             
              return 0;
}

Output of this program can be shown as follow.


Question 13 - Enter the name, height, weight and gender of a person and calculate his/her BMI in Kg.                                               BMI = weight/ height2

Answer –

#include <stdio.h>

int main()

{

              char name[15]="";

              char gender[15]="";

              float height=0.0f, weight=0.0f, bmi=0.0f;

             

              printf("Enter your name : ");

              scanf("%s", &name);

              printf("Enter your gender : ");

              scanf(" %s", &gender);

              printf("Enter your height : ");

              scanf("%f", &height);

              printf("Enter your weight : ");

              scanf("%f", &weight);

             

              bmi=weight/(height*height);

             

              printf("Name   : %s\n", name);

              printf("Gender : %s\n",gender);

              printf("BMI    : %.4f\n", bmi);

             

              return 0;

}

 

This program is very interesting. Because there is something new to us that we didn’t find before in our previous exercises. This program is also started by the statement #include <stdio.h> and int main() statements. We have discussed about the function of these statements before in this post. The first statement edited within the braces is a variable declaration. Second and third statements are also variable declarations. You already know what is going in the third variable declaration statements. But in the first and second variable declaration statements it is different. Those are string variables, meaning that they store one or mare characters. char is the data type and the word that comes after char represents the variable name. In here you must remember that we use same data type, which is char to declare both characters and strings. They differ from the way we declaring each of them . When declaring a character we use single quotations after the equal sign. But in string we use double quotations after equal sign and in addition to that we use square brackets after variable name to make its a array. Inside those brackets we type the string length that we are going to store. We use %s as the format specifier for strings. After that declaration statements there are statements, that written to take input from the user and after that there is a variable expression, which you already know about and after that there are program statements that edited to display values and finally we can the return statement. So the output of this program will be as follows, 



Now try the two questions below this and check your answers with the given answers.

 

Question 14 - Write a program that converts inches to centimeters. For example, if the user enters 16.9 for a Length in inches, the output would be 42.926cm. (Hint: 1 inch = 2.54 centimeters.)

Answer –

#include <stdio.h>
int main ()
{
            float cm = 0.0f;
            float inch = 0.0f;
           
            printf("Enter value in inches : ");
            scanf("%f", &inch);
           
            cm = inch*2.54;
           
            printf("%.2f inch in centimeter is %.3fcm.\n", inch,cm);
            return 0;         
}

Output -


Question 15 - The figure gives a rough sketch of a running track. It includes a rectangular shape and two semi-circles. The length of the rectangular part is 67m and breadth is 21m.Calculate the distance of the running track.


Answer –

#include <stdio.h>
int main ()
{
            float width = 21.0f;
            float length = 67.0f;
            float distance = 0.0f;
            float radius = 0.0f;
           
            radius = width/2.0;
            distance = 2*length+2*3.14*radius;
           
            printf("The distance of the track is %.2fm.\n",distance);
            return 0;         
}

Output - 





How now all you get detailed knowledge of how the C programming works. Lets see you in another post with more knowledge about the language C.

 

Contribution -      Ranishka Gunathilake    @RG761  5641  – 2, 3, 7, 8, 13, 14
                            Sandakelum Kumarasiri    @SK2208    5737  - 4, 5, 9, 10, 15
                            Mahesh Wijenayaka    @MW1513    5734   - 1, 6, 11, 12