C Sample programs with explanation

By Nirmal Priyankara



We will discuss the following these topics:

  1. "Hello World!" in C
  2. Get inputs from the user to the program
  3. Sum and Difference of two numbers 
  4. Functions in C
  5. Pointers in C

1. "Hello World!" in C

Sample Code:

#include <stdio.h>
int main() {
    char string[100];
    fgets(string, 100, stdin);
    printf("Hello world\n");
    printf("%s",string);
    return 0;
}
}

Input:

    Welcome to C programming!

Output: 

    Hello World!
    Welcome to C programming!

Code Explanation:

    Line 1: #include<stdio.h> is a header file library that lets us work with input and output functions(like printf()).
 
    Line 2: int main() in here int means that is the code return type. main() is a function in C. The main function returns an integer value, as indicated by the int keyword before the main() function call. The return type of main() must be int as per C convention. Any code included within the curly braces ( { } ) of the main() function will be executed.

    Line 3: char string[100];  Here we created a string. C does not have a string type to easily create string variables. So, You must use the char type and create an array of characters to make a string in C.
 
    Line 4:fgets(string, 100, stdin); fgets() is a function in C. We use this function to get inputs from the user(or from our keyboard). scanf() is also a function and is used for getting inputs as fgets() function. Why do we need two functions to get input? The reason is scanf() is not capable to get sentences (like Hello World!). It can get only one word but fgets() function can get sentences without any problem. So, in fgets() parentheses we have to include the string name, string size, and standard input(stdin). 

    Line 5: printf() is a function used to print outputs to the screen. (remember, every C statement ends with a semicolon) 
 
    Line 6:  printf("%s", string); To print a string in C we have to use a special format specifier(%s). 
 
    Line 7: return 0; this is the end of the main() function. When the program execution is successful, main() typically returns an integer value of 0. A non-zero return value from main() generally indicates an error or some specific condition.




2. Playing with characters

Sample code:

#include <stdio.h>
#include <strings.h>
int main() {
    int inputNum;                       
// 3 
    char inputCharacter;                // N          
    char inputString1[50];              // Hello world!
    char inputString2[10];              // Hello 

    scanf(" %d",&inputNum);
    scanf(" %c", &inputCharacter);
    scanf("\n%[^\n]%*c",inputString1);
    scanf(" %s",inputString2);

    printf("%d\n",inputNum);
    printf("%c\n", inputCharacter); 
    puts(inputString1);
    printf("%s\n",inputString1);
    printf("%s\n",inputString2);  
    return 0;
}

Input:

    3
    Hello world!
    Hello

Output:

    3
    N
    Hello world!
    Hello world!
    Hello

Code explanation:

    Line 1: int inputNum;  Here, we created a variable to store our inputs. this variable is an int-type variable. So, to specify a variable type we have to include the data type (int, float, char) before the variable name.
 
    Line 2: int inputCharacter;  Here, we created a variable again. But this time we will store a character in this variable(a-z, A-Z, digits (0-9), and special characters like !, @, #, etc.)   
    
    Line 3, 4: char inputString1[10];,
         char inputString2[50];     Here we created two variables. All of these variables' type is char. But here has a difference. C has no string data type like in  Python. Therefore, we use the char data type in C. Also, one thing we should declare size of the string. Try to give some big numbers as the size of the string.
 
    Line 5, 6: scanf("%d", &inputNum); 
          sacnf(“%c”, &inputcharacter);
    We used scanf() function. Using this function, we can get inputs from our keyboard or user. this function is like printf() function. we have to include what are we going to get the data type in double quotes ("%d" or "%f" or "%c" or "%s"). Also, we must use the reference operator (“&”) before the variable name(&inputNum). That stores the memory address of the variable.

 

     Line 7: scanf("\n%[^\n]%*c",inputString1);   This is a way to use for getting multiple words using scanf() function from the user or keyboard. I mentioned earlier that the sacnf() function is capable to get one word. But, If we can modify format specifier(“%s”) like this(“\n%[^\n]%*c”) we can get multiple words.

     Line 8: Like lines 5 and 6.

     Line 11: puts(inputString1);    this puts() function typically use for printing string. In this function, we do not need to give data type as printf() function. And it adds the newline The newline character \n is automatically appended at the end, so puts() always moves to the next line after printing the string.



3. Sum and Difference of two numbers

Sample code:

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
 
int main()
{
    int intNum1;
    int intNum2;
    float floatNum1;
    float floatNum2;
   
    scanf("%d %d",&intNum1,&intNum2);
    scanf("%f %f",&floatNum1,&floatNum2);
   
    int intSum=intNum1+intNum2;
    int intDifference=intNum1-intNum2;
    float floatSum=floatNum1+floatNum2;
    float floatDifference=floatNum1-floatNum2;
   
    printf("%d %d\n",intSum,intDifference);
    printf("%.1f %.1f",floatSum,floatDifference);
   
    return 0;
}

Input

10  4
4.0  2.0

Output

14  6
6.0  2.0

Code explanation:

                   Here nothing to tell especially. But I want to mention these things.
      o   In C we can use “%d” and “%i” format specifiers for integers.
      o   “%.1f” here “.1” represents how many decimal points should add to the answer (like this 6.2, 2.3, …). If you increase this (like this “.2”) it will give two decimal points after the decimal point (2.34, 5.45, 6.67 …). 





4. Functions in C

Sample code:

int max(int a, int b) {
    return a > b ? a : b;   
}
 
int max_of_four(int a, int b, int c, int d) {
    return max(a, max(b, max(c, d)));
}
 
int main() {
    int a, b, c, d;
    scanf("%d %d %d %d", &a, &b, &c, &d);
    int ans = max_of_four(a, b, c, d);
    printf("%d", ans);
   
    return 0;
}

Input

2 13 6 20

Output

20

Code explanation: 

Here I created two functions. max() and max_of_four(), these functions has a return type(int).

Line 1:  In the max() function I included two parameters for finding the max number from those two numbers.
    Note: now I show you a structure of a sample function.

                    void myFunction( ) {
                                            // code to be executed
                                           }
Line 2:  This line I created if, else condition. In C have two types to write if, and else statements. Now I show you guys,

    Type 1 - if (a > b) {
                                   return a;
                               }
                                else {
                                    return b;
                                }

    Type 2- variable=(condition) ? expression True: expression False;

                                 answer=(a > b) ? a : b;
                                 return answer;
                                          or
                                 return (a > b) ? a: b;




5. Pointers in C

Sample code:

#include <stdio.h>
#include <stdlib.h>
 
void update(int *x,int *y) {
    int t1, t2;
    t1 = *x + *y;
    t2 = abs(*x - *y);
    *x = t1;
    *y = t2;
}
 
int main() {
    int a, b;
    int *pa = &a, *pb = &b;
   
    scanf("%d %d", &a, &b);
    update(pa, pb);
    printf("%d\n%d", a, b);
 
    return 0;
}

Input

5
7

Output

12
2

Some explanation about pointers: 

This is a good example to learn C pointers. You can think about Pointers as datatype types like int, char, etc. int works with hole numbers, char is working with characters, double works with decimal numbers, So, pointers work with memory address.

1. how to get a memory address

int myNumber = 20;
Printf(“%d”, myNumber); // this will display 20
Printf(“ myNumber’s memory address : %p” &myNumber); /* this will display myNumber variable memory address(“0x7ffe22319724” this value depends on your computer)*/

2. how to define a pointer variable

int myNumber = 20;
int* pMyNumber = &myNumber;
// pMyNumber is the pointer variable name here
printf(“%p”, &myNumber);   // (“0x7ffe22319724”)
printf(“%p”, pMyNumber);   // (“0x7ffe22319724”)

3. differencing pointers

int myNumber = 20;
int* pMyNumber = &myNumber;
printf(“%p” , &myNumber);   // (“0x7ffe22319724”)
printf(“%p” , pMyNumber);   // (“0x7ffe22319724”)
printf(“%d” , *pMyNumber);  // 20

4. good to know :

int myNumber = 20;
int* pMyNumber = &myNumber;
printf(“%d” , *pMyNumber);  // 20
printf(“%d” , &*pMyNumber);  // 0x7ffe22319724
printf(“%d” , *&*pMyNumber);  /* 20 (you can do this multiple times &*&*&*&*&*&*&*&*&*&*…)*/

 

Code explanation: 

                   

                                   Our computer storage

  1. Using our pointers knowledge, we can create two pointer variables (pa, pb).
  2. After the scanf()  function get user input and store that data in a and b variables (using the pointer variables (pa, pb) or (&a, &b)
  3. After that, we give those memory addresses to update the () function as arguments using the pointers((&a, &b) or (pa, pb))
  4. update() function: Here, we give two parameters for this function. also, we created two pointer variables (x and y) again. So, the function will detect arguments (pa, pb) and give those new names for that pointer variables like (x and y). So, now pa=x and pb=y, function go to those variables using this memory address. After that using dereference operator (“*”) function read what are the values in those variables (a, b). After getting those values, the function will generate answers using our commands. And function again put the final answers in the variables.
  5. After that printf() function displays those answers using a and b variables       


Summary:

Here, I explained five examples with sample code and explanation. Actually, these questions are on HackerRank website. If you could not solve these problems refer this article.



















Comments

Popular Posts