Wednesday, June 3, 2015

C program to shutdown a windows pc


The c program given below is able to shutdown a windows pc. When you will run the program, then you will be asked to provide your choice. Actually a message Shutdown PC? (Y/N): will appear on the command prompt box.

That means you have press Y or N. If you press y (both in small and capital letter will do the same), then the computer system will shut down soon. But if you press n, then another message will be displayed. Similarly if you press anything else except y/n then another message will be displayed.
//This C program is able to shutdown a Windows PC
//But you have to decide by pressing y/Y
#include <stdio.h>
#include <stdlib.h>

int main(){
    //Declaring variable
    char decision;

    //Displaying message
    printf("Shutdown PC? (Y/N): ");

    //Getting decision
    scanf("%c", &decision);

    //Taking action
    if(decision == 'y' || decision == 'Y'){
        system("C:\\WINDOWS\\System32\\shutdown /s");
    } else if(decision == 'n' || decision == 'N'){
        printf("Okay, close the window!\n\n");
    } else {
        printf("You haven't pressed Y/N\n\n");
    }

    return 0;
}

Let's see how the above program works!
1. The first two lines of the program is just comments. Similarly all other lines started with double slash (//) is considered as comments.

2. In the third and fourth line there I have included two header files names stdio.h and stdlib.h
Learn what is header file in c programming.

3. In the sixth line there has started the main function of the c program and ended at the line number 26.

4. In the eighth line there I have declared a character type variable named decision, where the decision flag character will be stored after providing by a user. And depending on this flag character, the rest of the codes will be executed.

5. By the 10th line the program will simply display a message to input the choice of the user. And by the 14th line the input will be stored into the variable decision.

6. In the 17th line there is an if condition that will first check if there is y or Y into the variable. If there found y into the variable, then the 18th line will be executed and the computer will shut down soon. Similarly by the 19th line it will checked if there is n or N into the decision variable. If found then the message from the 20th line will be displayed.

Otherwise, the message from the 22nd line will be displayed.

Advertisement

No comments:

Post a Comment