Index-1              Index-2              Home Page
Showing posts with label main(void). Show all posts
Showing posts with label main(void). Show all posts

First C Program

Your First C Program

Here, is a Hello World program in C
#include<stdio.h> //Pre-processor directive
void main()  //main function declaration
{
printf("Hello World"); //to output the string on a display
getch ();  //terminating function
}
Here is the code explanation:

Pre-processor directive

#include is a pre-processor directive in 'C.'
#include <stdio.h>, stdio is the library where the function printf is defined. printf is used for generating output. Before using this function, we have to first include the required file, also known as a header file (.h).
You can also create your own functions, group them in header files and declare them at the top of the program to use them. To include a file in a program, use pre-processor directive
#include <file-name>.h
File-name is the name of a file in which the functions are stored. Pre-processor directives are always placed at the beginning of the program.

The main function

The main function is a part of every 'C' program. We can represent the main function in various forms, such as:
  • main()
  • int main()
  • void main()
  • main(void)
  • void main(void)
  • int main(void)
The empty parentheses indicate that this function does not take any argument, value or a parameter. You can also represent this explicitly by placing the keyword void inside the parentheses. The keyword void means the function does not return any value, in this case, the last statement is always getch ().
#include<stdio.h> //Pre-processor directive
int main()  //main function declaration
{
printf("Hello World"); //to output the string on a display
return 0;  //terminating function
}
In the above example, the keyword int means the function will return an integer value. In this case, the last statement should always return 0.

The source code

After the main function has been declared, we have to specify the opening and closing parentheses. Curly brackets { }, indicate the starting and end of a program. These brackets must be always put after the main function. All the program code is written inside these brackets, such as declarative and executable part.
The printf function generates the output by passing the text "Hello World!"
The semicolon ; determines the end of the statement. In C, each statement must end with a semicolon.
So we have successfully installed the compiler and now can begin working in 'C.' We will write a simple program that will say hello to us. Let's start.

How to run C Program

Step 1) Create a new Project
Step 2) In the pop-up,
  1. Select File
  2. Choose the "C/C++ Source"
  3. Click "Go."
Step 3) Continue, by clicking on "Next."
Step 4) To create the new file ,select a "C" file then click on "Next" button to continue.
Step 5) Set the file path by clicking the "..." button, the explorer window permits to create the C file.
Step 6) Select the path of your new C File then its name which has .c extension and save it.
Step 7) Finally, to confirm the C file creation click "Finish."
Step 8) Enter the code, save it and compile it by clicking on the "Build & Run "button.
Here is the result:
 Hello, World! 

Summary

  • The main function is a mandatory part of every 'C' program.
  • To use the functionality of a header file, we have to include the file at the beginning of our program.
  • Every 'C' program follows a basic structure.

C Programming Questions and Answers

// a) If a 5 digit number is input through the keyboard, write a program to print the sum.

#include <stdio.h>

int main(){
   int number, sum = 0, remainder = 0, counter = 0;
   printf("Enter an integer\n");
   scanf("%d", &number);
   while (number != 0){
       remainder = number%10;
       counter += 1;
       sum += remainder;
       number = number/10;
   }
   if(counter == 5){
       printf("Sum of digits of %d.\n", sum);
   }
   else{
       printf("\nIt was not 5 digit number.\n");
   }
   return 0;
}

// b) If a four digit number is input through the keyboard, write a program to find the sum of first and last digit.

#include <stdio.h>

int main(){
   int number, sum = 0, remainder = 0, counter = 0;
   printf("Enter an integer\n");
   scanf("%d", &number);
   while (number != 0){
       remainder = number%10;
       counter += 1;
       if(counter == 1 || counter == 4){
           sum += remainder;
       }
       number = number/10;
   }
   if(counter == 4){
       printf("Sum of digits of %d.\n", sum);
   }
   else{
       printf("\nIt was not 4 digit number.\n");
   }
   return 0;
}

// e) Write a program to show the advantage of using function in a program.

#include <stdio.h>

// a function return total of an array with given size
int sum(int *arr, int size){
    int total = 0;
    for(int i = 0; i < size; i++){
        total += arr[i];
    }
    return total;
}

int main(){
    int number_of_array[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

    int bellow_fifth = 0, all_sum = 0;
    bellow_fifth = sum(number_of_array, 5);
    all_sum = sum(number_of_array, 10);

    printf ("Total of bellow fifth %d\n", bellow_fifth);
    printf ("All total in an array %d\n", all_sum);

    return 0;
}


// Write a program for the addition of all values from an Array.
#include <stdio.h>

// a function return total of an array with given size
int sum(int *arr, int size){
    int total = 0;
    for(int i = 0; i < size; i++){
        total += arr[i];
    }
    return total;
}

int main(){
    int number_of_array[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

    int all_sum = 0;
    all_sum = sum(number_of_array, 10);

    printf("All total in an array %d\n", all_sum);

    return 0;
}

// a) If a 10 digit number is input , write a program to print the sum of all odd digits.

#include <stdio.h>

int main(){
   int number, sum = 0, remainder = 0, counter = 0;
   printf("Enter an integer\n");
   scanf("%d", &number);
   while (number != 0){
       remainder = number%10;
       counter += 1;
       if(remainder%2 != 0){
           sum += remainder;
       }
       number = number/10;
   }
   if(counter == 10){
       printf("Sum of odd digits of %d.\n", sum);
   }
   else{
       printf("\nIt was not 10 digit number.\n");
   }
   return 0;
}

// b) If a four digit number is input through the keyboard, write a program to find the sum of first and last digit.

#include <stdio.h>

int main(){
   int number, sum = 0, remainder = 0, counter = 0;
   printf("Enter an integer\n");
   scanf("%d", &number);
   while (number != 0){
       remainder = number%10;
       counter += 1;
       if(counter == 1 || counter == 4){
           sum += remainder;
       }
       number = number/10;
   }
   if(counter == 4){
       printf("Sum of digits of %d.\n", sum);
   }
   else{
       printf("\nIt was not 4 digit number.\n");
   }
   return 0;
}

// e) Write a program to check a prime number between 1 and 100.

#include <stdio.h>
int main(){
    for(int i = 1; i < 101; i++){
        int flag = 1;
        for(int m = 2; m < i; m++){
            if(i%m == 0){
                flag = 0;
                break;
            }
        }
        if(flag == 1){
            printf("This is a prime number %d\n", i);
        }
    }
    return 0;
}


// f) Write a program for the addition of all even values from an integer Array.

#include <stdio.h>

// a function return total of even from an array
int sum(int *arr, int size){
    int total = 0;
    for(int i = 0; i < size; i++){
        if(arr[i]%2 == 0){
            total += arr[i];
        }
    }
    return total;
}

int main(){
    int number_of_array[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

    int all_sum = 0;
    all_sum = sum(number_of_array, 10);

    printf("All total in an array %d\n", all_sum);

    return 0;
}

Do-While :

a do while loop is a control flow statement that executes a block of code at least once, and then repeatedly executes the block, or not, depending on a given Boolean condition at the end of the block.

Syntax:

do{
statement(s);
}
while (Boolean condition)

Example:
do{
run();
}
while(edge)


While loop:

 a while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition.
Syntax:
while( Boolean condition) {
   statement(s);
}

Example:
while (edge)
{
run();
}


For loop:

for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times.

Syntax:

for ( init; condition; increment ) {
   statement(s);
}

#include <stdio.h>
 
int main () {
 
   int a;
         
   /* for loop execution */
   for( a = 10; a < 20; a = a + 1 ){
      printf("value of a: %d\n", a);
   }
 
   return 0;
}



Pointer and Arrays

When an array is declared, compiler allocates sufficient amount of memory to contain all the
elements of the array. Base address i.e address of the first element of the array is also
allocated by the compiler. Suppose we declare an array arr,

int arr[5] = { 1, 2, 3, 4, 5 };

Assuming that the base address of arr is 1000 and each integer requires two bytes, the five
elements will be stored as follows:


Here variable arr will give the base address, which is a constant pointer pointing to the first
element of the array, arr[0]. Hence arr contains the address of arr[0] i.e 1000. In short, arr has two purpose - it is the name of the array and it acts as a pointer pointing
towards the first element in the array. arr is equal to &amp;arr[0] by default

We can also declare a pointer of type int to point to the array arr.
int *p;
p = arr;

// or,

p = &amp;arr[0]; //both the statements are equivalent.

Now we can access every element of the array arrusing p++ to move from one element to
another


Switch :

switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each switch case.

Syntax

The syntax for a switch statement in C programming language is as follows −
switch(expression) {
 
   case constant-expression  :
      statement(s);
      break; /* optional */
         
   case constant-expression  :
      statement(s);
      break; /* optional */
  
   /* you can have any number of case statements */
   default : /* Optional */
   statement(s);
}

#include <stdio.h>
 
int main () {
 
   /* local variable definition */
   char grade = 'B';
 
   switch(grade) {
      case 'A' :
         printf("Excellent!\n" );
         break;
      case 'B' :
      case 'C' :
         printf("Well done\n" );
         break;
      case 'D' :
         printf("You passed\n" );
         break;
      case 'F' :
         printf("Better try again\n" );
         break;
      default :
         printf("Invalid grade\n" );
   }
   
   printf("Your grade is  %c\n", grade );
 
   return 0;
}
 

Go-to:

goto statement in C programming provides an unconditional jump from the 'goto' to a labeled statement in the same function

Syntax

The syntax for a goto statement in C is as follows −
goto label;
..
.
label: statement;

#include <stdio.h>
 
int main () {
 
   /* local variable definition */
   int a = 10;
 
   /* do loop execution */
   LOOP:do {
   
      if( a == 15) {
         /* skip the iteration */
         a = a + 1;
         goto LOOP;
      }
                 
      printf("value of a: %d\n", a);
      a++;
 
   }while( a < 20 );
 
   return 0;
}



C File I/O

A file represents a sequence of bytes, regardless of it being a text file or a binary file. C programming language provides access on high level functions as well as low level (OS level) calls to handle file on your storage devices. This chapter will take you through the important calls for file management.

Opening Files

You can use the fopen( ) function to create a new file or to open an existing file. This call will initialize an object of the type FILE, which contains all the information necessary to control the stream. The prototype of this function call is as follows −
FILE *fopen( const char * filename, const char * mode );
Here, filename is a string literal, which you will use to name your file, and access mode can have one of the following values −
Sr.No.
Mode & Description
1
r
Opens an existing text file for reading purpose.
2
w
Opens a text file for writing. If it does not exist, then a new file is created. Here your program will start writing content from the beginning of the file.
3
a
Opens a text file for writing in appending mode. If it does not exist, then a new file is created. Here your program will start appending content in the existing file content.
4
r+
Opens a text file for both reading and writing.
5
w+
Opens a text file for both reading and writing. It first truncates the file to zero length if it exists, otherwise creates a file if it does not exist.
6
a+
Opens a text file for both reading and writing. It creates the file if it does not exist. The reading will start from the beginning but writing can only be appended.
If you are going to handle binary files, then you will use following access modes instead of the above mentioned ones −
"rb", "wb", "ab", "rb+", "r+b", "wb+", "w+b", "ab+", "a+b"

 

Closing a File

To close a file, use the fclose( ) function. The prototype of this function is −
int fclose( FILE *fp );
The fclose(-) function returns zero on success, or EOF if there is an error in closing the file. This function actually flushes any data still pending in the buffer to the file, closes the file, and releases any memory used for the file. The EOF is a constant defined in the header file stdio.h.
There are various functions provided by C standard library to read and write a file, character by character, or in the form of a fixed length string.

 

Writing a File

Following is the simplest function to write individual characters to a stream −
int fputc( int c, FILE *fp );
The function fputc() writes the character value of the argument c to the output stream referenced by fp. It returns the written character written on success otherwise EOF if there is an error. You can use the following functions to write a null-terminated string to a stream −
int fputs( const char *s, FILE *fp );
The function fputs() writes the string s to the output stream referenced by fp. It returns a non-negative value on success, otherwise EOF is returned in case of any error. You can use int fprintf(FILE *fp,const char *format, ...) function as well to write a string into a file. Try the following example.
Make sure you have /tmp directory available. If it is not, then before proceeding, you must create this directory on your machine.
#include <stdio.h>
 
main() {
   FILE *fp;
 
   fp = fopen("/tmp/test.txt", "w+");
   fprintf(fp, "This is testing for fprintf...\n");
   fputs("This is testing for fputs...\n", fp);
   fclose(fp);
}
When the above code is compiled and executed, it creates a new file test.txt in /tmp directory and writes two lines using two different functions. Let us read this file in the next section.

 

Reading a File

Given below is the simplest function to read a single character from a file −
int fgetc( FILE * fp );
The fgetc() function reads a character from the input file referenced by fp. The return value is the character read, or in case of any error, it returns EOF. The following function allows to read a string from a stream −
char *fgets( char *buf, int n, FILE *fp );
The functions fgets() reads up to n-1 characters from the input stream referenced by fp. It copies the read string into the buffer buf, appending a nullcharacter to terminate the string.
If this function encounters a newline character '\n' or the end of the file EOF before they have read the maximum number of characters, then it returns only the characters read up to that point including the new line character. You can also use int fscanf(FILE *fp, const char *format, ...) function to read strings from a file, but it stops reading after encountering the first space character.
#include <stdio.h>
 
main() {
 
   FILE *fp;
   char buff[255];
 
   fp = fopen("/tmp/test.txt", "r");
   fscanf(fp, "%s", buff);
   printf("1 : %s\n", buff );
 
   fgets(buff, 255, (FILE*)fp);
   printf("2: %s\n", buff );
   
   fgets(buff, 255, (FILE*)fp);
   printf("3: %s\n", buff );
   fclose(fp);
 
}
When the above code is compiled and executed, it reads the file created in the previous section and produces the following result −
1 : This
2: is testing for fprintf...
 
3: This is testing for fputs...