CODEXCEL Tutorial 02 - Basics of C Programming





CODEXCEL Tutorial 02 - Basics of C Programming


 In this post, let's discuss C programming in more detail. We hope to apply the same approach here as we did in our earlier posts. So let's get going on this journey now. Let's begin by running a quick program to review the work we did in our earlier posts.


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>
The standard input-output header file (stdio.h) contains essential functions like printf() and scanf() for C program operations. These files, like printf, reduce code complexity and line count, while also allowing for reusing declared functions, reducing time waste and reducing the number of lines in the code.

int main ()

In C programming, int main() function serves as the program's entry point and starting point for execution. The primary function's return type is int, and its value is '0' at the end of execution. The function accepts NO arguments and can accept any number of arguments.

int sub;

The variable declaration declares its data type as an integer, assigns the name 'sub' to its memory address, which is the location where the data is stored.

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

The = symbol (assignment operator)allows us to give a variable a value. The sub variable in the above statement has been assigned the result of subtracting 15 from 87. As a result, we are only capable of entering values in the same data type that we entered before the variable name when assigning values to the variables. For illustration, the data type of the aforementioned sub variable is int. As a result, integer values should be used to represent the value of the sub variable. If not, an error will be generated.

Multiline comments are used to explain code and make it more readable, and can be declared in any language. They are not executed when running the code. There are two types of comments: single-line comments, which can be written in a single line, and multiline comments, which can be used multiple times.

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

The stdio.h header file contains the standard function printf, which prints prepared texts.

The format specifier %i is used in the C programming language. The type is specified as integer by %i. In C, format specifiers are used to accept inputs and output a variable's value. We employ the symbol % in each and every format specifier. Format specifiers provide information to the compiler about the kind of variable that has to be displayed on the screen. Therefore, we should utilise the name of the associated variable after specifying the format specifier and separate the prepared text with a comma.

return 0;

A return statement terminates a function's execution, transferring control to the calling function, typically indicating successful execution with a return 0; statement.


We hope you now understand exactly how the foregoing code functions.Let's try a few more codes next.


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

Let's analyse each line of the program above to identify any syntactical mistakes.

Line 01 - No error.It is written in correct form.

Line 02 - 'Void' should be written in lowercase instead.As C language is a case sensitive language all keywords in this language are written in lowercase.

Line 03 - In the main function, '{' (curly braces) should be used as the starting parenthesis instead of '(' (Brackets)

Line 04 - 'INT' should be corrected as 'int' as it is a data type in C language.All the data types in C language is written in lowercase.

Line 05 - A multiline comment has being opened successfully but yet it hasn't closed.Therefore, you can closed the comment properly by using */.

Line 06 - Missing ';' at the end of the statement.Therefore, it should be 'sum = 25 + 37 - 19;'

Line 07 - Here again the programmer had taken a proper start for a comment but an incomplete ending.It should be correct as '/*DISPLAY RESULT*/.

Now let's hop into the correct version of the above code.

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

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

Two integer variables, response and result, are initialized in this program. This can also be written as separate statements for "int answer;" and "int result;".The answer is assigned a value of 100, and the result is assigned the answer minus 10, which is 90. After that, the outcome of result + 5 is printed.

The result of this program would be:


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


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


  • 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

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;

}

Our program is linked to the stdio.h header file by the first statement. The primary function is int main (void), which commences the execution of our program. The space between the opening and closing braces indicates the primary function's scope. The variable declaration seen in the first sentence changed right after the braces, char c, d;, is altered. It indicates that there are two character variables: c and d. indicating that they keep a single character in storage. The variable initialization is done in the following statement, c='d';. The character d is assigned to the variable c in this instance. Initializing the value in variable c into variable d is what happens in the following statement, which is also a variable initialization. The value of the variable d is shown in the printf statement, and the program's successful execution is indicated by returning 0 in the return statement.

Therefore the outcome of the above program is d.


Moving further, we would like to talk about a few questions associated with mathematical operations for your further knowledge.

Question 7 –  Convert given value in Meter to centimeter.

Source code :-

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

A length value in meters is converted to centimeters using this C program. The first two float variables declared are meterValue and centimeterValue, with initial values of 0.0. Using printf(), the application asks the user to enter a value in meters. The input value is then read using scanf() and saved in the meterValue variable. The result is then assigned to the centimeterValue variable. First, it multiplies the input value by 100 to determine the equivalent value in centimeters, as one meter is equal to 100 centimeters. Lastly, it uses printf() to format the original number in meters and the corresponding value in centimeters, displaying two decimal places. With a return result of 0, the program then ends.



Question 8 –  Calculate the volume of a cylinder. PI * r2 h

Source code :-
#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;
}
This C programs uses the height and radius that the user enters to get the volume of a cylinder. The three float variables—height, volume, and radius—are declared first and set to 0.0 initially. The application then uses printf() to display the relevant messages and asks the user to enter the cylinder's height and radius, accordingly. Using scanf(), the user inputs are retrieved and saved in the variables height and radius.Next, the program determines the cylinder's volume using the following formula.3.1459 is the approximation of π that is utilized in this application. The variable volume contains the computation's result.Using printf() and the format specifier %.4f to display the value with four decimal places, the program finally prints the estimated volume. Since the main function is intended to return an integer, it then returns 0, signifying that the operation was accomplished.

 


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

Source Code :-
#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;
}  

The purpose of this C program is to find the average of the marks received in the four subjects. First, it declares five float variables (mark1, mark2, mark3, mark4, and average), all of which are initialized to 0.0. Next, it uses printf() to display specific messages for each subject and prompt the user to enter the marks received in each of the four subjects. The user input is then read by scanf() and saved in the corresponding variables (mark1, mark2, mark3, and mark4). Finally, the program computes the average of the marks by adding the marks received in all four subjects and dividing the total by four. The final average is saved in the average variable.This program gives a straightforward method for calculating a student's average marks across four subjects. Lastly, it prints the calculated average using printf() with the format specifier %.2f to display the value with two decimal places. It then returns 0, indicating successful execution, since the main function is declared to return an integer.




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

Source Code :-
#include <stdio.h>
int main()
{

          float celciusValue = 0.0f, fahrenheitValue = 0.0f;
          printf("Enter the temperature value in Celcius : ");
          scanf("%f", &celciusValue); 
          fahrenheitValue = (celciusValue*1.8)+32;
          printf("%.2f Celcius is equal to %.2f Fahrenheit\n", celciusValue,fahrenheitValue);
          return 0;
}


A temperature value can be converted from Celsius to Fahrenheit using this C program. Two float variables, celciusValue and fahrenheitValue, are declared first and initialized to 0.0. Printf() is used by the program to ask the user to provide a temperature value in Celsius. Next, it uses scanf() to read the input value and stores it in the celciusValue variable. Next, it applies the calculation fahrenheitValue = (celciusValue * 1.8) + 32 to determine the corresponding temperature value in Fahrenheit. The fahrenheitValue variable holds the result. Lastly, the program uses printf() to output the temperature in Fahrenheit as well as the initial temperature value in Celsius. The two numbers are displayed with two decimal places using the format specifier %.2f.The primary function is then declared to return an integer, and the program returns 0, signifying successful execution. A straightforward method of converting temperature readings from Celsius to Fahrenheit is offered by this program.



 

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

Source Code :-

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


With a given value for x, this C program determines the value of a variable called y. The first step is to declare two float variables, x and y, and set x's initial value to 5.23. Next, it uses the equation 3.5*x + 5 to assign a value to y. The calculation of this statement is 3.5 times the value of x + 5. The variable y contains the computed value.Following the calculation, the program uses printf() to output the value of y with three decimal places, format specifier %.3f. The value of y is indicated in the printed message.Finally, since the main function is intended to return an integer, the program returns 0, signifying that it has executed successfully.



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

Source Code :-

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



Using the quantity and unit pricing of the products as inputs, this C program determines the total cost of the things. The first three variables declared are items, unitPrice, and cost; unitPrice and cost are floats, and items is an integer. printf() is used by the program to ask the user to enter the number of items. scanf() is then used to read the input value and store it in the items variable. In a similar manner, it uses printf() to ask the user to enter the unit price, scanf() to read the result, and then puts it in the unitPrice variable.Subsequently, the computer multiplies the number of things (items) by the unit price (unitPrice) to determine the overall cost (cost). The cost variable contains the result.Following the computation, the program uses printf() to output the cost with two decimal places, format specifier %.2f. The whole cost is displayed in the printed message.




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

Source Code :-

#include <stdio.h>

int main()

{

              char name[25]="";

              char gender[10]="";

              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;

}



The Body Mass Index (BMI) is computed by this C program using user-supplied data, including name, gender, height, and weight. The first step includes creating multiple variables: height, weight, and BMI are declared as floats, and name and gender are declared as character arrays to hold the user's name and gender, respectively. printf() is used by the program to prompt the user for their name, gender, height, and weight. Using scanf(), it reads each input value and places it in the appropriate variable.The computer program uses the formula BMI = weight / (height * height) to determine the user's BMI after receiving their input. The outcome is kept in the BMI variable.
Lastly, this program uses printf() to output the user's name, gender, and computed BMI. %s and %.4f are format specifiers.The character arrays and the BMI value with four decimal places are displayed using 4f, respectively. The primary function is then declared to return an integer, and the program returns 0, signifying successful execution.



Now let's try another 2 similar questions.


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


Source Code :-

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

Hope you clearly understand how the above code, cause we have already solved similar problem in question 7.


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.

Source Code :-
#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 %.2f m.\n",distance);
            return 0;         
}

The output for the above source code is,

We hope now you have a clear and wide knowledge about the basics of C language.We are looking forward to meet you soon in another blog post on C programming.Until then, Good Bye!


Contribution - Nuhansa Rathnayake @NR860 - 7,8,9,10,11,12,13,14,15
                        Parami Ashinsa  @PA805 - 4,5,6
                        Shirani Abeyrathna @SA2582 - 1,2,3

Comments

Popular Posts