Coding for DUMMIES 04 : Constants and Operators





 If you have following us since our first post , now you have really good idea about C language basics. today let's peek into little bit of the depth of C programming. type casting, constants and operators of C programming language. In every programming language there are data types so computer can understand which type of data you have entered. In C there are 4 basic data types, 
  • int - integer
  • char - character
  • float - floating point number
  • double - double precision numbers
sometimes we might needs to convert the data type to another and we can feed instructions to the compiler to do that for us. this is called type cast and lets peek into it using the below code.

      

#include <stdio.h>

int main() 

{

int sum = 17, count = 5;

double mean;

mean = sum / count;

printf("Value of mean : %f\n", mean );

return 0;

}

 I hope you remember about the #include and printf function from our previous posts and incase if you font remember we recommend you you to go and understand about it using here. and if you well known about these functions congratulations you are now have good knowledge about basics of c programming language. now if you analyze the above code you can see that it is used to find the mean of two numbers. in here sum and count are two integer variables and mean is double data type variable. now if we get the output of this code it will be 3.000000 s and that because integer values of sum and count is gong to get stored inside of mean. but can type cast this to double values as folows , 


#include <stdio.h>
int main() 
{
    int sum = 17, count = 5;
    double mean;
    
    mean = (double) sum / count;
 
    printf("Value of mean : %f\n", mean );
    return 0;
}

  In here both sum and count is promoted into the double so output will be 3.400000 .

And when one type of data is assigned to another type of variable, an automatic type promotion will be taken place. for an automatic promotion there are some conditions to be met,

  • The two types should be compatible.
  • destination type should be larger than the source type.
by large this mean that how much bytes a type can store. for an example char type can only store 1 byte and int can store 4bytes. so we can store char value in a int but we cannot store int value in char data type. see the following code to get an idea about automatic promotion.

                        #include <stdio.h>

int main() 

{

int i = 17;

char c = 'c'; /* ascii value is 99 */

int sum;

sum = i + c;

printf("Value of sum : %d\n", sum );

return 0;

}      

  int above code variable i is an integer variable and 17 is assigned to the i. and variable c is a char variable and character c is stored inside of it. now bear in mind ASCII value equitant to character 'c' is 99. for the integer variable sum , summation of i and c are assigned . now when we get the output of this code output will be 116 which is summation of value 99 and 17. this happens because instead of character 'c' ASCII value of c promoted to the sum promoting chanter variable to an integer variable.

Typical arithmetic conversion.


    in an arithmetic operation when they have different types  compiler performs integer promotion casting their values to a common type.

                        #include <stdio.h>

int main (void)

{

float f1 = 123.125, f2;

int i1, i2 = -150;

char c = 'a';

/* floating to integer conversion */

i1 = f1;

printf ("%f assigned to an int produces %i\n", f1, i1);

/* integer to floating conversion */

f1 = i2;

printf ("%i assigned to a float produces %f\n", i2, f1);

/* integer divided by integer */

f1 = i2 / 100;

printf ("%i divided by 100 produces %f\n", i2, f1);

/* integer divided by a float */

f2 = i2 / 100.0;

printf ("%i divided by 100.0 produces %f\n", i2, f2);

/* type cast operator */

f2 = (float) i2 / 100;

printf ("(float) %i divided by 100 produces %f\n", i2, f2);

return 0;

}



 looking at the above output and the code we believe you have an idea about typical arithmetic conversion. Incase you do not, what here happened was in the 8th line floating variable is assigned to the integer type variable. and when getting output output is coming out as an integer value. that is why the value 123.125000 is conversed in to the 123. as same all other types are converted in to the assigned common type.

Command line arguments.

  In C programming it is possible to pass arguments using the command prompt when they are executed. In here inside of the main funtion int argc, char* argv[] is used inside the brackets. argc means argument count and and argv means argument variable. argc count refers number of argumets passed and * mark in argv is an pointer array which points each arguments passed to the program. now lets get into the coding.

                        #include <stdio.h>

int main( int argc, char*argv[] )

{

printf("The first argument supplied is %s\n",argv[0]);

printf("The second argument supplied is%s\n",argv[1]);

return 0;

}

Now if you run this code in the Quincy what you will is following 


 in here the second argument supplied is null because we haven't given any argument and argv[0] is always the location of the exe file. now for us to give argument we need to run this using command prompt. 

to do that in Quincy go to tools> command prompt.

so the 1st argument we should supply is file_name.exe and second is the argument you want to use. in here we used cars as the second argument.

so for this command output will be as follows,

Try changing arguments and argv[] number as your choice for practice command line arguments.

Defining Constants in C language


    there are many constants in C language and we need to define a constant to use it in our program. there are 2 methods of defining a constant and following is the 1st method

                        #include <stdio.h>

#define PI 3.1412

int main ()

{

float radius;

printf ("Enter the radius in mm : \n");

scanf ("%f",&radius);

printf("The perimeter is : %.2f", 2*PI*radius);

return 0;

}

In here using #define defines the constant. as you can see above constant called PI is defined at the value 3.1412 . the other method of defining a constant is to define it as same as variable declaration using the keyword const

          #include <stdio.h>

int main ()

{

const float PI = 3.1412;

float radius;

printf ("Enter the radius in mm : \n");

scanf ("%f",&radius);

printf("The perimeter is : %.2f", 2*PI*radius);

return 0;

}

It is good practice of programming to use capital letters when defining a constant, 

when using second method syntax is 

                    const <data_type> <identifier> = <value>;


I hope you remember that <stdio.h> is a header file that contain instructions to the compiler about input and output functions. just like that there are many header files that can be used in C programming. you can refer them by here. from those various header files lets talk about special one that called math.h . this header file is used to do math functions. there are so many functions that can be used in this header file and following is a code that used math.h functions.

                        #include <stdio.h>

#include <math.h>

int main ()

{

printf("Value 8.0 ^ 3 = %.2lf\n", pow(8.0, 3));

printf("Sqrt of 100 = %.2f\n", sqrt(100));

printf("log (100) = %.2f\n", log(100.0));

printf("sin (90) = %.2f\n", sin (90.0));

printf("ceil (10.45) = %.2f\n", ceil(10.45));

printf("floor (10.45) = %.2f\n", floor(10.45));

printf("fabs (-10.45) = %.2f\n", fabs(-10.45));

printf("round (10.45) = %.2f\n", round (10.45));

return(0);

}

 

since  we going to display output first we import stdio.h header file and then we import math.h header file. in this code we can see we used some unfamiliar keywords,

  • pow (x,y) - power of x to the y
  • sqrt (s0 - square root of x
  • log(x) - logarithm of x
  • sin(x) - sin value of x
  • ceil(x) - smallest integer value greater than or equal to x
  • floor(x) - largest integer value less than or equal to x
  • fabs(x) - absolute value of x
  • round(x) - rounded off value of an floating point number to nearest value

following is the output of above code.



Operators in C programming language


    Just like any other programming language C also have operators that can be used in various operations. In c operators have operation precedence and math in programming is different than the calculations in mathematics. As for basics multiplications have priority over and additions and additions have priority over logical operators. now lets get into C operators through the following code,

                        #include <stdio.h>

int main (void)

{

int a = 100;

int b = 2;

int c = 25;

int d = 4;

int result;

result = a - b;

printf ("a - b = %i\n", result);

result = b * c;

printf ("b * c = %i\n", result);

result = a / c;

printf ("a / c = %i\n", result);

result = a + b * c;

printf ("a + b * c = %i\n", result);

printf ("a * b + c * d = %i\n", a * b + c * d);

return 0;

}

This code is about Arithmetic operators in c language. 


There are many was to use arithmetic operations and followings are some of them. make sure to practice them at home for better understand of arithmetic operators.

            1

                        #include <stdio.h>

int main (void)

{

int a = 25;

int b = 2;

float c = 25.0;

float d = 2.0;

printf ("6 + a / 5 * b = %i\n", 6 + a / 5 * b);

printf ("a / b * b = %i\n", a / b * b);

printf ("c / d * d = %f\n", c / d * d);

printf ("-a = %i\n", -a);

return 0;

}

            2

                        #include <stdio.h>

int main (void)

{

int a = 25, b = 5, c = 10, d = 7;

printf ("a %% b = %i\n", a % b);

printf ("a %% c = %i\n", a % c);

printf ("a %% d = %i\n", a % d);

printf ("a / d * d + a %% d = %i\n",a / d * d + a % d);

return 0;

}

now if we look at the above code inside the printf function we can see that %% is used. this is because that % is an format specifier and to display % in printf function we need to use %% .

Logical operators in C language

following code show how logical operators can be used in c language. logical operators are AND , OR and NOT. we use,

&& for logical AND

|| for logical OR

! for logical NOT.


                        #include <stdio.h>

int main()

{

int a = 5;

int b = 20;

int c = 1;

printf( "( a && b ) = %d \n", a && b );

printf( "( a || b ) = %d \n", a || b );

printf( " !a = %d \n", !a );

return 0;

}



since it is logical operators outwill be generated as Boolean value of 1 and 0.

Relational operators in c language       

when editing a code we will need to compare data with each other and for that relational operators will be needed. following is an code consist of each and every relational operators of C language.

                        #include <stdio.h>

int main()

{

int a = 5;

int b = 20;

int c = 5;

printf( "( a < b ) = %d \n", a < b );

printf( "( a <= b ) = %d \n", a <= b );

printf( "( a > b ) = %d \n", a > b );

printf( "( a >= b ) = %d \n", a >= b );

printf( "( c == a ) = %d \n", c == a );

printf( "( a != b ) = %d \n", a != b );

return 0;

}


As you can see here the comparison output is Boolean  value. if the expression is true value 1 will return and if it is false 0 will return.

 Bitwise operators in c language

Bitwise operator works on bits and perform bit-by-bit operation. look following code for the more understanding about the bitwise operators.

                        #include <stdio.h>

int main()

{

int a = 60;

int b = 13;

printf( "( a & b ) = %d \n", a & b );

printf( "( a | b ) = %d \n", a | b );

printf( "( a ^ b ) = %d \n", a ^ b );

printf( "( ~ a ) = %d \n", ~a );

printf( "( a << 2 ) = %d \n", a << 2);

printf( "( a >> 2 ) = %d \n", a >> 2);

return 0;

}



Increment  and decrement operators in c language

following is an increment and decrement operators used in the c code.

                        #include <stdio.h>

int main() {

int a = 21;

int c =10;;

c = a++;

printf( "Line 1 - Value of a and c are : %d - %d\n", a, c);

c = ++a;

printf( "Line 2 - Value of a and c are : %d - %d\n", a, c);

c = a--;

printf( "Line 3 - Value of a and c are : %d - %d\n", a, c);

c = --a;

printf( "Line 4 - Value of a and c are : %d - %d\n", a, c);

return 0;

}




Assignment operators in c language.

do you remember we assigned value to a variable, actually what we have done there was an assignment operation. and when assignment operators are used they will be associated from right to left instead of left to right.

example : A=B this means B is assigned to the A , so that values in B is now stored inside of A.

There are many other assignment operators and look following code to see usage of each and every operators.

                        #include <stdio.h>

int main()

{

int a = 21;

int c ;

c = a;

printf("Line 1 - = Operator Example, Value of c = %d\n", c );

c += a;

printf("Line 2 - += Operator Example, Value of c = %d\n", c );

c -= a;

printf("Line 3 - -= Operator Example, Value of c = %d\n", c );

c *= a;

printf("Line 4 - *= Operator Example, Value of c = %d\n", c );

c /= a;

printf("Line 5 - /= Operator Example, Value of c = %d\n", c );

c = 200;

c %= a;

printf("Line 6 - %= Operator Example, Value of c = %d\n", c );

c <<= 2;

printf("Line 7 - <<= Operator Example, Value of c = %d\n", c );

c >>= 2;

printf("Line 8 - >>= Operator Example, Value of c = %d\n", c );

c &= 2;

printf("Line 9 - &= Operator Example, Value of c = %d\n", c );

c ^= 2;

printf("Line 10 - ^= Operator Example, Value of c = %d\n", c );

c |= 2;

printf("Line 11 - |= Operator Example, Value of c = %d\n", c );

return 0;

}

output will be as follows ,



   Conditional operator in c language

given that A,B,C are expressions , then the expression,

    A? B:C

this means that if A has none-zero value its is B and If A has zero it is C will be selected. 

                        #include<stdio.h>

int main()

{

int num;

int flag;

printf("Enter the Number : ");

scanf("%d",&num);

flag = ((num%2==0)?1:0);

printf ("Flag value : %d \n", flag);

return 0;

}

 now in above code input number divided by 2 and if it remainder is 0 1 will be displayed. if the remainder is 1 , 0 will be displayed. so you can understand that this is a simple program to find out whether a number is odd or even. now  first lets see output if we enter an even value.

now lets see if we entered an odd value , 


sizeof operator in c language

using this operator we can see the size that is used to store and data type.

                        #include<stdio.h>

int main() {

int ivar = 100;

char cvar = 'a';

float fvar = 10.10;

double dvar = 18977670.10;

printf("%d\n", sizeof(ivar));

printf("%d\n", sizeof(cvar));

printf("%d\n", sizeof(fvar));

printf("%d\n", sizeof(dvar));

return 0;

}


since we used syntax sizeof(data_type) here output is how many bytes that has allocated to hold the each data type. 

Comma operator in c language

    comma operator is an very common operators that we have used it in out previous codes too, comma operator can be used to link the related expressions together. a comma linked expression is evaluated from left to right so that on the expression, x = (a = 2 ,b = 4, a+b); compiler first assign number 2 to a and then assign number 4 to the b and then calculate a+b and the answer 6 will be stored inside the x.

                        #include<stdio.h>

int main()

{

int num1 = 1, num2 = 2;

int res, x, a, b;

x = (a = 2, b = 4, a+b);

res = (num1, num2);

printf("%d\n", res);

x = (a = 2, b = 4, a+b);

printf("%d\n", x);

return 0;

}

    Now lets implement our newly learned ideas to some problems. we suggest that to write code on your own before look into the answer and remember in coding there can be many ways to have the same answer.                 

Question 1 - Write a program to evaluate the polynomial shown here:

3x3 - 5x2 + 6 for x = 2.55

answer : 


as you can see that in here we have used math.h header file so we can use power to our code.

output :


Question 2 - Write a program that evaluates the following expression and displays the results (remember to use exponential format to display the result):

(3.31 × 10-8 × 2.01 × 10-7) / (7.16 × 10-6 + 2.01 × 10-8)

answer : 


in this code if you look at closely you can see something you haven't seen much. it is %e format specifier. this format specifier  make sure that output of this code is displayed in exponential form AKA scientific notation. 

output :


Question 3 -  To round off an integer i to the next largest even multiple of another integer j, the following formula can be used:

Next_multiple = i + j - i % j

For example, to round off 256 days to the next largest number of days evenly divisible by a week, values of i = 256 and j = 7 can be substituted into the preceding formula as follows:

Next_multiple = 256 + 7 - 256 % 7

= 256 + 7 - 4

= 259

Write a program to find the next largest even multiple for the following values of i and j: (Use keyboard to input values for i and j)


i

j

365

7

12258

23

996

4

 
answer : 

before we get into coding read this question very carefully, this code says that use keyboard input as values which means we have to input values manually. but there also they have given us  a table consisting answers, this is actually a trick question to make you think and since you have to input values manually you don't really need to care about the table. 
Now we hope you remember how get an keyboard value as input. incase you are not, don't worry we got you covered.
we use scanf();  function to input value from keyboard . but first we need a place to hold the value we going to input , so we going to declare a variable first. 


int input;
scanf ("%i",&input);

after the scanf function we going to use format specifier for integer, which is %i because value we are going to input is an integer. you can see that before the variable name there is '&' mark , this addresses the location of of variable and when we get the input it stores the value at that place.
now lets get into the code,





output :
now lets see the out for for first value in our table 365 and 7,



now you can try other values too.


Question 4 - Write a program to input the radius of a sphere and to calculate the volume of the sphere. Volume = 4/3*pi*radius3

answer :

you can see that in here we have used constant PI and also we have used math.h header file for the power function.

output :

lets take radius as 5cm


Question 5 - 100 spherical ice (cubes) of a given radius are placed in a box of a given width, length and height. Calculate the height of the water level when the ice melts. Neglect the change in volume when ice converts to water.

answer :

        

now if you look at this and previous you can see that same constant is used but they were defined in different ways.

    output :

lets look in to the output for the above code taking radius as 1.5cm, height as 20 cm, width as 10 cm and length as 15cm.

Question 6 - Write a program to input your midterm marks of a subject marked out of 30 and the final exam marks out of 100. Calculate and print the final results. Final Result = Mid Term + 70% of Final Mark.

answer :


output :

lets take mid term marks as 25 and final exam marks as 75


Question 7 - Input the source file and destination file name as command line arguments and print the following message to standard output:

“Copy the details in <file name 1> to <file name 2> at 23.59.59”

answer :

 for this question we will have to get the output using command line arguments.

you can see that we have used argv[] array to get the input from command line .

output :

lets supply Frist argument as my_files and second argument as documents


Question 8 - Input the target rate as command line argument and compute the total commission as follows:

Total commission = ( total sale × 0.2 × target rate ) + cash flow.

Cash flow is a constant.

answer :

 in this question you will have to get command line argument as a input. to do that instead of scanf(); function we are going to use sscanf(); function. this is also same as the scanf function  but the difference is in scanf we get input from the use or from files but in sscanf we get input by parsing values from strings. when using this first we get the value from argv{1} argument and then store it inside a variable.



output :

let see out put if we use target rate as 100

    

       Now we hope you have learned about C operators and how to use them in programming well . so until next make sure to practice programming everyday. practice what makes you a good programmer.


    

     contribution : - Sandakelum Kumarasiri @SK2208 5737- 3,5,9 
                             Ranishka Gunathilake    @RG761 5641 -4,6,8
                             Mahesh Wijenayaka    @MW1513 5734 -  1,2